0
我有一些評估模型,其中包含ip和url以及必填字段。 我在request.POST中獲得了一些這些字段,但我必須從我的視圖中將ip和url傳遞給模型表單。 我的模型:將附加參數傳遞給Django Model Forms以及request.POST
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')
在我views.py:
form = RatingModelForm(request.POST, ip=ip, url=url)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
和我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
我已經嘗試設置初始值,但form.is_valid( )給予False,並聲明ip和url是必需的。如何繼續這個?
感謝您的回答,但request.POST是我的情況下不可變querydict。無法修改 –
@roushankumar我修改了我的答案。 – Jonathan
@roushankumar有幫助嗎? – Jonathan