Saving test user as a foreign key in unit tests

297 views
Skip to first unread message

jondbaker

unread,
Apr 11, 2012, 2:44:11 PM4/11/12
to django...@googlegroups.com
I have a Tasting model with an 'author' field that is a ForeignKey to the User model. Within my unit test I'm attempting to create a test user, and pass that user object as the author of a test Tasting, but I keep getting the following error: "IntegrityError: tastings_tasting.author_id may not be NULL"

models.py
class Tasting(models.Model):
    notes = models.TextField(blank=True)
    author = models.ForeignKey(User, editable=False)

forms.py
class TastingForm(ModelForm):
    class Meta:
        model = Tasting

views.py
def create_tasting(request):
    if request.method =='POST':
        form = TastingForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/tastings/')
    else:
        form = TastingForm()
    return render_to_response('tastings/create.html', {
        'form': form
    }, context_instance=RequestContext(request))

test_views.py
class TestPostCreateTasting(TestCase):
    def test_auth_response_valid_data(self):
        client = Client()
        user = User.objects.create_user('test', 'te...@test.com', 'testPassword')
        client.login(username='test', password='testPassword')
        tasting = {
            'notes': 'What a great beer',
            'author': user,
        }
        response = client.post('/tastings/create/', tasting)
        self.assertEquals(response.status_code, 200)
        tastings = Tasting.objects.all()
        self.assertEquals(len(tastings), 1)
        client.logout()

jondbaker

unread,
Apr 11, 2012, 3:14:36 PM4/11/12
to django...@googlegroups.com
Problem solved. Within my view I needed use the following:

def create_tasting(request):
    if request.method =='POST':
        form = TastingForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.author = request.user
            obj.save()
Reply all
Reply to author
Forward
0 new messages