S
S
Sergey Nizhny Novgorod2016-08-12 07:44:17
Django
Sergey Nizhny Novgorod, 2016-08-12 07:44:17

Am I testing a form correctly in Django?

Hello.
I want to check the form that accepts data on the site, creates a new object:
So:
Url:

url(r'^addcreview(?P<add_id>[0-9]+)$', views.addcreview, name='addcreview'),

Model:
class Creview(models.Model):
    creview = models.ForeignKey(Course, on_delete=models.CASCADE, default=1)
    userview = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
    # username = models.CharField(max_length=200, help_text="Имя автора отзыва", verbose_name="Имя автора отзыва")
    review = models.TextField(help_text="Отзыв", verbose_name="Сам отзыв о курсе")

view:
def addcreview(request, add_id):
    token = {}
    token.update(csrf(request))
    if request.user.is_authenticated():
        current_user = request.user
        if request.POST:
            course = Course.objects.get(id=add_id)
            form = CreviewForm(request.POST)
            if form.is_valid():
                review = form.cleaned_data['review']
                review_obj = Creview(creview=course, userview=current_user, review=review)
                review_obj.save()
                return redirect('/course' + add_id, token)

Test:
class Test_Forms_For_Safe(TestCase):
    def test_creview_form_save(self):
        ##########
        user = User.objects.create(id=1, username="gavgav", password='W123456')
        profile = Profile.objects.create(user=user)
        self.client.login(username='gavgav', password='W123456')
        ##########
        course = Course.objects.create(id=1, title="заголовок")
        ##########
        response = self.client.post('/addcreview1',
                                    {'id': "1", "creview": "course", "userview": "user", "review": "ревьюшка"})
        ##########

        creview = Creview.objects.get(id=1)

        self.assertEqual(creview.review, 'ревьюшка')

Those. my Logic:
- I create a user
- I go to the site with him - I
create a Course object
- I pass data to the post url that should create a Creview object - I check the
data matches.
Mistake:
faceset.models.DoesNotExist: Creview matching query does not exist.

Can you suggest what I'm doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SkiBY, 2016-08-12
@Terras

Not right.
1. It is customary to do an authentication check as

@login_required
def...

this is convenient - the situation with redirection to the login page, etc. is immediately processed.
2. First you need to create an object. Processing the form with the standard method for POST:
form = CreviewForm(request.POST or None)
if request.method == 'POST' and form.is_valid():
        obj = form.save(commit=False)
        obj.course = course
        ....
        obj.save()
        form.save() 
else:
    возврат к представлению для исправления данных и т.д.

This format will check both csrf, and data in the form, and so on.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question