如何访问 ModelForm 中的请求以添加 request.user 作为外键
我试图覆盖模型表单中的保存以将当前用户添加为车辆的所有者。但我收到“NoneType”对象没有属性“user” 我忘记了什么?
forms.py:
class VehicleForm(ModelForm):
class Meta:
model = Vehicle
exclude = ('slug', 'owner', )
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(VehicleForm, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
kwargs['commit']=False
obj = super(VehicleForm, self).save(*args, **kwargs)
obj.owner = self.request.user
obj.save()
return obj
我的模型:
class VehicleBase(models.Model):
owner = models.ForeignKey(User)
vehicle_type = models.SmallIntegerField(_('kind'),
choices=vehicle_types, default=1,)
make = models.CharField(_('make'), max_length=31,
help_text=_('Maximum is 31 characters.'), )
model = models.CharField(_('model'), max_length=31,
help_text=_('Maximum is 31 characters.'), )
class Meta:
abstract = True
class Vehicle(VehicleBase):
name = models.CharField(_('fun name'), max_length=31,
help_text=_('Maximum is 31 characters.'), )
slug = models.SlugField(_('slug'), )
def save(self, *args, **kwargs):
is_new = self.pk is None
if is_new:
self.slug = slugify("%s %s %s" %(self.make, self.model, self.name, ))
super(Vehicle, self).save(*args, **kwargs) # Call the "real" save() method.
if is_new:
Calendar.objects.get_or_create_calendar_for_object(self, name = "%s's schedule" %self.name)
class Meta:
unique_together = (("name", "owner", ), )
def __unicode__(self):
return u'%s: %s\'s %s %s' %(self.name, self.owner, self.make, self.model, )
def __str__(self):
return self.__unicode__()
def get_absolute_url(self):
return reverse('vehicle_view', kwargs={'object_id':self.id, 'slug':self.slug, }, )
我正在使用通用视图:
url(r'^create/$',
'create_update.create_object',
dict(template_name='vehicles/vehicle_create.html',
form_class=VehicleForm,
post_save_redirect="/vehicles/"),
name='vehicle_create'),
I am trying to override save in the modelform to add the current user as the owner of a vehicle. But I am receiving 'NoneType' object has no attribute 'user'
What am I forgetting?
forms.py:
class VehicleForm(ModelForm):
class Meta:
model = Vehicle
exclude = ('slug', 'owner', )
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(VehicleForm, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
kwargs['commit']=False
obj = super(VehicleForm, self).save(*args, **kwargs)
obj.owner = self.request.user
obj.save()
return obj
my model:
class VehicleBase(models.Model):
owner = models.ForeignKey(User)
vehicle_type = models.SmallIntegerField(_('kind'),
choices=vehicle_types, default=1,)
make = models.CharField(_('make'), max_length=31,
help_text=_('Maximum is 31 characters.'), )
model = models.CharField(_('model'), max_length=31,
help_text=_('Maximum is 31 characters.'), )
class Meta:
abstract = True
class Vehicle(VehicleBase):
name = models.CharField(_('fun name'), max_length=31,
help_text=_('Maximum is 31 characters.'), )
slug = models.SlugField(_('slug'), )
def save(self, *args, **kwargs):
is_new = self.pk is None
if is_new:
self.slug = slugify("%s %s %s" %(self.make, self.model, self.name, ))
super(Vehicle, self).save(*args, **kwargs) # Call the "real" save() method.
if is_new:
Calendar.objects.get_or_create_calendar_for_object(self, name = "%s's schedule" %self.name)
class Meta:
unique_together = (("name", "owner", ), )
def __unicode__(self):
return u'%s: %s\'s %s %s' %(self.name, self.owner, self.make, self.model, )
def __str__(self):
return self.__unicode__()
def get_absolute_url(self):
return reverse('vehicle_view', kwargs={'object_id':self.id, 'slug':self.slug, }, )
I am using a generic view:
url(r'^create/
,
'create_update.create_object',
dict(template_name='vehicles/vehicle_create.html',
form_class=VehicleForm,
post_save_redirect="/vehicles/"),
name='vehicle_create'),
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是我最近如何编写视图的简短版本,仅供将来查看。
不需要任何
__init__
子类化,也不需要重复表单构造函数:Here's a shorter version of how I'd write the view these days, just for future eyes.
No need for any
__init__
subclassing, and no repetition of the form constructor:我想在 Manoj 和 Daniel 的回复中添加更多信息。基本上我需要一个自定义视图才能在保存时传递用户
urls.py:views.py:forms.py
:
:
I wanted to add a little more info to Manoj's and Daniel's responses. Basically I needed a custom view in order to pass in the user on save:
urls.py:
views.py:
forms.py:
您没有显示如何在视图中实例化表单。当您这样做时,您需要记住实际传递请求:
You don't show how you are instantiating the form in your view. You need to remember to actually pass the request in when you do so: