私は次のようなmodels.pyを持っています:
from django.db import models
from django.contrib.auth.models import User
# everything has a colour...
class Colour(models.Model):
colour = models.CharField(max_length=100)
def __unicode__(self):
return self.colour
# a thing can have a colour...
class Thing(models.Model):
name = models.CharField(max_length=155)
colour = models.ForeignKey(Colour)
description = models.CharField(max_length=255)
def __unicode__(self):
return self.name
# a user can save his choices
class UserLikes(models.Model):
user = models.ForeignKey(User)
colour = models.ForeignKey(Colour)
thing = models.ForeignKey(Thing)
class Meta:
verbose_name_plural = "User Likes"
def __unicode__(self):
return '%d - %s' % (self.pk, self.user)
そして私の見解では:
def ThingPicker(request):
if request.method == 'POST':
form = ThingForm(request.POST)
if form.is_valid():
colour = form.cleaned_data['colour']
thing = form.cleaned_data['thing']
likes = UserLikes(user=request.user, colour=colour, thing=thing)
likes.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('thing_picker.html', {
'form': form,
}, RequestContext(request))
else:
form = ThingForm()
return render_to_response('thing_picker.html', {
'form': form,
}, RequestContext(request))
そして私のtests.pyで私はこのようなことをしたいです(編集済み):
class ViewTests(TestCase):
def setUp(self):
self.client = Client()
def test_thingpicker(self):
User.objects.create_superuser('foo', 'myemail@test.com', 'bar')
self.client.login(username='foo', password='bar') # request.user is now user foo
response = self.client.post('/colours/things/', {'colour': 1, 'thing': 2})
userlike = UserLikes.objects.get(pk=1)
self.assertEqual(userlike.colour_id, 1)
エラーが発生します:
DoesNotExist: UserLikes matching query does not exist.
シェルでテストクライアントを試してみると、次のようになります。
>>> c = Client()
>>> user1 = User.objects.create_superuser('foo', 'myemail@test.com', 'bar')
>>> c.login(username='foo', password='bar')
>>> c.post('/colours/things/', {'user': user1, 'colour': 1, 'thing': 2})
>>> userlike = UserLikes.objects.get(pk=1)
>>> userlike.colour_id
1L
期待通りの結果が得られました。