我尝试将新变量 urls 从函数传输到ModelForm。 在这封信中,变量来了,但是在形式上 - 保存一个空字符串。
models.py
class Order(models.Model):
name = models.CharField(max_length=25, verbose_name="Имя*")
phone = models.CharField(max_length= 20, verbose_name="Мобильный телефон*")
email = models.EmailField(max_length=25, verbose_name="Электронная почта*")
text = models.TextField()
urls = models.URLField()
views.py
def viewperson(request, slug):
trainer = Trainer.objects.get(slug = slug)
urls = (reverse('trainers:viewperson', args=[slug]))
if request.method == 'POST':
model_form = ModelOrderForm(request.POST)
if model_form.is_valid():
subject = "New order"
phone = model_form.cleaned_data['phone']
name = model_form.cleaned_data['name']
text = model_form.cleaned_data['text']
email = model_form.cleaned_data['email']
recipients = [mail@gmail.com']
message = name + " " +" "+ phone + " " + "site.com"+urls +" "+ text
if result['success']:
try:
model_form.cleaned_data['urls']=urls #Here i try to send urls in forms urls-field
instance = model_form.save()
send_mail(subject, message, email, recipients)
return redirect('thanks_for_order')
except BadHeaderError:
return HttpResponse('Invalid header found')
else:
messages.error(request, 'Error reCAPTCHA. Tray again.')
return redirect('trainers:viewperson' , slug=slug)
else:
model_form = ModelOrderForm()
return render(request, "trainer_person.html", {'trainer':trainer,
'model_form':model_form,})
答案 0 :(得分:1)
如果我正确理解了您的问题,您需要在保存过程中将url值添加到实例。在这种情况下,您可以使用commit=False
形式的保存参数来更新新的实例,然后将其保存在DB中:
instance = model_form.save(commit=False)
instance.urls = urls
instance.save()