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

时间:2010-09-08 08:33:11

标签: django override save foreign-key-relationship modelform

我正在尝试覆盖模型中的保存,以将当前用户添加为车辆的所有者。但我收到'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'),

3 个答案:

答案 0 :(得分:3)

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

urls.py:

url(r'^create/$',
    'create_vehicle',
    name='vehicle_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', )

答案 1 :(得分:3)

这是我现在写这个视图的简短版本,只是为了将来的眼睛。 不需要任何__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})

答案 2 :(得分:2)

您没有显示如何在视图中实例化表单。您需要记住在执行此操作时实际传递请求:

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