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 ;)
Related
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.
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.
I'm new to django. Problem: to see my homepage (that shows the default django login form)
i have to write the addess:
x.x.x.xxx:8001/login
I would like to access it directly through that:
x.x.x.xxx:8001
What i can see now if i digit x.x.x.xxx:8001, is the login page without the form.
I have:
in my urls.py:
urlpatterns = patterns('',
url(r'^$', 'license.views.index', name='auth_login'),
in my views.py
from django import template
from django.shortcuts import render_to_response
from django.views.decorators.vary import vary_on_cookie
#vary_on_cookie
def index(request):
return render_to_response('login.html', {
}, context_instance = template.RequestContext(request))
That is because you are not passing a login form instance to your form.
Unless you want to perform some custom stuff in your view, your best bet is to use Django's built-in login view. You can set a custom template for it:
url(r'^$', 'django.contrib.auth.views.login', {'template_name': 'login.html'})
See this page for more info: django.contrib.auth.views.login (v1.5) docs
Now, I see that you are using a decorator on your view, which implies that you do indeed want to perform custom stuff. In that case, I believe you'll want to use the django.contrib.auth.forms.AuthenticationForm. Try doing something like this in your view:
from django.contrib.auth.forms import AuthenticationForm
from django.shortcuts import render
from django.views.decorators.vary import vary_on_cookie
#vary_on_cookie
def index(request):
form = AuthenticationForm(data=request.POST or None)
return render(request, 'login.html', {
'form': form
})
can i add the ajax code with django?
i have created a simple registraion form that have 5 fields . i wish to disply the each fields in different pages but in a single window . it means by using next button 5 pages want to disply in a single window. same time all content of each page i want add to my database. is this possible in django with ajax..
my codes are as follows :
#view
from django.shortcuts import render_to_response
from registration.models import UserDetails
from forms import UserForm
from django import forms
from django.template import RequestContext
from django.http import HttpResponseRedirect
def user_details(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
form.save()
else:
form = UserForm()
return render_to_response("career.html", {"form": form},context_instance=RequestContext(request))
#form
from django import forms
from registration.models import UserDetails
class UserForm(forms.ModelForm):
pass
class Meta:
model = UserDetails
#model
from django.db import models
class UserDetails(models.Model):
fname=models.CharField(max_length=20)
lname=models.CharField(max_length=20)
email = models.EmailField()
address = models.CharField(max_length=50)
country = models.CharField(max_length=20)
def __unicode__(self):
return self.fname
return self.lname
return self.email
return self.address
return self.country
#url
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^registration/$', 'registration.views.user_details', name='user_details'),
url(r'^admin/', include(admin.site.urls)),
)
# template
<form enctype="multipart/form-data" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" ....>
</form>
Whay have you tried for ajax call?
Server just serve some result to client then it is up to your client code:
either it is post back that you refresh page
or iframe, you refresh a frame in parent doc
or html tag like tag that you inject by $(targetElement).html($someResultFromServer)
In most case server does not even care what and how it looks like client(rich or thin),
Thats you javascript, query and css codes which to works on behalf of client. Vice versa, in most case client does not even care what is and how it looks like it is server: Loosely coupled
For ajax calls you can follow this link: http://api.jquery.com/jQuery.ajax/
As Martin Thurau stated your question is very hard to understand. Regardless I think that what you are asking for is a stepped form.
Best you take a look at Django's Form Wizard here
can i add the ajax code with django?
i have created a simple registraion form that have 5 fields . i wish to disply the each fields in different pages but in a single window . it means by using next button 5 pages want to disply in a single window. same time all content of each page i want add to my database. is this possible in django with ajax..
my codes are as follows :
#view
from django.shortcuts import render_to_response
from registration.models import UserDetails
from forms import UserForm
from django import forms
from django.template import RequestContext
from django.http import HttpResponseRedirect
def user_details(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
form.save()
else:
form = UserForm()
return render_to_response("career.html", {"form": form},context_instance=RequestContext(request))
#form
from django import forms
from registration.models import UserDetails
class UserForm(forms.ModelForm):
pass
class Meta:
model = UserDetails
#model
from django.db import models
class UserDetails(models.Model):
fname=models.CharField(max_length=20)
lname=models.CharField(max_length=20)
email = models.EmailField()
address = models.CharField(max_length=50)
country = models.CharField(max_length=20)
def __unicode__(self):
return self.fname
return self.lname
return self.email
return self.address
return self.country
#url
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^registration/$', 'registration.views.user_details', name='user_details'),
url(r'^admin/', include(admin.site.urls)),
)
# template
<form enctype="multipart/form-data" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" ....>
</form>
Whay have you tried for ajax call?
Server just serve some result to client then it is up to your client code:
either it is post back that you refresh page
or iframe, you refresh a frame in parent doc
or html tag like tag that you inject by $(targetElement).html($someResultFromServer)
In most case server does not even care what and how it looks like client(rich or thin),
Thats you javascript, query and css codes which to works on behalf of client. Vice versa, in most case client does not even care what is and how it looks like it is server: Loosely coupled
For ajax calls you can follow this link: http://api.jquery.com/jQuery.ajax/
As Martin Thurau stated your question is very hard to understand. Regardless I think that what you are asking for is a stepped form.
Best you take a look at Django's Form Wizard here