我遇到了Django CBV的问题。我无法在页面上呈现我的表单。 (即使我这样做,我也无法保存表格)。
我想:
以下是我的代码,但它似乎无法运作:
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)
任何帮助都很受欢迎!!我一直在为此而低下头!