为什么Django中的client.post不断返回GET响应

时间:2018-07-22 06:31:10

标签: django testing

我正在django 2.0.4和python 3下开发Web应用程序。我需要为Signup视图编写一个测试,以确保在成功注册后进行重定向。这是代码:

forms.py

from django.contrib.auth.forms import UserCreationForm
from django.cotnrib.auth.models import User
class SignupForm(UserCreationForm):
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    email = forms.EmailField(max_length=200)

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',)

views.py

from django.shortcuts import render, redirect
from .form import SignupForm

class SignupView(View):
    template_name='signup/signup.html'
    form_class = SignupForm

    def get(self, request, *args, **kwargs):
        form = self.form_class()
        return render(request, self.template_name, {'form' : form })

    post(self, request, *args, **kwargs):
        form = self.self.form_class(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user=authenticate(username=username, password=raw_password)
            if user is Not None:
                login(request, user)
                return redirect('index')
        else:
            form = self.form_class()
            context = {'form' : form}
            return render(request, self.template_name, {'form' : form})

urls.py(应用程序)

from django.url import path

urlpatterns = [
    path('signup/', views.SignupView.as_view(), name='signup'),
    ...
]

signup.html

<form method="post" action="{% url 'signup' %}>
    {% csrf_token %}
    <table>
        {{ form.as_table }}
    </table>
    <button type="submit">sign up</button>
</form>

在我尝试对帖子进行测试之前,以上所有方法均能正常工作。那是对代码的测试。

return redirect('index')

这是“ test_views.py”中的测试代码

class SignUpViewTest(TestCase):
    def test_view_redirect_after_post(self):
      post_data = {'username': 'mary',
                 'first_name':'Mary',
                 'last_name': 'Farh',
                 'password1': '1234_abcd',
                 'password2':'1234_abcd',
                 'email': 'goinhome@outlook.com'}
      resp = self.client.post(reverse('signup'), post_data)
      #self.assertRedircts(resp, reverse('index'))
      self.assertEqual(resp.status_code, 302)

我ALWASYS的resp.status_code为200。而且我非常确定HttpResponse来自“ else”子句(在views.py中)。

class SignupView(View)
    def post(self,request, *args, **kwargs)
        ...
        if form.is_valid():
            ...
        else:
            form = self.form_class()
            context = {'form' : form}
            return render(request, self.template_name, {'form' : form})

请告诉我为什么分支

if  form.is_valid():
    ...

被绕过。并告诉我如何修复测试。

谢谢!

0 个答案:

没有答案