using get or post to pass argument to django view - django

In my django app ,I need to call a view with an argument named 'year'. Then in the template,I created a form and a dropdown list using a list of year names,At this point,I am confused as to how the view should be invoked.
The view is named 'create_report_for_data_of_the_year'.It expects a year argument.
ie,
http://127.0.0.1:8000/myapp/reports/2011
I tried to write the template as shown below.
<li id="yearlydataplots" class="report">
<form action="create_report_for_data_of_the_year" >
<select name="year" id="year">
{% for anyear in years %}
<option value={{anyear}} > {{anyear}}</option>
{% endfor %}
</select>
<input type="submit" value="Plot for entries of the year"/>
</form>
</li>
However,when the submit button is clicked,the browser goes to
http://127.0.0.1:8000/myapp/reports/create_report_for_data_of_the_year?year=2006
which causes a 404.
I changed method="post", and clicking submit goes to
http://127.0.0.1:8000/myapp/reports/create_report_for_data_of_the_year
which again causes 404
I know,I am missing something very basic :-)..If someone can kindly point it out,it would be nice
thanks in advance,
mark
def create_report_for_data_of_the_year(request,year,page_title,template_name):
dataset=MyDataModel.objects.filter(today__year=year,creator=request.user)
#today is a field in MyDataModel and is a datetime.datetime
map = create_map_of_names_and_values(dataset)
basefilename = "plotofdataforyear%s"%year
page_title = page_title+" "+year
imgfilename= create_plot(map,basefilename)
report_data={'basefilename':basefilename,'plot_image':imgfilename,'year':year,'page_title':page_title}
report_data["name_value_dict"]=map
req_context=RequestContext(request,context)
return render_to_response(template_name,req_context)
and url mapping is
...
url(r'^reports/(?P<year>\d{4})/$','myapp.views.create_report_for_data_of_the_year',
{
'template_name':'myapp/report_for_data_of_the_year.html',
'page_title':'report for data in the Year'
},name='report_data_for_year' ),
...

You need to do a redirect to desired page with JS. Or you can accept a year as a get paramener with year = request.GET.get('year').

Related

How to use loop for requesting from html template in Django

From html template say "createlist" I want to add link which actually request server to get one more object of image form to the "createlist" page. But when I run the code it actually happens only one time but I want maximum of 5 times this should be accepted. So here how I can use loop in html template so that it will get the request again and again up to the limit say 5.
here is the template code -
{% if morepicform %}
{{ morepicform }}
{% endif %}
Want to add more pics? <a href="{% url 'createlist' 'morepic' %}" role="button">
<img src="static/auctions/plus-circle-solid.svg" height="20px" width="20px"></a>
views function
def morepic(request, morepic=''):
return render(request, "auctions/createlist.html",{
"morepicform" : PictureForm(),
"picform" : PictureForm(),
"listform" : ListingForm()
})
url pattern path function -
path("createlist/<str:morepic>", views.morepic, name="createlist")
Now how can I add the functionality of requesting "morepicform"?

Django filters - adjusting box width

With django_filters, I have my filterset, everything works fine it's just the display that I am stuck with (box width).
As you can see below, I have changed the "size" attribute of some of the filter options - because the default is too wide. But the "rating" one, which is a NumberInput, doesn't work for some reason. The "size" attribute works for TextInput but not NumberInput.
I want to change the size or rather the width of the NumberInput box that will be displayed in the template (see template pictures below).
Can anyone help? Thanks in advance!
class ReviewFilter(django_filters.FilterSet):
comments = CharFilter(field_name='comments', lookup_expr='icontains', label="Comments ", widget=TextInput(attrs= {'size': 15 } ))
role_title = CharFilter(field_name='role_title', lookup_expr='icontains', label="Role title ", widget=TextInput(attrs={'size': 15 } ))
date_range = DateRangeFilter(field_name="date_created", label=" Posted date ")
**rating = CharFilter(field_name="rating", lookup_expr='gte', label="Minimum rating ", widget=NumberInput(attrs={'size': 1 } ))**
class Meta:
model = Review1
fields = '__all__'
exclude = {'recruiter', 'date_created', 'user'}
I have this:
Screenshot - Look at "Minimum rating" box width
But I want this:
Screenshot with filter search bar - Look at "Minimum rating" box width
I found a solution in the thread below by using the attribute - "style" : 'width6ch'
Apparently NumberInput doesn't have a working "size" attribute in HTML yet.
Solution to my problem
You cannot directly style the django-filters search fields. I was stuck with the same problem and here is my way of solving it.
Step 0 : intall widget_tweaks by pip install django-widget-tweaks
step 1 : add widget_tweaks to INSTALLED_APPS in your settings.py
step 2 : add {% load widget_tweaks %} into your template.html
step 3 : style individual elements in template
<div class="form-group col-sm-4 col-md-3">
{{ filter.form.comments.label_tag }}
{% render_field filter.form.comments class="form-control" %}
</div>
<div class="form-group col-sm-4 col-md-3">
{{ filter.form.role_title.label_tag }}
{% render_field filter.form.role_title class="form-control" %}
</div>
this way you can style individual form elements from filters, you can also add html tag attributes such as type or class and style them based on your needs.
you can use this link for reference. Link for Reference

Pass a parameter across views - Django

I have the following scenario:
I have created globalModels (Season, Team, Player, Referee). Also, I have created seasonalModel (SeasonTeam, SeasonPlayer, SeasonReferee) as I want to record statistics from a Team every particular season, same with Player and Referee) and also I will aggregate statistics from every SeasonTeam into the globalModel Team.
I am building platform for administration. So I have next urls:
adminSite.urls
url(r'^$', views.homeAdmin, name='homeAdmin'),
url(r'^addGlobal/', include('globalModels.urls', namespace='addGlobal')),
url(r'^addSeasonal/', include('seasonalModels.urls', namespace='addSeasonal'))
globalModels.url
url(r'^$', admin_views.addGlobal, name='addGlobal'),
url(r'^addSeason/', views.addSeason, name='addSeason'),
url(r'^addPlayer/', views.addPlayer, name='addPlayer'),
url(r'^addTeam/', views.addTeam, name='addTeam'),
url(r'^addReferee/', views.addReferee, name='addReferee')
Now, in order not to have to choose the season (foreignKey in every seasonalModel) everytime I want to add a new seasonalModel, I want to make a first step of choosing the season, and then let the administratos choose between adding a seasonalTeam, seasonalPlayer...
How would you accomplish this? I have thought about 2 possibilities:
FRONT END
Display with a list of the seasons registered as divs and with JS get the id that the administrator has click on:
{% for season in seasons %}
<div id="{{ season.season }}" class="adminButton chooseSeason ">
{{ season.season }}
</div>
{% endfor %}
And then pass it inside the url:
$(".chooseSeason").click(function (){
var season = $(this).attr('id');
window.location.href = "http://localhost:8000/admin-site/addSeasonal/" + season + "/";
})
In this case, I have my:
seasonModels.py
url(r'^chooseSeason', admin_views.addSeasonalChooseSeason, name='addSeasonalChooseSeason'),
url(r'^([0-9]{4})-([0-9]{4})/', admin_views.addSeasonal, name='addSeasonal'),
url(r'^([0-9]{4})-([0-9]{4})/addTeam/', views.addSeasonalTeam, name='addSeasonalTeam'),
url(r'^([0-9]{4})-([0-9]{4})/addPlayer/', views.addSeasonalPlayer, name='addSeasonalPlayer'),
But I am missing how to make the register the namespace properly:
addSeasonal.html
<div id="addTeamButton" class="adminButton">
Añadir Equipo
</div>
<div id="addPlayerButton" class="adminButton">
Añadir Jugador
</div>
'addSeasonalTeam' is not a registered namespace inside 'admin-site:addSeasonal'
Any idea on how to avoid this problem?
BACK END
Pass as a ModelForm the available seasons registered, and use the submitted as a parameter passed with the request in order to filter in the view that will be used to add the new object in the database
In this case, if season as a globalModel is a charField, how can I force the form to be a list of option with the seasons registered insted of a charField expecting an input?
Sorry for the long post, I hope you could understand my intention and help me.
Thanks in advance!
PR

django tags and html buttons

In my base.html I have:
blabla
{% ifequal alterprofile no %}
{% include 'registration/submittedprofile.html' %}
{% else %}
{% include 'registration/submittedprofile2.html' %}
{% endifnotequal %}
blabla
In views.py I have alterprofile = "no".
How do i change alterprofile to "yes". This is my submittedprofile:
<form action="" method="get">
blablabla
<input type="submit" value="Make Changes">
</form>
And this is my views.py:
def userprofile(request):
alterprofile = "no"
username = request.user
return render_to_response('registration/userprofile.html', {'user': username, 'alterprofile' = alterprofile})
Is there anyone who can code the answers for me. I've tried playing round with the previous answers but to no affect.
Django variables are rendered from the server side, so you can not change the variable after it was passed to your template. What you want to achieve is done via frontend scripting.
In this case you would pass both variables to the django template, save them in your Javascript and then switch them once you clicked the button you mentioned (via onClick event handling).
You can use url arguments like:
/myurl/
/myurl/?show2
then, in your views.py you can use request.POST['show2'] to check if exists and then send a variable again to the view to be checked with your {if}s
As an aside note, either you don't understand basic request flow with web applications or you are not explaining properly what you mean with "html button", so you are not fluent with html language. Sorry if my intuition is harsh or wrong.
its not that clear what you are asking but here is how to make the logic work as I think you want it based on yoru submitted code:
in your template change it to
ifequal alterprofile "no"
to include registration/submittedprofile.html.
When you change the view to alterprofile = "yes" the registration/submittedprofile2.html will be included instead if you keep your current template logic.
This is because in your view, alterprofile is assigned a string therefore its always a string. When you tried to test against no instead of "no" django was looking for a variable called no which doesn't exist.
This means that everytime you run it would have always included registration/submittedprofile2.html

Django Custom Template Tag with Context Variable Argument

I have a custom template tag which shows a calendar. I want to populate certain items on the calendar based on a dynamic value.
Here's the tag:
#register.inclusion_tag("website/_calendar.html")
def calendar_table(post):
post=int(post)
imp=IMP.objects.filter(post__pk=post)
if imp:
...do stuff
In my template, it works fine when I pass a hard coded value, such as
{% load inclusion_tags %}
{% calendar_table "6" %}
However when I try something like {% calendar_table "{{post.id}}" %} , it raises a error a ValueError for the int() attempt. How can I get around this?
You want {% calendar_table post.id %}; the extra {{ and }} are what are causing you the heartburn.
Note that, in your custom tag, you need to take the string ("post.id") that gets passed and resolve it against the context using Variable.resolve. There's more information on that in the Django docs; in particular, look here: http://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#passing-template-variables-to-the-tag