简体   繁体   中英

Django views and URl's

I'm having a problem with the way my URL's look in Django. I have a view like this:

def updatetext(request, fb_id):
    Account.objects.filter(id=fb_id).update(display_hashtag=request.POST['hashtag'])

    fb = get_object_or_404(Account, pk=fb_id)
    return render(request, 'myapp/account.html', {
        'success_message': "Success: Settings updated.",
        'user': fb
    })

When a user clicks on the URL to update the text they are then redirected to the account page but the URL then looks like 'account/updatetext/'. I would like it just be 'account/'.

How would I do this in Django. What would I use in place of render that would still allow me to pass request, 'success_message' and 'user' into the returned page but to not contain the 'updatetext' within the URL?

[edit]

The urls.py file looks like this:

from django.conf.urls import patterns, url

from myapp import views

urlpatterns = patterns('',
    url(r'^home/$', views.index, name='index'),
    url(r'^(?P<fb_id>\d+)/$', views.account, name='account'),
    url(r'^(?P<fb_id>\d+)/updatetext/$', views.updatetext, name='updatetext'),
    url(r'^(?P<fb_id>\d+)/updatepages/$', views.updatepages, name='updatepages'),
    url(r'^login/$', views.user_login, name='login'),
    url(r'^logout/$', views.user_logout, name='logout'),
    url(r'^admin/$', views.useradmin, name='admin'),
)

You need to actually redirect the user to '/account/'. Rather than returning a call to render you can do the following:

from django.http import HttpResponseRedirect

def updatetext(request, fb_id):
    Account.objects.filter(id=fb_id).update(display_hashtag=request.POST['hashtag'])

    fb = get_object_or_404(Account, pk=fb_id)
    return HttpResponseRedirect(reverse('account', kwargs={"fb_id": fb_id}))

However, it would be better to pass in a call to reverse into the HttpResponseRedirect constructor, but since I don't know your urls.py I just wrote the relative 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