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

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)

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

Django delete models based on form input

I have a form and a model, in my views I take the data from form and use it to delete the object from my model, but it does not delete the object at all, even though if I use the shell and create the same query set with the same syntax it works. What am I missing here?? Thx
Code from views:
form = SecondForm()
query_list = DictWord.objects.all()
dict_DictWord = {'words': query_list,"form":form}
if request.method == "POST":
form = SecondForm(request.POST)
if form.is_valid():
##Does not delete the object from models
data = form.cleaned_data['name']
DictWord.objects.filter(name=data).delete()
return render(request, 'appone/index.html', context = dict_DictWord)
else:
messages.error(request, "Error")
return render(request,'appone/index.html',context=dict_DictWord)
But if I use manage.py shell, I import my model and this syntax works, and it returns the dict with the deleted object:
from app.models import DictWord
DictWord.objects.filter(name="SomeName").delete()
#try this
record=DictWord.objects.get(name=data)
record.delete()
return render(request, 'appone/index.html', context = dict_DictWord)

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

python redirect to another view [duplicate]

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',)))

Django form submit again on refresh

Hello I am working on a simple form. The form submits fine but if I refresh the page it resubmits the data. Seems the form is holding the data after submit and I assume since after the submit the request method is post. Question is what is the best way after the submit to clear the form in Django. After the submit the form variables should not be holding the values anymore. Thanks
def testimonials(request, template_name="testimonials.html"):
reviews = Reviews.objects.all()
if request.method == 'POST':
form = forms.ReviewsForm(data = request.POST)
# create a new item
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
if form.is_valid():
nameIn = form.cleaned_data['name']
reviewIn = form.cleaned_data['review']
newReview = Reviews(name = nameIn, review = reviewIn)
newReview.save()
return render_to_response(template_name, locals(), context_instance=RequestContext(request))
else:
# This the the first page load, display a blank form
form = forms.ReviewsForm()
return render_to_response(template_name, locals(), context_instance=RequestContext(request))
Typically, you would issue a redirect after processing a form/POST request (this is common web development practice to avoid the resubmission issue you mentioned). So instead of a render_to_response, you might issue a HttpResponseRedirect like so:
if form.is_valid():
# Process form as desired here
# Simple example; use reverse() to avoid hard-coding URLs
return HttpResponseRedirect('/success/')
Check out the using a form in view for a skeleton of how forms are typically processed.
use reverse instead of render to response
if form.is_valid():
nameIn = form.cleaned_data['name']
reviewIn = form.cleaned_data['review']
newReview = Reviews(name = nameIn, review = reviewIn)
newReview.save()
return HttpResponseRedirect(reverse('app_name:url'))
You could also use the 'redirect' shortcut:
from django.shortcuts import redirect
...
return redirect(newReview)
This is assuming you have get_absolute_url defined in your Review Model.
See the docs for more info.

Categories

Resources