如何访问 ModelForm 中的请求以添加 request.user 作为外键

发布于 2024-09-18 17:09:02 字数 2295 浏览 15 评论 0原文

我试图覆盖模型表单中的保存以将当前用户添加为车辆的所有者。但我收到“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

‖放下 2024-09-25 17:09:02

这是我最近如何编写视图的简短版本,仅供将来查看。
不需要任何 __init__ 子类化,也不需要重复表单构造函数:

@login_required
def create_vehicle(request):
    form = forms.VehicleForm(data=request.POST or None)
    if form.is_valid():
        form.instance.owner = request.user
        form.save()
        return redirect('vehicles')
    return render(request, 'vehicles/vehicle_create.html', {'form': form})

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:

@login_required
def create_vehicle(request):
    form = forms.VehicleForm(data=request.POST or None)
    if form.is_valid():
        form.instance.owner = request.user
        form.save()
        return redirect('vehicles')
    return render(request, 'vehicles/vehicle_create.html', {'form': form})
彼岸花似海 2024-09-25 17:09:02

我想在 Manoj 和 Daniel 的回复中添加更多信息。基本上我需要一个自定义视图才能在保存时传递用户

urls.py:views.py:forms.py

url(r'^create/

:

@login_required
def create_vehicle(request):
    if request.method == 'POST':
        form = VehicleForm(request.POST)
        if form.is_valid():
            vehicle = form.save(commit=False)
            vehicle.owner = request.user
            vehicle.save()
        return HttpResponseRedirect('/vehicles/')
    else:
        form = VehicleForm()
    return render_to_response('vehicles/vehicle_create.html', {'form': form},     context_instance=RequestContext(request))

class VehicleForm(ModelForm):
    class Meta:
        model = Vehicle
        exclude = ('slug', 'owner', )
, 'create_vehicle', name='vehicle_create'),

:

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:

url(r'^create/

views.py:

@login_required
def create_vehicle(request):
    if request.method == 'POST':
        form = VehicleForm(request.POST)
        if form.is_valid():
            vehicle = form.save(commit=False)
            vehicle.owner = request.user
            vehicle.save()
        return HttpResponseRedirect('/vehicles/')
    else:
        form = VehicleForm()
    return render_to_response('vehicles/vehicle_create.html', {'form': form},     context_instance=RequestContext(request))

forms.py:

class VehicleForm(ModelForm):
    class Meta:
        model = Vehicle
        exclude = ('slug', 'owner', )
, 'create_vehicle', name='vehicle_create'),

views.py:

forms.py:

微暖i 2024-09-25 17:09:02

您没有显示如何在视图中实例化表单。当您这样做时,您需要记住实际传递请求:

def myview(request):
    form = VehicleForm(instance=whatever, request=request)

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:

def myview(request):
    form = VehicleForm(instance=whatever, request=request)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文