如何在django中将用户重定向到Detailview

时间:2016-03-09 03:02:46

标签: django

从表单请求创建模型后,我遇到以下错误:Generic detail view SugboxDetailView must be called with either an object pk or a slug.

my urls.py

urlpatterns = [
      url(r'^box/(?P<pk>[0-9A-Za-z-]+)/$', views.get_box, name='box'),
      url(r'^sugbox/$', views.SugboxForm.as_view(), name='sugbox'),
      url(r'^liste/$', views.IndexView.as_view(), name='index'),
      url(r'^(?P<id>[0-9A-Za-z]+)/$', views.SugboxDetailView.as_view(), name='detail'),
      url(r'^suggies/$', views.SuggestionForm.as_view(), name='suggies'),
      #url(r'^$', views.Homepage.as_view(), name='root'),
      url(r'^$', views.SugboxForm.as_view(), name='sugbox'),

my models.py

@python_2_unicode_compatible
class Box(models.Model):
    """
    Box model
    """
    def __str__(self):
        return self.title
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)     
    title = models.CharField(max_length=40, blank=True, null=True)
    identify = models.BooleanField(default=False)
    activate = models.BooleanField(default=False)
    created_at = models.DateField(auto_now_add=True)
    updated_at = models.DateField(auto_now=True)

my views.py

class SugboxForm(FormView):
    """
    for user to Create a Suggestion Box
    """
    template_name = 'boxes/sugbox_form.html'
    form_class = SugboxForm
    success_url = '/boxes/detail/'
    """ Send to a page that will show the  slug 
    so that the user can share it  SuggestionBox
    to others
    """

    def form_valid(self, form):
        # This method is called when valid form data has been POSTed.
        # It should return an HttpResponse.
        form.save()
        messages.success(self.request, "Successfully Created")
        print(self.request)
        return super(SugboxForm, self).form_valid(form)

class SugboxDetailView(generic.DetailView):
    model = Box
    template_name =  "boxes/details.html"
    context_object_name = "sugbox"


class SuggestionForm(FormView):
    """
    for user to put their suggestion
    """
    template_name = 'boxes/suggestion.html'
    form_class = SuggestionForm
    success_url = '/suggestion/'

    def form_valid(self, form):
        # This method is called when valid form data has been POSTed.
        # It should return an HttpResponse.
        form.save()
        return super(SuggestionForm, self).form_valid(form)

我的错误在http://localhost:8002/boxes/detail/

1 个答案:

答案 0 :(得分:1)

试试这个:

class SugboxDetailView(generic.DetailView):
    model = Box
    template_name =  "boxes/details.html"
    context_object_name = "sugbox"
    pk_url_kwarg = 'id'

    def get_queryset(self):
        qs = super(SugboxDetailView, self).get_queryset()
        return qs.filter(...., attr=self.kwargs.get('id'))