0

I learned Django in the book Learning Django Web Development recently. I want the make the post-tweet function but i always get the errors below

The view tweets.views.PostTweet didn't return an HttpResponse object. It returned None instead.

After a series of test, i found that the form is invalid.

Here's the views.py

class PostTweet(View):
    """
    Tweet post form availbale on page/user/<username> URL
    """
    form_class = TweetForm
    template_name = 'profile.html'

    def post(self, request, username):
        form = self.form_class(request.POST)
        if form.is_valid():
            user = User.objects.get(username=username)
            tweet = Tweet(text=form.cleaned_data['text'],
                          user=user,
                          country=form.cleaned_data['country'])
            tweet.save()
            form.save()
            return HttpResponseRedirect('/user/'+username)

profile.html

{% extends "base.html" %}
{% block content %}
<div class="row clearfix">
  <div class="col-md-6 col-md-offset-3 column">
    <form id="search-form" method="POST" action="post/">{% csrf_token %}
      <div class="col-md-8 fieldWrapper">
        <textarea cols="85" id="id_text" maxlength="160" name="text" rows="1"></textarea>
        <input id="id_country" name="country" type="hidden" />
        <span class="input-group-btn">
          <button class="btn btn-default" type="submit">Post</button>
        </span>
      </div>
    </form>
  </div>
  <h3>&nbsp;</h3>
  <div class="col-md-12 column">
    {% for tweet in tweets %}
      <div class="well">
        <span>{{ tweet.text}}</span>
      </div>
    {% endfor %}
  </div>
</div>
{% endblock %}

forms.py

from django import forms

class  TweetForm(forms.Form):
    text = forms.CharField(widget=forms.Textarea.is_required,max_length=160)
    country = forms.CharField(widget=forms.HiddenInput())

Anyone just give me a hint will be appreciated. :-)

Peter Tsung
  • 915
  • 2
  • 10
  • 20

1 Answers1

0

Your view takes action when the form is valid, but when the form is not valid then the block that does the redirect is not run and the method exits without taking any action, returning None by default.

You will want to add some action to handle the case when form.is_valid() returns false, such as an error message or error page redirect.

Canute Bigler
  • 220
  • 1
  • 9