Django CBV表格非常有问题

时间:2015-07-16 17:27:19

标签: python django

我遇到了Django CBV的问题。我无法在页面上呈现我的表单。 (即使我这样做,我也无法保存表格)。

我想:

  1. 显示表单(让我们将其称为推文表单),并在同一页面上显示所有推文(使用2个单独的视图)
  2. 保存推文,并在同一页面上显示更新的推文列表。
  3. 以下是我的代码,但它似乎无法运作:

    forms.py

    from django import forms
    from .models import Tweet
    
    class TweetForm(forms.Form):
    text = forms.CharField(widget=forms.Textarea(attrs={'rows': 1, 'cols': 85}), max_length=155)
    country = forms.CharField(widget=forms.HiddenInput())
    

    urls.py

    from django.conf.urls import include, url
    from django.contrib import admin
    from microblog.views import Index, Profile, PostTweet
    
    admin.autodiscover()
    
    urlpatterns = [
    url(r'^$', Index.as_view(), name='home'), # Homepage of app
    url(r'^user/(\w+)/$', Profile.as_view(), name='profile'), # User profile page
    url(r'^user/(\w+)/post/$', PostTweet.as_view(), name='post'),
    url(r'^admin/', include(admin.site.urls)),
    ]
    

    views.py

    class Profile(View):
        def get(self, request, username):
            params = dict()
            user = User.objects.get(username=username)
            tweets = Tweet.objects.filter(user=user)
            params["tweets"] = tweets
            params["user"] = user
            return render(request, 'microblog/profile.html', params)
    
    class PostTweet(View):
        def post(self, request, username):
            form = TweetForm(self.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()
                words = form.cleaned_data['text'].split(" ")
                for word in words:
                    if word[0] == "#":
                        hashtag, created = HashTag.objects.get_or_create(name=word[1:])
                    hashtag.tweet.add(tweet)
             return HttpResponseRedirect('/user/'+username)
    

    任何帮助都很受欢迎!!我一直在为此而低下头!

0 个答案:

没有答案