【发布时间】:2020-01-22 06:30:20
【问题描述】:
我正在使用 ModelForm,我想用一个初始值填充我的 dataset_id 字段,该初始值将来自争论中传递的“pid”变量。我已经尝试了一些东西并附加了该代码,但它不起作用
views.py
def home(request, pid):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = DelegateForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
p = form.save()
# redirect to a new URL:
return HttpResponseRedirect('/')
# if a GET (or any other method) we'll create a blank form
else:
# Here I want to pass the value of "pid" to the dataset_id field so that when it renders it is populated with the value in the pid variable
form = DelegateForm(initial={'dataset_id': pid})
return render(request, 'add_delegate.html', {'dform': form, 'uid': pid})
models.py
class Delegate(models.Model):
dataset_id = models.CharField(max_length=255, null=True, blank=True)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255, null=True, blank=True)
email = models.CharField(max_length=255, null=True, blank=True)
phone = models.IntegerField(null=True, blank=True)
company = models.CharField(max_length=255, null=True, blank=True)
designation = models.CharField(max_length=255, null=True, blank=True)
address = models.CharField(max_length=255, null=True, blank=True)
city = models.CharField(max_length=255, null=True, blank=True)
pincode = models.IntegerField(null=True, blank=True)
image_path = models.CharField(max_length=2083, null=True, blank=True)
forms.py
class DelegateForm(forms.ModelForm):
class Meta:
model = Delegate
fields = ['dataset_id', 'first_name', 'last_name']
widgets = {
'dataset_id': forms.TextInput(attrs={'class': 'form-control'}),
'first_name': forms.TextInput(attrs={'class': 'form-control'}),
'last_name': forms.TextInput(attrs={'class': 'form-control'}),
}
template.html
{% block content %}
{% load static %}
<form action="/success/" method="post">
{% csrf_token %}
<div class="form-group">
<label>{{ dform.dataset_id.label_tag }}</label>
{{ dform.dataset_id }}
<label>{{ dform.name.label_tag }}</label>
{{ dform.name }}
</div>
<input type="submit" value="Submit"/>
</form>
{% endblock %}
【问题讨论】:
-
您在哪里使用
ModelForm?我没看到这里 -
pid应该是对象的id,dataset_id还是别的什么?
-
pid 是唯一的,它从另一个视图函数传递给我的 def home 方法。 pid 每次传递时都会填充一个 4 位唯一数字
-
我基本上想要 def home 参数中的 pid 值,然后使用该值使用该值自动填充 dataset_id 字段
标签: python django python-3.x django-forms modelform