def create(request): IdeaForm = make_IdeaForm(request.user) is_create = False # If the user is logged in then we don't need a form. if request.user.is_authenticated(): UserForm = None elif request.method == 'POST': # Figure out if its creating a user account or logging in. if 'first_name' in request.POST: is_create = True UserForm = TorchUserForm else: UserForm = AuthenticationForm if request.method == 'POST': # We need to authenticate the user and rebuild the IdeaForm user_form_is_valid = True if UserForm is not None: user_form = UserForm(data=request.POST) user_form_is_valid, user = _deal_with_form_validation( request, user_form, is_create, ) if user_form_is_valid: IdeaForm = make_IdeaForm(user) idea_form = IdeaForm(request.POST) if idea_form.is_valid() and user_form_is_valid: idea = idea_form.save() url = reverse('idea_view', kwargs={'idea_id': idea.pk}) return HttpResponse( dumps( {'url': url}, ), mimetype="application/json", ) else: return HttpResponse( dumps( {'errors': str(idea_form.errors) + str(user_form.errors)}, ), mimetype="application/json", ) else: idea_form = IdeaForm() user_form = TorchUserForm() context = RequestContext(request, { 'user_form': user_form, 'idea_form': idea_form, }) return render_to_response( 'idea/create.html', context_instance=context, )
def test_invalid_user(self): params = {"title": "title", "description": "description", "tag": CREATIVITY} IdeaForm = make_IdeaForm(None) form = IdeaForm(params) is_valid = form.is_valid() assert not is_valid self.assertEqual(form.errors["__all__"], ["This field is required."])
def test_empty(self): # Build the form with no input. Equivalent to no POST vars. IdeaForm = make_IdeaForm(None) form = IdeaForm({}) is_valid = form.is_valid() assert not is_valid for key in form.errors.keys(): self.assertEqual(form.errors[key], ["This field is required."])
def test_invalid_tag(self): user = User.objects.create() params = {"title": "title", "description": "description", "tag": 1000} # Not a valid tag. IdeaForm = make_IdeaForm(user) form = IdeaForm(params) is_valid = form.is_valid() assert not is_valid self.assertEqual(form.errors["tag"], ["Select a valid choice. 1000 is " "not one of the available choices."])
def test_valid(self): user = User.objects.create() IdeaForm = make_IdeaForm(user) params = {"title": "title", "description": "description", "tag": CREATIVITY} form = IdeaForm(params) is_valid = form.is_valid() assert is_valid idea = form.save() self.assertEqual(idea.author, user) self.assertEqual(idea.title, "title") self.assertEqual(idea.description, "description") self.assertEqual(idea.tag, CREATIVITY)