python中redirect如何传值_如何将extra_context传递给“ redirect_to“方法在Django python...

My views.py:

@login_required

def some_views(request):

if request.method == 'POST':

form = AddressCreateFrom(request.POST)

if form.is_valid():

name = form.cleaned_data['Address']

ip_value = form.cleaned_data['value']

user_list = get_username(name)

address_create = form.save()

extra_context = {

'user_list': user_list

}

return redirect_to(request, url=address_create.get_absolute_url())

else:

form = AddressCreateFrom()

extra_context = {

'form':AddressCreateFrom(initial={'user': request.user.pk})

}

return direct_to_template(request,'networks/user_form.html',extra_context)

In form.py:

class AddressCreateFrom(forms.ModelForm):

Address = forms.CharField(max_length=40)

value = forms.CharField(max_length=40)

class Meta:

model = Network

widgets = {

'user': forms.HiddenInput()

}

As you see that i am using Djang model form with two extra Django form field i.e. Address and value in AddressCreateForm class. I need all of the field at the time of rendering the template.

Indeed some_views method are working fine but i also want render some extra data written in context_dictionary i.e. user_list to a requesting URL i.e. address_create.get_absolute_url().

If i am not wrong, if we are handling with the database we have to use redirect_to method. Is it possible to do that?

解决方案

A redirect will return a HTTP response with status code 301 or 302, and the location to redirect to:

301 MOVED PERMANENTLY

Location: http://www.example.com/new-url/

There is no template rendered by the original view, so you can't pass extra_context to it.

The users browser will usually follow the redirect, and request the new url.

If you want to display information about a particular user in the next view, you have to do something like:

design your url pattern to include the user id, e.g. /users/200/,

include it as a get parameter e.g. /users/?id=200, then fetch the user id fromrequest.GET` in the view.

store the user_id in the session

Before redirecting, create a message using the messages framework using the user data.

Then in the view that you redirect to, you can fetch the user from the database, and add it to the template context.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值