我是Django的新手,没有经验,尝试实现基于类的视图,并完全陷入尝试设置success_url的问题。
我尝试了两种方法,我认为它们最接近基于Google的正确方法,并且不确定哪一种方法最可靠:
success_url ='letters / home'->导致意外的重定向/ letters / write / letters / home,而我希望它转到/ letters / home
reverse_lazy('letters:home')导致“找不到'home'的反向项。'home'不是有效的视图函数或模式名称。”
这是我的代码:
查看
from .models import Topic
from django.views.generic.edit import CreateView
from django.views.generic import TemplateView
from django.urls import reverse_lazy
from .forms import WriteLetterForm
class HomeView(TemplateView):
template_name = 'letters/letter/home.html'
class WriteLetterView(CreateView):
template_name = 'letters/letter/write_letter.html'
form_class = WriteLetterForm
success_url = 'letters/home' # reverse_lazy('letters:home')
# success_url = 'letters/home'
# success_url = reverse_lazy('HomeView')
def form_valid(self,form):
form.instance.author = self.request.user
form.instance.topic = Topic.objects.get(slug=self.kwargs['slug'])
result = super(WriteLetterView,
self).form_valid(form)
cd = form.cleaned_data
# user = authenticate(username=cd['username'],
# password=cd['password1'])
# login(self.request, user)
return result
应用内的urls.py
from django.urls import path
from . import views
app_name = 'letters'
urlpatterns = [
path('home/', views.HomeView.as_view()),
path('write/<str:slug>', views.WriteLetterView.as_view()),
]
forms.py
from django import forms
from .models import Letter
from braces.forms import UserKwargModelFormMixin
class WriteLetterForm(UserKwargModelFormMixin, forms.ModelForm):
#letter = forms.ModelChoiceField(queryset=Letter.objects.all())
class Meta:
model = Letter
fields = ['body', 'picture_1', 'picture_2', 'picture_3']
def create(self):
obj = super(WriteLetterForm, self).save(commit=False)
obj.author_id = self.user
obj.save()
return obj
我哪里出错了? :(
答案 0 :(得分:2)
urlpatterns = [
path('home/', views.HomeView.as_view(),name="home"),
path('write/<str:slug>', views.WriteLetterView.as_view()),
]
success_url = reverse_lazy('letters:home')
这样做就可以了,因为您还没有命名家庭网址,因此显示的网址未找到