Django, How to pass data object from one template to another template - python

I have one data object list in the view and passing it to the template to summarize the the list.
Now, from that template I want to take the data object to the next page (template) to display the details of the data object.
In my view.py
schools = PublicSchools.objects.all()
return render_to_response('searchresult.html', {'schools': schools}, context_instance=RequestContext(request))
In my template searchresult.html, I am listing the summary data of schools.
In turn I want to send the single school object to the next template (dateils.html) to display the details of particular school.
Can some one please help?
Thanks,

You can write another view to handle your requirement
Try this sample code
URL
# pass the selected school id form template to your view
url(r'^school/(?P<school_id>\d+)/$', schoolDetails),
views
def schoolDetails(request, school_id):
try:
school = PublicSchools.objects.get(pk=school_id)
except school.DoesNotExist:
raise Http404
return render(request, 'detail.html', {'school': school})
Hope this helps you :)

Related

Displaying the content on a different html based on the primary key

I am using Django to create a site. I have Table called notice as below
Models.py
class Notice(models.Model):
Notice_No=models.AutoField(primary_key=True)
Content=models.TextField(max_length=5000, help_text="Enter Owner Name")
I am using a for loop to display the all these fields on my template page as
Notice No, Content, Date of issue, Date of expiry. I have provided a hyperlink to the all the content values which take it to another HTML play with a proper notice formal of a CHS. Now what I wanna do is if I click on let's say notice of notice no-1. I only want to display the content of that notice on the next page. If I click on notice _no 2, it should only display the contents of that notice. I'm new to python so not sure how to do this. How do I go about this?
Notice.html is the page that displays the table. Noticesoc.html display is where the content should be displayed.
views.py
def notices(request):
Notice_all=Notice.objects.all()[:50]
return render(
request,
'notices.html',
context={'Notice_all':Notice_all}
)
def noticesoc(request):
Notice_all=Notice.objects.all()
return render(
request,
'noticesoc.html',
context={'Notice_all':Notice_all}
)
Send the primary key of the data you want to see in detail.
<td style="color:white; font-family:helvetica; font-size:15px;">
<a class="nav-link" href="{% url 'noticesoc' Notice.pk %}">
Click here to view the contents</a>
</td>
url( r'^noticesoc/(?P<pk>\d+)/$', 'noticesoc')
Then in the view. Use .get to get the information Notice and then render it.
Ex:
def noticesoc(request, pk):
Notice=Notice.objects.get(id=pk)
return render(
request,
'noticesoc.html',
context={'Notice_all':Notice}
)
in reference to this ....
Still doesn't work. Error=local variable 'Notice' referenced before assignment. Can you see my url.py(previous comment) and see if it's correct
you will notice that the model name and the function name are similar hence instead of django differentiating the two it assumes them as similar with the first code to run as the model then the view function
try to use another name for your view function and call the name different and unique from the model name for instance
def noticesoc(request, pk):
Notice=Notice.objects.get(id=pk)
return render(
request,
'noticesoc.html',
context={'Notice_all':Notice}
)
use this instead
def noticesoc(request, pk):
note=Notice.objects.get(id=pk)**
return render(request,'noticesoc.html',context={'note':note}
emphasized text

Querying the Sqlite database for a user with username "x" using the standard django.contrib.auth.models.User model

I'm trying to wrap my head around an issue I'm having.
I want to present the users with a page in which they can look up a user by entering his username.
Yet I can't wrap my head around how to do this. Do I provide a function in my view in which a query is executed that retrieves a user from the database? For example retrieve his username or id and go to his profile page? I can't seem to grasp how to do this, I have been looking for examples on this but I can't find anything so I hope someone here can help me out!
Yes, at the simplest level you would have a view that accepts a form submission which takes the value of the field and does something like User.objects.get(username=my_variable) and returns the results, if any. You should wrap the call in a try/ except block so your view doesn't blow up if no such user exists with that username. Django provides a shortcut function for doing just this, so instead of the line above you could do user = get_object_or_404(User, username=my_variable). Your whole view would look something like
from django.shortcuts import render, get_object_or_404
def username_search(request):
# if there are any form values sent in a GET
if request.GET:
my_variable = request.GET.get('username', '')
user = get_object_or_404(User, username=my_variable)
else:
user = None
return render(request, 'some_template.html', {'user': user}
In reality you might also create a Django form to do some validation on the submissions and make it easier to render your form.

What's the best way to link views and pass data between them?

I have a basic diary application that has two views: Add and Edit view. When user hits 'Add' button on Add view, the data is saved into database and simple message is shown. When user hits 'Update' button on Edit View, the data is updated and a last update stamp is added.
So far these views run independently. The Edit View by default loads the last saved entry and allows for that to be updated.
I want to update it so that upon successful addition of new diary entry on the Add View, it transitions to the Edit View to allow the user to Edit and Update if they want to. How do I link the views together and pass the relevant data to Edit View to know which Entry (database object) to fetch for edit? Also I would like to be able to use the Edit View independently to fetch a specified diary entry for example on a GET. So the Edit View is agnostic to whomever called it, it just knows which diary entry to load.
The code for Add and Edit View as they are now, are displayed below:
def addEntry(request):
entryForm = None
if request.method == "POST":
entryForm = EntryForm(request.POST)
if entryForm.is_valid():
entryForm.save(commit = True)
request.method = "GET"
return entrySubmitted("Entry has been submitted")
else:
logger.info(entryForm.errors)
else:
# Set up view with new entry form
entryForm = EntryForm()
template = getEntryViewTemplate(entryForm)
return render(request, "DiaryEntry.html", template)
def editEntry(request):
# Get the latest entry from the database
entry = Entry.objects.last();
if request.method == 'GET':
entryForm = EntryForm(instance = entry)
else:
entryForm = EntryForm(request.POST, instance = entry)
if entryForm.is_valid():
entryForm.setLastUpdated(datetime.now())
entryForm.save(commit = True)
templateData = getEntryViewTemplate(entryForm)
return render(request, "EditEntry.html", templateData)
Thanks in Advance,
Francis
Look django documentation about Class Base View.
https://docs.djangoproject.com/en/1.10/topics/class-based-views/intro/#
You can create a class, with different method.
Get, Post(create object), Put(Update object)
And you have a lot of methods and attributes usefull.
You can link your class view to a specific model (Entry) for example.
https://docs.djangoproject.com/fr/1.10/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin.get_queryset
How do I link the views together and pass the relevant data to Edit View to know which Entry (database object) to fetch for edit?
You need to pass ID Object to edit. Two solutions. In your Post data. Or by argument in your url.
http://your_web_site.com/entry/id_entry/
And you init your form with entry data
In your URL django you can link to url to your class base view.
url(r'^entry/$', views.EntryView.as_view(), name='create_entry'),
url(r'^entry/(?P<pk>[-\w/]+)$', views.EntryView.as_view(), name='update_entry'),
I hope this will help you

django forms, cleaned_data is empty

I have been playing around with forms a little and cant seem to understand why cleaned_data is not giving me any usable output (aka the dict appears to be completely empty). What id like to do is have a form on a page with two date selector so the user can select a from and to date that Django will then query a database that has periodic thermocouple measurements and create a table.
views.py
def temperature_data(request):
date_select_form = CalLabDateSelect(request.POST)
if request.method == 'POST':
if date_select_form.is_valid(): # All validation rules pass
print "this should be some date/time data from date_select_form:", date_select_form.cleaned_data
#return HttpResponseRedirect('/test_page/') # Redirect after POST
raw_data = Callab.objects.all().using('devices').order_by('-time')
return render_to_response("temperature_display.html",
locals(),
context_instance=RequestContext(request))
forms.py
def make_custom_datefield(f):
formfield = f.formfield()
if isinstance(f, models.DateField):
formfield.widget.format = '%m/%d/%Y'
formfield.widget.attrs.update({'class':'datePicker', 'readonly':'true'})
return formfield
class CalLabDateSelect(forms.Form):
formfield_callback = make_custom_datefield
when i visit the page and select a date then submit the form i see this outputted to the console:
QueryDict: {u'date': [u'10/04/2014'], u'csrfmiddlewaretoken': [u'C5PPlMU3asdFwyma9azFDs4DN33CMmvK']}
this should be some date/time data from date_select_form: {}
all i notice is that the dictionary is empty {} but the request.POST data shows 10/04/2014???
any ideas why this is happening??
And thank you all very much for any help in understand this!!
Your form doesn't actually define any fields, so I don't know what you're expecting to get in cleaned_data. formfield_callback is only useful in a ModelForm, where it operates on the fields already defined by a model: but your form is not based on a model.
Either use a model form, or define your form fields explicitly in your form class.

How to pre-populate Django form with part of URL?

I'm completely new to programming (Django), and I'm trying to pre-populate a django_messages form with a snippet of the URL.
For example, for a compose form at www.mywebsite.com/compose_root/Chris88, I want the "Recipient" field to be pre-populated with "Chris88".
Is there any way to do this? In urls.py, I have:
url(r'^compose_root/(<recipient>[\w.#+-]+)/$', compose, name='messages_compose_to'),
I already tried plugging in recipient as an initial in the "Recipient" form field, but it didn't work, so it might be easier just to pre-populate with an excerpt of the URL.
Help is much appreciated.
Assuming you have a form that looks something like:
class New_form(Form.form):
... FormStuff
recipient = Some Field
Add a view that looks like:
def compose_root(request,recipient):
...# View Stuff
form = New_form(initial={"recipient": recipient})
return render_to_response('form-template.html', {'form':form})
And in your form-template
{{form}}

Categories