python redirect to another view [duplicate] - python

This question already has answers here:
Django return redirect() with parameters
(4 answers)
Closed 9 years ago.
I want to redirect from a view to another view and passing data but no chance.
Here are my codes :
def affiche(request):
if request.method == 'POST':
form = AfficheForm(request.POST)
if form.is_valid():
Select = form.cleaned_data['Select']
if Select == '1':
return redirect('affiche_all', devise='EURO')
def affiche_all(request, devise):
data = websvc(devise)
return render_to_response('affiche_all.html', {'data': data},
RequestContext(request))
I'm new to django development, so i will appreciate your help.

You need to use reverse to build up your URL to redirect to:
from django.urls import reverse
from django.http import HttpResponseRedirect
def affiche(request):
form = AfficheForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
Select = form.cleaned_data['Select']
if Select == '1':
url = reverse('affiche_all', args=(),
kwargs={'devise': 'EURO'})
return HttpResponseRedirect(url)
This assumes you have a named url pattern that accepts a keyword argument of 'devise', as such:
from django.conf.urls import url, patterns
urlpatterns = patterns('your_app.views',
url(r'^some-path/(?P<devise>[-\w]+)/$', 'affiche_all', name='affiche_all'),
)
That named parameter will look for one or more words and hypens, like a slug. You might want to change that to suit your needs.

try this
return HttpResponseRedirect(reverse('affiche_all', devise=('EURO',)))

Related

Problems with Django URL routing

I'm building a website, to be used in dental practices, however I'm having trouble with the URL routing. I'm wanting af URL pattern like: Denthelp/kartotek/#nameofclinic#/opretpatient.
My suggestion looks like this:
urls.py:
path('kartotek/<str:kl_id>/', views.kartotek, name="kartotek"),
path('kartotek/<str:kl_id>/opretpatient/', views.opretpatient, name="opret_patient"),
Views. py:
def kartotek(request, kl_id):
kliniknavn = Klinik.objects.get(navn=kl_id)
E_patient = kliniknavn.patient_set.all()
context = { 'kliniknavn':kliniknavn, 'E_patient':E_patient}
return render(request,'DentHelp/kartotek.html', context )
def opretpatient(request, kl_id):
kliniknavn = Klinik.objects.get(navn=kl_id)
form = PatientForm()
if request.method == 'POST':
form = PatientForm(request.POST)
if form.is_valid():
form.save()
return redirect('kartotek/<str:kl_id>/')
context = {'form':form, 'kliniknavn':kliniknavn}
return render(request,'DentHelp/kartotek/<str:kl_id>/opretpatient.html', context)
When running code I get an OSError for the last line of code shown here.
Have you guys have any advise for this to work?
You are mixing up render with redirect. render renders a template dynamically with attributes from context, where redirect redirects the user to a different view. To call render, you need to provide template name and context. For redirect, you need to provide url name and parameters (if required). Here is how you should do in your code:
def opretpatient(request, kl_id):
kliniknavn = Klinik.objects.get(navn=kl_id)
form = PatientForm()
if request.method == 'POST':
form = PatientForm(request.POST)
if form.is_valid():
form.save()
return redirect('kartotek', kl_id) # url name and parameter
context = {'form':form, 'kliniknavn':kliniknavn}
return render(request, 'DentHelp/kartotek/opretpatient.html', context) # template name and context

JSONDecodeError at / Expecting value: line 1 column 1 (char 0) when try to return response in a django rest_framework

I'm new to python rest_framework. I am trying to create a django website with two Apps.
The first App has an HTML form which gets a city name from the user and then sends a request to the API in the second App, calls WeatherApp. In the WeatherApp I read data from database and serialize it but when trying to return response, I get this error:
JSONDecodeError at /
Expecting value: line 1 column 1 (char 0)
This is the first App views:
def index(request):
context = {'form': form}
if request.method == 'POST':
form = CityForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
url = "http://127.0.0.1:8000/city/{}"
city_weather = requests.get(url.format(name)).json()
And this is the WeatherApp views:
def myfunc(self, cityname):
query = City.objects.filter(name = cityname)[0]
serializer = CitySerializer(query)
return Response(serializer.data)
Any help would be appreciated.
I figured it out and share the solution for anyone with a similar problem:
The problem was in the return in WeatherApp views.
It should be like this:
return JsonResponse(serializer.data)
and the JsonResponse should import like this:
from django.http import JsonResponse

django-form show form data after saving it

I want to show same data to user as posted by him using form after saving it in database.
I am not getting the logic for it.
I am trying to do something like this:
def CreateDeal(request):
if request.method == "POST":
form = DealForm(request.POST)
if form.is_valid():
form.save(commit = True)
data = form.data
return render(request, '/path_to/deal_detail.html',data=data)
Is it ok ?
Is there any better way to do it?
If you do it this way, a redirect of the "detail" page will resubmit the form. This is generally not desired behaviour.
A better way would be to create a detail view for you saved object (if you haven't already) and redirect the user to the detail view of that particular object:
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
def CreateDeal(request):
if request.method == "POST":
form = DealForm(request.POST)
if form.is_valid():
obj = form.save(commit=True)
return HttpResponseRedirect(reverse('deal-detail-view', args=(obj.id,)))
# or return HttpResponseRedirect(obj.get_absolute_url())
# if `get_absolute_url` is defined

Using data from one view function in another with Django (forms)

I am currently using Django to have users enter data using a form. Using my views.py file, I was able to write a views function that stores the data users enter. However. What I want to do, is take the data the users has enter and use it in another views function in my "views.py" file.
For example, here is my views.py file:
def s(request):
if request.method == 'POST':
search = Search(data=request.POST)
if search.is_valid():
success = True
name = search.cleaned_data['search']
else:
print search.errors
else:
search = Search()
return HttpResponse(name)
What I'd then like to do is create a second view function and be able to call the "name" variable defined above. Anyone know how I could go about doing this? Thanks.
Not sure what you want to do in the second view. Try passing parameters.
from django.shortcuts import render
from django.http import HttpResponseRedirect
def s(request):
search = Search()
if request.method == 'POST':
search = Search(data=request.POST)
if search.is_valid():
return HttpResponseRedirect('/second-url/?name=%s' %(search.cleaned_data['search'],))
return render(request, 'template_name', {'form': search})
def s2(request):
name = request.GET.get('name')
return HttpResponse('hello %s' % name)

HttpResponseRedirect changes view but does not render template

I am new to Django and web programming in general, please don't make the answers too complicated. I have looked up the documentation and questions in here but I can't wrap my head around it.
I have a form and after validating and saving the model to the database I want to redirect the user to a new page. My question is, how do I do it with HttpResponseRedirect(or even the shortcut redirect) correctly, because it redirects the view correctly, the url pattern gets called but when it reaches the view in the views.py something goes array. Why doesn't the template change but the view does?
Can somebody tell me where I am wrong, and how to fix it?
views.py
class CreateSuccess(generic.ListView):
template_name = 'login/successReg.html'
def CreateUser(request):
if request.method == "POST":
form = CreateUserForm(request.POST)
if form.is_valid():
newUser = form.save()
return HttpResponseRedirect('sucess/')
else:
form = CreateUserForm()
return render(request, 'login/addUser.html', {'form':form})
urls.py
urlpatterns = patterns('',
url(r'^$', views.LoginIndex.as_view(), name='loginIndex'),
url(r'^create/', views.CreateUser, name='addUser'),
url(r'^authenticate/', views.LoginUser.as_view(), name='loginUser'),
url(r'^create/success/', views.CreateSuccess.as_view(), name='successReg'),
)
Try returning an reverse() object which constructs the required url for you
if form.is_valid():
newUser = form.save()
url = reverse('your_app:successReg') # Replace your_app with the name of your app
return HttpResponseRedirect(url)
More about reverse():
reverse(viewname)
viewname is either the function name (either a function reference, or
the string version of the name) which means that either you could make viewname a existing function in your views.py or either reference it by its string name in the urls.py
It's always recommended to do it in the form reverse('app_name : name_defined_in_urls')
Note: since your a beginner I dropped those optional args and kwargs parameters which are used if you want to redirect a user to dynamic webpage

Categories

Resources