0
我在提交表單後很難返回正確的網址。我可以通過將它引導到索引頁面來實現它,但是我希望它指向新創建的項目url。比如我想要的網址看起來像這樣:使用CreateView後需要幫助才能返回正確的網址
www.example.com/username/project-slug
我一直沒有運氣:-(現在正試圖約5小時任何幫助將是非常感謝!
意見
class CreateProject(CreateView):
model = UserProject
form_class = UserProjectForm
template_name = 'howdidu/create_project.html'
#success_url = "/"
def form_valid(self, form):
form.instance.user = self.request.user
self.object = form.save()
return super(CreateProject, self).form_valid(form)
def get_success_url(self):
return reverse_lazy('index')
網址
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^register_profile/$', views.register_profile, name='register_profile'),
url(r'^update_profile/$', views.update_profile, name='update_profile'),
url(r'^create_project/$', views.CreateProject.as_view(), name='create_project'),
url(r'^(?P<username>\w+)/$', views.profile_page, name='user_profile'),
url(r'^(?P<project_title_slug>[\w-]+)/$', views.project_page, name='user_project'),
)
車型
class UserProject(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=100)
project_overview = models.CharField(max_length=1000)
project_picture = models.ImageField(upload_to='project_images', blank=True)
date_created = models.DateTimeField(auto_now_add=True)
project_views = models.IntegerField(default=0)
project_likes = models.IntegerField(default=0)
project_followers = models.IntegerField(default=0)
slug = models.SlugField(max_length=100, unique=True) #should this be unique or not?
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(UserProject, self).save(*args, **kwargs)
def __unicode__(self):
return self.title
項目的URL
url(r'^admin/', include(admin.site.urls)),
url(r'', include('howdidu.urls')),
url(r'^accounts/register/$', MyRegistrationView.as_view(), name='registration_register'), #redirects to home page after registration
(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^(?P<username>\w+)/', include('howdidu.urls')), #do i need this?
URL的定義在哪裏:www.example.com/username/project-slug? –