简体   繁体   中英

Django view not redirecting properly

Need some help with redirecting this back to the page I was on, it's for a button click similar to a like on a page.

class ProjectDelayedView(RedirectView):
    def get_redirect_url(self, *args, **kwargs):
        slug = self.kwargs.get("slug")
        print(slug)
        obj = get_object_or_404(Project, slug=slug)
        if obj.delayed is False:
            obj.delayed = True
        else:
            obj.delayed = False
        obj.save()
        return 'http://127.0.0.1:8000/si/list/All/'

I have got this redirecting to google as I can't quite work out how to redirect it to a page on my site. Here is my urls page also:

rom django.urls import path

from project_portal.views import (
    ProjectCreateView,
    ProjectDelayedView,
    ProjectListView,
    project_update_view,
    search,
)

urlpatterns = [
    path('project-create/', ProjectCreateView.as_view(), name='project-create'),
    path('<slug:slug>/delayed/', ProjectDelayedView.as_view(), name='project-delay'),
    path('list/<area>/', ProjectListView.as_view(), name='project-list'),
    path('<slug:slug>/update/', project_update_view, name='project-update'),
    path('search/', search, name='search'),
]

The tutorial I was following was saying to use get_absolute_url, but I'm not sure how that works, and it's tricky trying to understand it in the docs, I'm assuming that get_absolute_url gets a hard coded url set in the Model perhaps. Aside from that, eventually, this will redirect to an DetailView which is where this button will be situated.

UPDATE:I've got this working now, but as you can see, the return from get_redirect_url() is just hardcoded, this was just to get the view working, I can't find anything in the docs as to what should be returned, but a hardcoded url is not very useful.

try something like this:

In your Project model insert a get_absolute_url method

    def get_absolute_url(self):
        from django.urls import reverse
        return reverse('project-detail', args=[self.slug])

with a detailview like this:

class ProjectDetailView(DetailView):
    model = Project

path('project/<slug:slug>/', views.ProjectDetailView.as_view(), name='project-detail'),

and finally in yout redirectview

class ProjectDelayedView(RedirectView):
    def get_redirect_url(self, *args, **kwargs):
        slug = self.kwargs.get("slug")
        print(slug)
        obj = get_object_or_404(Project, slug=slug)
        if obj.delayed is False:
            obj.delayed = True
        else:
           obj.delayed = False
        obj.save()
        return obj.get_absolute_url()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM