我想将查询字符串(例如?refcode='A1234'
)传递给ModelForm中名为inbound_referral_code
的隐藏字段。
我的模型如下:
class User(models.Model):
email = models.EmailField(max_length=255, blank=False, unique=True)
inbound_referral_code = models.CharField(max_length=255)
我的ModelForm目前如下:
class UserForm(forms.ModelForm):
model = User
fields = ['email', 'inbound_referral_code']
widgets = {'inbound_referral_code': forms.HiddenInput()}
我的观点是:
def register(request):
if request.method == 'POST':
form = UserForm(request.POST)
[...]
else:
form = UserForm()
return render(request, 'register.html', {'form': form})
目前我的模板是:
<form action="{% url 'register' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit"/>
</form>
两个问题:
?refcode
参数分配给inbound_referral_code
字段??refcode
会怎样?答案 0 :(得分:1)
要分配refcode
,您需要将其传递到表单中,因此您传入包含它的request.POST以外的内容,在
dict = request.POST.copy()
dict["inbound_referral_code"] = request.POST.get("refcode")
form = UserForm(dict)
# ...
或验证后:
if form.is_valid():
form.cleaned_data["inbound_referral_code"] = request.POST.get("refcode")
如果没有提供,您可以检查并传递自定义值,或在定义表单/模型时设置默认值。
要在模板中设置它,您可以传递初始值
else:
form = UserForm(initial={"inbound_referral_code": "ref-value-here"})
return render(request, 'register.html', {'form': form})
答案 1 :(得分:1)
结合不同的答案,以下解决方案有效:
设置表单参数的“初始”值,并确保在验证失败时使用绑定表单呈现模板。正确的视图功能是:
def register(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
return redirect([...])
else:
refcode = request.GET.get('refcode')
form = UserForm(intial={'inbound_referral_code': refcode)
return render(request, 'register.html', {'form': form})
请注意,需要移动底部return render(...)
,以便在POST请求中包含验证错误的情况下使用表单调用它...