Reputation: 2661
My Models look like this:
class Car(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
name = models.CharField(max_length=200)
class Owner(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
car = models.ForeignKey(Car)
and a Form that looks like this:
class CarForm (forms.ModelForm):
def __init__(self, *args, **kwargs):
super(CarForm, self).__init__(*args, **kwargs)
self.fields['car_name']=forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off'}),label='', required=False)
self.fields['person_name']=forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off'}),label='', required=False)
So when the user goes to my index file he find two forms, one for his name and one for the car's name which when submitted will be created in the database then.
So now I am in the shell and want to test that and I'm not sure what the correct syntax is, I've tried this:
response = client.post('/', {'car_name':'something','person_name':'something'})
but it always returns:
IndexError: list index out of range
What does that mean? Or what's the correct syntax to run the tests?
I've also tried this:
response = client.post('/', {'id_car_name':'something','id_first_name':'something'})
Since these are the ids that Django creates in the homepage, but it didn't work
Upvotes: 0
Views: 1968
Reputation: 1731
Your test case syntax looks correct. The field names from your first example are correct and match those declared in self.fields
. Here is a more detailed example (with assertions as desired):
from django.test import Client, TestCase
class CarFormTest(TestCase):
def test_form(self):
client = Client()
response = client.post('/', {'car_name':'something','person_name':'something'})
self.assertEqual(response.status_code, 200)
I don't see anything in your test line that would cause an IndexError.
Given that you did not map the Car model to the CarForm like this:
class CarForm(forms.modelForm):
class Meta:
model = Car
It appears that you don't want a direct mapping and instead you need a custom save()
method on your CarForm to create Car
and Owner
objects when you save the form. The IndexError must be coming from a line of code that you have not shown.
Please update your question to provide additional code.
Upvotes: 2