django-views

How can I get the username of the logged-in user in Django?

亡梦爱人 提交于 2019-11-28 18:17:57
问题 How can I get information about the logged-in user in a Django application? For example: I need to know the username of the logged-in user to say who posted a Review: <form id='formulario' method='POST' action=''> <h2>Publica tu tuit, {{ usuario.username.title }} </h2> {% csrf_token %} {{formulario.as_p}} <p><input type='submit' value='Confirmar' /></p> </form> In usuario.username.title I get the username, but in the template, I need to get that information from the view. Thanks. =) 回答1: You

What is the equivalent of “none” in django templates?

时间秒杀一切 提交于 2019-11-28 18:04:55
I want to see if a field/variable is none within a Django template. What is the correct syntax for that? This is what I currently have: {% if profile.user.first_name is null %} <p> -- </p> {% elif %} {{ profile.user.first_name }} {{ profile.user.last_name }} {% endif%} In the example above, what would I use to replace "null"? Gerard None, False and True all are available within template tags and filters. None, False , the empty string ( '', "", """""" ) and empty lists/tuples all evaluate to False when evaluated by if , so you can easily do {% if profile.user.first_name == None %} {% if not

How do I set user field in form to the currently logged in user?

旧巷老猫 提交于 2019-11-28 17:55:42
I'm making an election information app, and I want to allow the currently logged-in user to be able to declare himself and only himself as a candidate in an election. I'm using Django's built-in ModelForm and CreateView. My problem is that the Run for Office form (in other words, the 'create candidate' form) allows the user to select any user in the database to make a candidate. I want the user field in the Run for Office to be automatically set to the currently logged-in user, and for this value to be hidden, so the logged-in user cannot change the value of the field to someone else. views.py

How to subclass django's generic CreateView with initial data?

a 夏天 提交于 2019-11-28 17:35:47
I'm trying to create a dialog which uses jquery's .load() function to slurp in a rendered django form. The .load function is passed the pk of the "alert" object. Also available in the class functions are things like self.request.user so I can pre-fill those fields, shown below in the Message model (models.py): class Message(models.Model): user = models.ForeignKey(User) alert = models.ForeignKey(Alert) date = models.DateTimeField() message = models.TextField() Subclassing django's CreateView makes it pretty easy to generate a context with an instance of the ModelForm (views.py): class

Raw SQL queries in Django views

て烟熏妆下的殇ゞ 提交于 2019-11-28 17:31:16
How would I perform the following using raw SQL in views.py ? from app.models import Picture def results(request): all = Picture.objects.all() yes = Picture.objects.filter(vote='yes').count() return render_to_response('results.html', {'picture':picture, 'all':all, 'yes': yes}, context_instance=RequestContext(request)) What would this results function look like? >>> from django.db import connection >>> cursor = connection.cursor() >>> cursor.execute('''SELECT count(*) FROM people_person''') 1L >>> row = cursor.fetchone() >>> print row (12L,) >>> Person.objects.all().count() 12 use WHERE clause

How to Create a form from a json-schema?

时间秒杀一切 提交于 2019-11-28 17:18:54
How to create form from JSON Schema? I am writing code in JavaScript and jquery. With this template part like Form I am creating this with haml and adding this in js file. For backend I am using python. I am using Django framework. So I got some links for create form from JSON Schema. Reference link : http://neyric.github.io/inputex/examples/json-schema.html In my Form : Input elemets : textboxes, textarea, select list, submit and cancel buttons are present. So I want to ask is creating form with JSON schema is feasible or not? If yes then, can you provide some good links? jsonform - Build

Redirect / return to same (previous) page in Django?

前提是你 提交于 2019-11-28 16:58:18
问题 What are the options when you want to return the user to the same page in Django and what are the pros/cons of each? Methods I know: HTTP_REFERER GET parameter containing the previous URL Session data to store the previous URL Are there any other? 回答1: One of the way is using HTTP_REFERER header like as below: from django.http import HttpResponseRedirect def someview(request): ... return HttpResponseRedirect(request.META.get('HTTP_REFERER')) Not sure of cons of this! 回答2: While the question

Django request to find previous referrer

偶尔善良 提交于 2019-11-28 16:57:42
I am passing the request to the template page.In django template how to pass the last page from which the new page was initialised.Instead of history.go(-1) i need to use this {{request.http referer}} ?? <input type="button" value="Back" /> //onlcick how to call the referrer That piece of information is in the META attribute of the HttpRequest , and it's the HTTP_REFERER (sic) key, so I believe you should be able to access it in the template as: {{ request.META.HTTP_REFERER }} Works in the shell: >>> from django.template import * >>> t = Template("{{ request.META.HTTP_REFERER }}") >>> from

Return results from multiple models with Django REST Framework

南笙酒味 提交于 2019-11-28 16:40:50
I have three models — articles, authors and tweets. I'm ultimately needing to use Django REST Framework to construct a feed that aggregates all the objects using the Article and Tweet models into one reverse chronological feed. Any idea how I'd do that? I get the feeling I need to create a new serializer, but I'm really not sure. Thanks! Edit: Here's what I've done thus far. app/serializers.py: class TimelineSerializer(serializers.Serializer): pk = serializers.Field() title = serializers.CharField() author = serializers.RelatedField() pub_date = serializers.DateTimeField() app/views.py: class

Use get_queryset() method or set queryset variable?

六眼飞鱼酱① 提交于 2019-11-28 16:26:05
问题 These two pieces of code are identical at the first blush: class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_poll_list' queryset = Poll.active.order_by('-pub_date')[:5] and class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_poll_list' def get_queryset(self): return Poll.active.order_by('-pub_date')[:5] Is there any difference between them? And if it is: What approach is better? Or when setting