简体   繁体   English

将多余的参数与request.POST一起传递给Django Model Forms

[英]Pass extra parameters to Django Model Forms along with request.POST

I have a Rating models with some fields in which ip and url and required fields. 我有一个带有某些字段的评级模型,其中ip和url以及必填字段。 I get some of these fields in request.POST but I have to pass ip and url to the modelform from my view. 我在request.POST中得到了一些字段,但是我必须从我的视图中将ip和url传递给modelform。 My Model: 我的模特:

class Rating(models.Model):

    rating = core_fields.SmallIntegerRangeField(min_value=1, max_value=5)
    url = models.URLField(max_length=2048)
    tracker = models.ForeignKey("core.Tracker", db_index=True)
    ip = models.GenericIPAddressField(db_index=True)
    user_agent = models.CharField(max_length=100)
    object_id = models.PositiveIntegerField(db_index=True)
   _content_type = models.ForeignKey(ContentType, db_index=True)
   special_object = GenericForeignKey('_content_type', 'object_id')

class Meta:
    unique_together = ['_content_type', 'tracker', 'object_id']
    verbose_name = ('rating')

In my views.py : 在我的views.py中:

form = RatingModelForm(request.POST, ip=ip, url=url)

if form.is_valid():
    instance = form.save(commit=False)
    instance.save()

And my in forms.py: 和我在forms.py:

class RatingModelForm(forms.ModelForm):

    class Meta:
        model = Rating
        exclude = ('special_object',)

    def __init__(self, *args, **kwargs):
        ip = kwargs.pop('ip', None)
        url = kwargs.pop('url', None)

        super(RatingModelForm, self).__init__(*args, **kwargs)
        self.fields['ip'].initial = ip
        self.fields['url'].initial = url

I have tried setting initial values but the form.is_valid() give False and and states that ip and url are required. 我尝试设置初始值,但是form.is_valid()给出False,并且指出ip和url是必需的。 How do proceed with this ? 如何进行呢?

The first argument of a ModelForm is data. ModelForm的第一个参数是数据。 Ie the expected data for the form. 即表格的预期数据。 As you mentioned that request.POST is an immutable querydict. 正如您提到的, request.POST是一个不变的querydict。 Make a new dictionary by making a copy out of it , modify that and then pass it into the form. 制作一个新字典,方法是制作一个副本,对其进行修改,然后将其传递给表单。

If you use dict() on a django QueryDict it will look odd. 如果在Django QueryDict上使用dict(),它将看起来很奇怪。 So you have to make a copy of the query dict to make it work properly. 因此,您必须复制查询字典以使其正常工作。

data = request.POST.copy()
data['ip'] = ip
data['url'] = url
form = RatingModelForm(data) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM