How to pass two variable from views to the html in Django - django

I have taken the objects from the tables into 2 variables. Now i want to send the values of those variables to html using render_to_response.
def AssetMovement(request):
print "AssetMovement"
feature_list = request.session['feature_list']
featuresgroups = request.session['featuresgroups']
pplid=request.session['pplid']
empnm = Asset_Assignment_Employee.objects.filter(Employee__People=pplid)
print empnm
id_obj = Asset_Track.objects.all()
print id_obj
report = reports.astmvmt_repo(queryset=id_obj)
report.generate_by(PDFGenerator, filename= 'E:\My Work Location\Example\WorkSpace\\asset_track1\media\\'+str(2)+".pdf")
return render_to_response('asset_mgmt/astmvmtReport.html',{"contacts":feature_list,'root': settings.MEDIA_ROOT,'len':len(feature_list)-1,"featuresgroups":featuresgroups,'assertlist':id_obj})
Like above, I have send id_obj through 'assertlist' now i want to send empnm object with the same name i.e, 'assertlist' and display in the table.
Kindly try to answer this question as soon as possible. Thank You.

Aside from the comments above, another option is to use the {% with %} template tag to re-assign the variable: https://docs.djangoproject.com/en/1.4/ref/templates/builtins/#with

Related

Django filtering in views.py with a session variable

I sessions up and running and currently I'm getting the variable 'context_number' set in the browser. In the view I would like to filter on this variable. So I have this in my views.py.
def allcontexts(request):
allcontexts = Context.objects.all()
return render(request, 'context_manager/context_manager.html',
{
'allcontexts':allcontexts,
})
In order to filter I change the second row to the following
allcontexts = Context.objects.filter(context_number=____)
In the blank I want to insert the context_number variable, so context_number[dbcolumn] = context_number[session variable]
I can't seem to figure out the correct syntax, any ideas?
You can access session variables using request.session.get() syntax:
allcontexts = Context.objects.filter(context_number=request.session.get("context_number"))

Why is Django Paramaterized query not working

I have been struggling with this simple query in django. I have checked a lot over internet. I tried using similar syntax - yet no luck.
In my application on html page I need to display some specific record. And for that i want to use parameterized select statement. But the query is not working..
I have checked id2 is getting correct value from previous html page..
And I know I can use APIs but for my databases classes I need to use raw queries in my application.
Can someone please help me here...
def details(request, id2):
temp = 'test3'
data = Posts.objects.raw('''select * from posts_posts where posts_posts.id = %s ''', id2)
context ={
'post' : data,
If you run that code you will see an error, since that is not the correct format for a call to raw. If you can't see the error output anywhere, then you have yet another problem for another post.
The correct format for raw is: .raw(sql, iterable-values), like this:
posts = Posts.objects.raw("select * ..", [id2, ]) # or use (id2,) for a tuple
<RawQuerySet: select * from ... where id = 5>
To get the actual list, since that just gives you a Query, you need to evaluate it somehow:
posts_list = list(posts)
first_post = posts[0]
Be careful, if you don't evaluate the QuerySet then it can be re-run a second time. Please convert it to a list() before doing further operations on it.

Django: How to access the model id's within an AJAX script?

I was wondering what is the correct approach,
Do I create HiddenInput fields in my ModelForm and from the
View I pass in the primaryKey for the models I am about to edit into
the hiddenInput fields and then grab those hiddenInput fields from
the AJAX script to use it like this?
item.load(
"/bookmark/save/" + hidden_input_field_1,
null,
function () {
$("#save-form").submit(bookmark_save);
}
);
Or is there is some more clever way of doing it and I have no idea?
Thanks
It depends upon how you want to implement.
The basic idea is to edit 1. you need to get the existing instance, 2. Save provided information into this object.
For #1 you can do it multiple ways, like passing ID or any other primary key like attribute in url like http://myserver/edit_object/1 , Or pass ID as hidden input then you have to do it through templates.
For #2, I think you would already know this. Do something like
inst = MyModel.objects.get(id=input_id) # input_id taken as per #1
myform = MyForm(request.POST, instance=inst)
if myform.is_valid():
saved_inst = myform.save()
I just asked in the django IRC room and it says:
since js isn't processed by the django template engine, this is not
possible.
Hence the id or the object passed in from django view can't be accessed within AJAX script.

Sharing data between two views through template in Django?

I may have overcomplicated things.
I have two views. The first view generates a bunch of temporary data based on the user's input from the form. Each of the generated data contains a name and misc data. I want to pass only the names to the template to be rendered as a list of hyperlinks. If the user clicks on one of them, the second view should be given the specific name the user clicked on so that the view can manipulate it. The only problem is, I don't know how to get the misc data associated with the name.
The misc data generated could contain random characters that's not a standard character in URLs, so I can't turn misc into a hyperlink like I can with just the name.
I have something like this:
views:
# Displays the temp data names
def display(request):
return render_to_response('display.html',{},context_instance=RequestContext(request))
# User provides input, generate temp data to be displayed as hyperlinks
def search(request):
form = SearchForm(request.POST)
if form.is_valid():
usr_input = form.cleaned_data['input']
data = generate_data(usr_input) # generates a list of (name, misc) data.
request.session['hyperlinks'] = get_list_names(data) # returns only names in data
return HttpResponseRedirect('views.display')
else:
....
# User has clicked on a hyperlink, we must process specific data given its name.
def process_data(request, name):
# How to get associated misc data created from search()?
I haven't written the template yet, but the idea is:
template:
{% for name_link in request.session.hyperlinks %}
<a href={% url process name_link %}>
{% endfor %}
One solution could be creating a bunch of session variables:
for name in get_list_names(data):
request.session[name] = // associated misc data
But this seems like a waste. Plus I'd have to manage deleting the session variable later on since this is only temporary data generated based on user input. A new input from the user would create another huge horde of session variables!
Another solution could be to store it temporarily in the database, but that also seems like a bad idea.
EDIT - Trying out suggestion by christophe31:
I'm not quite sure if I understand your suggestion, but is it something like this?
data_dict = {name1:misc1, name2:misc2, etc...}
encoded = urllib.urlencode(data_dict) # encoded = 'name1=misc1&name2:misc2...etc'
request.session['hyperlinks'] = encoded
A few questions on this though:
1) Wouldn't encoding it using urllib defeat the purpose of having a dictionary? It returns a string rather than a dictionary
2) To expand on (1), what if the misc data had '&' and '=' in it? It would screw up parsing which is the key and value by the second view. Also, misc data may have unusual characters, so allowing that to be part of the url to be displayed may be bad.
3) Does Django protect from allowing the user to maliciously modify the session misc data so that the misc data generated from the first view may be different than the one passed to the second view? That would be a problem!
You may want to put a dictionary as a session variable, set a cookie, or pass as get argument throught the link your data.
For me you have to put all these data in a dictionary before export it as get parameters (with urllib2) or store it in your user's session.
Ask me if you want more info on a suggested way.
Edit:
They are 2 ways I see, by session:
data_dict = {name1:misc1, name2:misc2, etc...}
request.session['hyperlinks'] = data_dict
Or passing to the template the data if no session backend:
data_dict = {name1:misc1, name2:misc2, etc...}
encoded = urllib.urlencode(data_dict)
return render(request, "my_template.html", {"url_params":encoded,}
and
Go to results

The linkcolumn about django-tables2

I use django-tables2 to show some data in page,and now I want to make the cell link to some url,but the link url such as :
url(r'^(?P\w+)/(?P\d+)/$', 'pool.views.pooldatestock',
name="pool_date_stock"),
and I read the documents of django-tables2,but I can't find some excample about this problem.
the tables show in the page's url just like:http://127.0.0.1:8000/pool/20111222/
I try to write this in my tables.py :
class PoolTable(tables.Table):
number = tables.LinkColumn('pool.views.pooldatestock', args=[A('number')])
date = tables.Column()
and then I try to write:
class PoolTable(tables.Table):
number=tables.LinkColumn('pool.views.pooldatestock',
args=[A('date')],
kwargs=A('number')])
date = tables.Column()
but it's error too...
somebody can tell me how to solve this problem?or should I create my own table view, without django-tables.
Thanks.and Merry Christmas:)
It makes no sense for the kwargs parameter to be given a list, it should be given a dict. However as your URL doesn't used named groups, it doesn't need keyword arguments anyway. Just put both URL parameters in the args parameter:
class PoolTable(tables.Table):
number = tables.LinkColumn('pool.views.pooldatestock',
args=[A('date'), A('number')])
date = tables.Column()