Я использую 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'}),
}
шаблон. 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 %}