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.