在保存视图时设置user_id - Django [英] Setting user_id when saving in view - Django
问题描述
我需要在添加视图中设置正在创建帖子的用户:
I need to set the user that is creating the post in the add view:
@login_required
def add(request):
if request.method == 'POST':
form = BusinessForm(request.POST)
form.user_id = request.user.id
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('listing.views.detail'), args=(f.id))
else:
form = BusinessForm()
return render_to_response('business/add.html', {'form':form},
context_instance=RequestContext(request))
我分配了用户ID form.user_id = request.user.id
,但保存时,仍然给我一个错误列user_id不能为空
I assign the user id form.user_id = request.user.id
but when saving, it still gives me an error Column user_id cannot be null
我做错了吗?谢谢
编辑:
我从模型中的表单中排除用户:
I am excluding the user from the form in the model:
class BusinessForm(ModelForm):
class Meta:
model = Business
exclude = ('user',)
可能导致问题?如何解决这个问题?
Could that be causing the problem?? How can I work around this?
编辑2:
根据建议编辑了我的BusinessForm()类,但是不工作:
Edited my BusinessForm() class as suggested but did not work:
class BusinessForm(ModelForm):
class Meta:
model = Business
exclude = ('user',)
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
return super(BusinessForm, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
kwargs['commit']=False
obj = super(BusinessForm, self).save(*args, **kwargs)
if self.request:
obj.user = self.request.user
obj.save()
商业模式
class Business(models.Model):
name = models.CharField(max_length=200)
user = models.ForeignKey(User, unique=False)
description = models.TextField()
category = models.ForeignKey(Category)
address = models.CharField(max_length=200)
phone_number = models.CharField(max_length=10)
website = models.URLField()
image = models.ImageField(upload_to='business_pictures',blank=True)
推荐答案
p>您不必为此使用 init
或 save
覆盖。
You don't have to use init
or save
overrides for this.
您只是在表单上设置一个属性,表单不会对其进行任何操作。它不会像模型实例那样神奇地表现(您的表单不会有 user_id
属性)。
You're just setting an attribute on your form and the form doesn't do anything with it. It doesn't magically behave like a model instance (your form wouldn't have a user_id
attribute).
由于您的表单是 ModelForm
,您只需使用 commit = False
获取未保存的实例,设置用户,然后在实例上调用 save
。
Since your form is a ModelForm
, you can simply call save on it with commit=False
to get the unsaved instance, set the user, then call save
on the instance.
if request.method == 'POST':
form = BusinessForm(request.POST)
if form.is_valid():
business = form.save(commit=False)
business.user = request.user
business.save()
这篇关于在保存视图时设置user_id - Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!