django-settings-export not passing variables - django

I am using Django 1.11 and django-settings-export, but it is not working for this view:
from django.shortcuts import render_to_response
def foo(request):
return render_to_response('foo.html', {})

Fixed changing render_to_response to render.
from django.shortcuts import render
def foo(request):
return render(request, 'foo.html', {})
Checking Django documentation, render_to_response is not recommended and will be deprecated.
This function preceded the introduction of render() and works similarly except that it doesn’t make the request available in the response. It’s not recommended and is likely to be deprecated in the future.

Related

Best way to do simple API calls between Django server and android application?

I'm building a system where I store a Member model on a Django server, one of the attributes of Member is score which is what I want to change using API calls. My question is what would be the best way to do this? I looked into the Django REST framework but it seems a bit overkill for what I'm trying to do. I've been trying to pass the necessary information through the url using regular expressions but I'm unsure if it will work. Outline of what I need is below
iOS/Android app makes request sending pk and score to add to total
server updates appropriate model instance and returns True/False to app depending if save was successful
You can achieve this by this quite dirty solution:
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('<int:member_id>/<int:score_to_add>/', views.update_score, name='update_score'),
]
views.py
from django.http import HttpResponse
from .models import Member
def update_score(request, member_id, score_to_add):
member = Member.objects.get(pk=member_id)
member.score += score_to_add
try:
member.save
return HttpResponse("True")
except:
return HttpResponse("False")
Also you can respond with Json. Here is alternative views:
Alternative views.py
from django.http import JsonResponse
from .models import Member
def update_score(request, member_id, score_to_add):
member = Member.objects.get(pk=member_id)
member.score += score_to_add
try:
member.save
return JsonResponse({'status': True})
except:
return JsonResponse({'status': False})
But i think Django Rest Framework is a better way to do this.
You can create a view to return JsonResponse. Take example of polls app in django and convert a post view to return a JSON response.
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.http import JsonResponse
from .models import Choice, Question
# Need to disable csrf here
#csrf_exempt
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
# If you want Json requests Or you can use
# received_json_data=request.POST if you are using normal form data request.
received_json_data=json.loads(request.body)
try:
selected_choice = question.choice_set.get(pk=received_json_data['choice'])
except (KeyError, Choice.DoesNotExist):
# If failed
return JsonResponse({'result': False})
else:
selected_choice.votes += 1
selected_choice.save()
return JsonResponse({'result': True})
Although It works but I would still recommend using DRF because what you are doing needs proper REST API and DRF eases a lot of pain points.

rendor_to_response is not defined error in django

This is my views.py code.
from __future__ import unicode_literals
from django.template import RequestContext
from django.shortcuts import render_to_response
def index(request):
context = RequestContext(request)
context_dict = {'bold-message': "I am bold font from the context"}
return render_to_response('rango/index.html', context_dict, context)
After starting the project when I run this in server, I am getting the following exception.
Global name 'rendor_to_response' is not defined
Please tell what I did wrong.
rendor_to_response is a typo. It should be render_to_response.
However, you shouldn't be using render_to_response at all. You should use the render shortcut instead.
from django.shortcuts import render
def index(request):
context_dict = {'bold-message': "I am bold font from the context"}
return render(request, 'rango/index.html', context_dict)
If you are following a tutorial that is using render_to_response then it is out of date. You should switch to an updated version of the tutorial, or a different tutorial.

Custom error pages using django 1.10

Hello I'm newbie in Django,
I'm looking to creating custom error pages to my app and found this site: http://blog.eliacontini.info/post/118617321553/django-custom-error-pages
However the 'render_to_response' is not used in Django 1.10
How do I transcript this code to Django 1.10
With best regards.
render_to_response() still works in Django 1.10, but if you want to use the more classical approach, you can use render(). Example:
from django.shortcuts import render
def myview(request):
if request.METHOD == 'GET':
context = {}
return render(request, 'index.html', context, status=404)
Django 1.10 passes three parameters to the page_not_found (https://docs.djangoproject.com/en/1.10/ref/views/#django.views.defaults.page_not_found)
create a function in your custom exceptions view
from django.shortcuts import render
def page_not_found(request, exception, template_name='404.html'):
return render(request, "page-not-found.html", context=None, status=404)
then add this line to your urls.py
handler404 = 'path_to_exceptions_view.page_not_found'

A weird Django error

This is my views.py:
# Create your views here.
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.db import models
from display.forms import CodeForm
from display.forms import CodeFormSet
from ExamPy.questions.models import QuestionBase
def codepost(request):
if request.method == 'POST':
form = CodeFormSet(request.POST)
if form.is_valid():
titles = []
for i in range(0, self.total_form_count()):
form = self.forms[i]
title = form.cleaned_data['title']
if title in titles:
raise forms.ValidationError("Articles in a set must have distinct titles.")
titles.append(title)
return render_to_response('quesdisplay.html')
else:
form = CodeFormSet()
return render_to_response('quesdisplay.html', {'form':form})
Thus, when I click on submit button, it should show the quesdisplay.html without any form in it. But, it is taking me to some contact page which doesn't even exist.
Error:
The current URL, contact/, didn't match any of these.
I've tried all possible ways to debug this but its not possible as there is no trace of anything called "contact" in this.
Edit:
This is the warning I get:
/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py:101: UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.
warnings.warn("A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.")
[10/Nov/2011 05:34:17] "
As seen in the comment before, using Requestcontext solve your problem.
Here is the documentation about csrf_token : https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#how-to-use-it
As we can read :
Use RequestContext, which always uses
'django.core.context_processors.csrf' (no matter what your
TEMPLATE_CONTEXT_PROCESSORS setting). If you are using generic views
or contrib apps, you are covered already, since these apps use
RequestContext throughout.
So here it seems we're not using a generic view, neither a contrib app.
So what we need it to pass the RequestContext because it's like that csrf protection works in Django.
from django.core.context_processors import csrf
from django.shortcuts import render_to_response
def my_view(request):
c = {}
c.update(csrf(request))
# ... view code here
return render_to_response("a_template.html", c)
or
from django.views.generic.simple import direct_to_template
def app_view(request):
return direct_to_template(request, 'app_template.html', app_data_dictionary)
or
from django.shortcuts import render_to_response
from django.template import RequestContext
def app_view(request):
return render_to_response('app_template.html',
app_data_dictionary,
context_instance=RequestContext(request))
Also the documentation speaks about : extras/csrf_migration_helper.py script.
Seems to be helpful for your case :)
Hope it helps ;)

How to set or get a cookie value in django

This is my code:
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django import http
from django.http import HttpResponse
def main(request, template_name='index.html'):
HttpResponse.set_cookie('logged_in_status', 'zjm1126')
context ={
'a':a,
'cookie':HttpResponse.get_cookie('logged_in_status'),
}
return render_to_response(template_name, context)
#return http.HttpResponsePermanentRedirect(template_name)
It raises this exception:
unbound method set_cookie() must be called with HttpResponse instance as first argument (got str instance instead)
What can I do?
You can't just start calling methods on the HttpResponse class, you have to instantiate it e.g. response = HttpResponse("Hello World"), call the cookie method, and then return it from your view.
response = render_to_response(template_name, context)
response.set_cookie('logged_in_status', 'never_use_this_ever')
return response
# remember my other answer:
# it's a terrrible idea to set logged in status on a cookie.
To get the cookie:
request.COOKIES.get('logged_in_status')
# remember, this is a terrible idea.
In case you want the raw cookie string (tested with Django 4.1)
request.META.get('HTTP_COOKIE')