*任何时候我插入数据都会发生上述错误! *
# my views
def new_topic(request):
"""Add a new topic."""
if request.method != 'POST':
# No data submitted; create a blank form.
form = TopicForm()
else:
# POST data submitted; process data.
form = TopicForm(request.POST or None, request.FILES or None)
if form.is_valid():
new_topic = form.save(commit=False)
new_topic.owner = request.user #this where i think, i'm messing up!
new_topic.save()
return HttpResponseRedirect(reverse('learning_logs:topics'))
context = {'form': form}
return render(request, 'learning_logs/new_topic.html', context)
*代表每个主题的模型* 来自django.contrib.auth.models导入用户
def upload_location(instance, filename):
return "%s/%s" %(instance.id, filename)
class Topic(models.Model):
"""A topic the user is learning about"""
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
image = models.ImageField()
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
owner = models.ForeignKey(User)
def __str__(self):
"""Return a string representation of the model."""
return self.text
请帮忙!
答案 0 :(得分:1)
如果用户已登录,则设置new_topic.owner = request.user
应该没问题。但是,如果用户未登录,则尝试分配匿名用户会导致问题。
您可以使用login_required
装饰器来阻止此操作,以便只有登录用户才能访问该视图。
@login_required
def new_topic(request):
...