Answer the question
In order to leave comments, you need to log in
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'),
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="Сам отзыв о курсе")
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)
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, 'ревьюшка')
faceset.models.DoesNotExist: Creview matching query does not exist.
Answer the question
In order to leave comments, you need to log in
Not right.
1. It is customary to do an authentication check as
@login_required
def...
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:
возврат к представлению для исправления данных и т.д.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question