I am making a test form using ModelForm which has two models.
CountryEmailI am creating a form based on Email models.
The Country model has name field, with the values given by the COUNTRIES list.
I want to display name field in the EmailForm, with all the COUNTRIES values. Do I have to use a foreign key? Please guide.
My models look like this:
COUNTRIES = (('IND', 'India'), ('PAK', 'Pakistan'), ('AMR', 'America'))
class Country(models.Model):
name = models.CharField(max_length=3, choices=COUNTRIES)
class Email(models.Model):
title = models.CharField(max_length=50)
country = models.ForeignKey('Country')
sender = models.EmailField(max_length=20)
date = models.DateTimeField()
text = models.CharField(max_length=20)
class EmailForm(ModelForm):
class Meta:
model = Email
If I generate a form out of this. it shows a drop down menu which is blank. How to get values from the list?
You probably want to add custom field to your ModelForm and exclude original foreign key:
class EmailForm(forms.ModelForm):
country_name = forms.CharField()
class Meta:
model = YourModel
exclude = ('country',)
Then, in your view you should manualy create (or get if it exists) your company and save the form:
def foo(request):
if request.method == 'POST':
form = EmailForm(request.POST)
if form.is_valid():
form.instance.country = Country.objects.get_or_create(cname=form.cleaned_data['country_name'])
form.save()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With