【发布时间】:2012-02-25 00:26:57
【问题描述】:
我目前正在开发我的第一个 Django 应用程序,它允许注册用户通过基本表单提交内容。
到目前为止,它有一个警告:当显示表单时,会向用户(“作者”)显示所有用户的下拉列表,而不是使用用户名自动填充该字段。这显然是不能接受的。
此目标是让注册用户的姓名自动填充表单。我已经看到了一些针对类似问题的各种潜在解决方案,但没有任何东西可以解决这个具体问题。
我尝试将模型中的 Author 字段设置为“unique=True”,但在迁移时导致数据库错误。
任何见解将不胜感激:
型号:
class Story(models.Model):
title = models.CharField(max_length=100)
topic = models.CharField(max_length=50)
copy = models.TextField()
author = models.ForeignKey(User)
zip_code = models.CharField(max_length=10)
latitude = models.FloatField(blank=False, null=False)
longitude = models.FloatField(blank=False, null=False)
date = models.DateTimeField(auto_now=True, auto_now_add=True)
def __unicode__(self):
return " %s" % (self.title)
表格:
class StoryForm(forms.ModelForm):
class Meta:
model = Story
查看:
@login_required
def submit_story(request):
if request.method == "GET":
story_form = StoryForm()
return render_to_response("report/report.html",
{'form': story_form},
context_instance=RequestContext(request))
elif request.method =="POST":
story_form = StoryForm(request.POST)
if story_form.is_valid():
new_story = Story()
new_story.title = story_form.cleaned_data["title"]
new_story.topic = story_form.cleaned_data["topic"]
new_story.copy = story_form.cleaned_data["copy"]
new_story.author = request.user
new_story.zip_code = story_form.cleaned_data["zip_code"]
new_story.latitude = story_form.cleaned_data["latitude"]
new_story.longitude = story_form.cleaned_data["longitude"]
new_story.save()
return HttpResponseRedirect("/report/all/")
else:
story_form = StoryForm()
return render_to_response("report/report.html",
{'form': story_form},
context_instance=RequestContext(Request))
编辑:我想我找到了相对简单的答案:我只是从表单中删除了“作者”字段并保持视图不变。我可以通过这种方式以注册用户的名义发帖。我认为这可行,除非我不知道(很多)是不正确或错误的协议。
【问题讨论】:
标签: django django-models django-forms