I'm trying to create a Django Rest API using this link, but I get an invalid syntax error. Here is my code:
urls.py
from django.conf.urls.defaults import *
from polls.views import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^polls/$',index),
(r'^polls/(?P<poll_id>\d+)/$',detail),
(r'^polls/(?P<poll_id>\d+)/results/$',results),
(r'^polls/(?P<poll_id>\d+)/vote/$',vote),
(r'^admin/', include(admin.site.urls)),
(r'^xml/polls/(.*?)/?$',xml_poll_resource),
)
views.py
from django_restapi.model_resource import Collection
from django_restapi.responder import XMLResponder
from django_restapi.responder import *
from django_restapi_tests.polls.models import Poll, Choice
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from polls.models import Poll, Choice
from django.http import Http404
from django.template import RequestContext
import pdb
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
return render_to_response('index.html',{'latest_poll_list': latest_poll_list})
def detail(request, poll_id):
pdb.set_trace()
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('detail.html', {'poll': p},
context_instance=RequestContext(request))
def results(request, poll_id):
return HttpResponse("Hello, world.Youre at the poll index.")
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the poll voting form.
return render_to_response('polls/detail.html', {
'poll': p,
'error_message': "You didn't select a choice.",
}, context_instance=RequestContext(request))
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('results', args=(p.id,)))
xml_poll_resource = Collection(
queryset = Poll.objects.all(),
permitted_methods = ('GET', 'POST', 'PUT', 'DELETE'),
responder = XMLResponder(paginate_by = 10))
)
Models.py
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def __unicode__(self):
return self.choice
This application is based on the tutorial that is given in the Django Website. It was working well but started failing once I implemented the logic for rest APIs.
(r'^xml/polls/(.*?)/?$',xml_poll_resource),
The URL that I'm trying: http://127.0.0.1:8000/xml/polls/
Error
SyntaxError at /xml/polls/
invalid syntax (views.py, line 49)
Request Method: GET
Request URL: http://127.0.0.1:8000/xml/polls/
Django Version: 1.3.1
Exception Type: SyntaxError
Exception Value: invalid syntax (views.py, line 49)
Probably not the answer you are looking for, however I recommand you to have a look at this Django REST framwork: django-rest-framework.org
Related
When i can send post request for contact view so try block can't run and except block should be run.
Here i cant unable to send mail.
Here error in send_mail function.
So please Help me.
In Here my setting.py code
settings.py
EMAIL_BACKEND='django.core.mail.backend.smtp.EmailBackend'
EMAIL_HOST='smtp.gmail.com'
EMAIL_PORT=587
EMAIL_HOST_USER='kalp2002prajapati#gmail.com'
EMAIL_HOST_PASSWORD='******'
EMAIL_USE_TLS = True
EMAIL_USE_SSL = 0
view.py
from rest_framework import permissions
from rest_framework.views import APIView
from .models import Contact
from django.core.mail import
send_mail,EmailMessage
from rest_framework.response import Response
class ContactCreateView(APIView):
permission_classes = (permissions.AllowAny, )
def post(self, request, format=None):
data = self.request.data
print(data)
try:
send_mail(
data['subject'],
'Name: '+ data['name']
+ '\nEmail: '+data['email']+'\nMessage:'+ data['message'],
'kalpprajapati2002#gmail.com',
['kalp2002prajapati#gmail.com'],
fail_silently=False
)
contact = Contact(name=data['name'], email=data['email'], subject=data['subject'], message=data['message'])
contact.save()
return Response({'success': 'Message sent successfully'})
except:
return Response({'error': 'Message failed to send'})
urls.py
from django.urls import path
from .views import ContactCreateView
urlpatterns = [
path('', ContactCreateView.as_view())
]
models.py
from django.db import models
from datetime import datetime
class Contact(models.Model):
name=models.CharField(max_length=200)
email=models.CharField(max_length=100)
subject=models.CharField(max_length=100)
message=models.TextField(blank=True)
contact_date=models.DateTimeField(default=datetime.now,blank=True)
def __str__(self):
return self.email
just delete all the self from the view, you need only the request.
if this doesn't make your code work, post the error you are getting
I'm trying to paginate a search Query. All imports seem to be in the right place, but it keeps telling me that error. "pagination.PaginationSerializer is not defined". I don't understand why? since I imported it "from rest_framework.pagination import PaginationSerializer". It's strange, I'm sure I'm doing something that is not being done in a proper way.So here is my code.
Note: I'm basing my code on the example on the official documentation.
http://www.django-rest-framework.org/api-guide/pagination#paginating-basic-data
Here is my TraceBack from Browser:
http://dpaste.com/2R1F03X/
Exception Type: NameError at /user-search/
Exception Value: name 'pagination' is not defined
Exception Location: /var/www/api/serializers.py in , line 19
views.py
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.core.paginator import Paginator , EmptyPage, PageNotAnInteger
from django.shortcuts import HttpResponseRedirect
import json
from api.models import users, subjects
from api.serializers import PaginatedUserSerializer, UserKarmaSerializer
#api_view(['GET'])
def user_search(request):
"""
Url must be example (/?subject=iOS Development)
"""
if request.method == 'GET':
search_subject = request.QUERY_PARAMS.get('subject')
# Query
user_ids = subjects.objects.filter(
ss__icontains=search_subject).values('id_user')
user = users.objects.filter(pk__in=user_ids).order_by('-karma', 'rate')
# Pagination Below
paginator = Paginator(user, 20)
page = request.QUERY_PARAMS.get('page')
try:
user = Paginator.page(page)
except PageNotAnInteger:
user = Paginator.page(1)
except EmptyPage:
user = Paginator.page(Paginator.num_pages)
serializer_context = {'request': request}
serializer = PaginatedUserSerializer(user,context=serializer_context)
return Response(serializer.data, status=status.HTTP_200_OK)
serializers.py
from rest_framework import serializers
from rest_framework.pagination import PaginationSerializer
from api.models import users, chat, call, subjects
""" Search Tutors Based on Rate & Subjects """
# Below is line 19
class UserSearchSerializer(serializers.HyperlinkedModelSerializer):
subjects = serializers.Field(source='user_subjects')
user_rate = serializers.Field(source='rate_format')
class Meta:
model = users
fields = ('name', 'nick', 'avatar_s', 'user_rate', 'id', 'subjects', 'bio', 'experience')
class PaginatedUserSerializer(pagination.PaginationSerializer):
class Meta:
object_serializer_class = UserSearchSerializer
Because you imported it as PaginationSerializer, you don't need pagination in front. Change to:
class PaginatedUserSerializer(PaginationSerializer)
Alternatively, you could change your import:
from rest_framework import pagination
I have a django model defined as
from utils.utils import APIModel
from django.db import models
from django.core.urlresolvers import reverse
class DjangoJobPosting(APIModel):
title = models.CharField(max_length=50)
description = models.TextField()
company = models.CharField(max_length=25)
def get_absolute_url(self):
return reverse('jobs.views.JobDetail', args=[self.pk])
with a view
from restless.views import Endpoint
from restless.models import serialize
from .models import *
from utils.utils import JSON404
import ujson as json
class JobList(Endpoint):
def get(self, request):
fields = [
('url', lambda job: job.get_absolute_url()),
'title',
('description',lambda job: job.description[:50]),
'id'
]
jobs = DjangoJobPosting.objects.all()
return serialize(jobs, fields)
class JobDetail(Endpoint):
def get(self, request, pk):
try:
job = DjangoJobPosting.objects.get(pk=pk)
print(job)
fields = ["title","description","company","id"]
return serialize(job,fields)
except Exception as e:
return JSON404(e)
What I have seen in other posts which talk about reverse method is that they define the first reverse parameter in the terms I specified above, but their urls.py uses the same kind of definition, while mine uses
from django.conf.urls import patterns, include, url
from .views import *
urlpatterns = patterns('',
url(r'^$',JobList.as_view()),
url(r'^(?P<pk>\d+)/$', JobDetail.as_view()),
)
What I keep getting is an error that states
"Reverse for 'jobs.views.JobDetail' with arguments '(1,)' and keyword arguments '{}' not found."
Give urls names:
from django.urls import reverse
urlpatterns = patterns('',
url(r'^$',JobList.as_view(), name='joblist'),
url(r'^(?P<pk>\d+)/$', JobDetail.as_view(), name='jobdetail'),
)
Use that name when call reverse:
return reverse('jobdetail', args=[self.pk])
or
return reverse('jobdetail', kwargs={'pk': self.pk})
I'm just about finished building the Poll app and everything seems to be working except for the results page. "Vote Again" isn't showing up, or any other data after I input a selection. It looks like the page is just reloading. The new votes are getting counted, and I'm not getting an error message. I can see that I'm on the /results/ page.
Does anyone have any ideas where I should be looking for the problem?
Thanks!
Views:
# Create your views here.
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from polls.models import Choice, Poll
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_poll_list'
def get_queryset(self):
"""Return the last five published polls."""
return Poll.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Poll
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Poll
template_name = 'polls/results.hmtl'
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the poll voting form.
return render(request, 'polls/detail.html', {
'poll': p,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
#Always return an HttpRespsonseRedirect after successfully dealing
#with Post data. This prevents data from being posted twice if a
#user hits the Back button
return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
URLs -
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
#ex: /polls/
url(r'^$', views.IndexView.as_view(), name='index'),
#ex: /polls/5/
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
# ex: /polls/5/results/
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
#ex: /polls/5/vote/
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)
Models
from django.db import models
import datetime
from django.utils import timezone
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __unicode__(self):
return self.choice_text
Hoping I didn't mess up any formatting when I pasted in here.
It seems like the error is because you misspell the template page for results.
class ResultsView(generic.DetailView):
model = Poll
template_name = 'polls/results.hmtl'
correct the spelling for results.html
Hi Stackoverflow people,
I am trying to write my own contact form in Django, where users can write messages to me and the message will be emailed and saved in the DB for tracking.
But somehow, the model.save() won't save anything. When I check the entries with Admin, the Contact table is empty. I also do not get any error messages.
The sending of the message hasn't been fully implemented yet.
To test the code, I set up some status messages in the if/else branch, but I do not get any of the statement - so the code seems to be neglected. But I do not understand why? Any suggestions?
I am not sure if I hand over the request variable between the views.py and forms.py correctly. Could this be the issue?
Thank you for your suggestions.
models.py
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.conf import settings
from django.core.urlresolvers import reverse
from django.core.mail import send_mail
import datetime, random
class Contact(models.Model):
"""
Contact class is the model for user messages.
Every message will be sent.
"""
CATEGORIES = (
('Suggestion', 'I have a suggestion'),
('Feedback', 'General feedback'),
('Complaint', 'You should improve ...'),
# ('', ''),
)
category = models.CharField(_('Message Category'),
max_length=10,
choices=CATEGORIES)
subject = models.CharField(_('Message Subject'),
max_length=255,)
sender = models.EmailField(_('Email Address'),)
message = models.TextField(_('Message Box'),)
# date and ansbwered are not visible to the user
timeOfMessage = models.DateTimeField(_('Time of sending'), blank=True, null=True)
answered = models.BooleanField(_('Answered?'),
default=False,)
def __unicode__(self):
return '%s' % self.sender
def send_and_save(self):
subject_new = ':'.join(self.category, self.subject)
send_mail(subject_new,
message,
sender,
'info#future_domain_address.com')
return True
forms.py
from django.forms import ModelForm
from django.utils.translation import ugettext_lazy as _
from contact.models import Contact
import datetime
class ContactForm(ModelForm):
class Meta:
model = Contact
exclude = ('answered', 'timeOfMessage')
def save_and_email(request):
if request.method == 'POST':
form = self(request.POST)
if form.is_valid():
# contact.cleaned_data()
contact = form.save(commit=False)
contact.timeOfMessage = datetime.now()
contact.answered = False
contact.save()
print "was here"
return True
else:
print "Saving Failed"
else:
print "POST failed"
return False
views.py
from django.views.generic.simple import direct_to_template
from django.shortcuts import redirect, get_object_or_404, render_to_response
from django.utils.translation import ugettext as _
from django.http import HttpResponseForbidden, Http404, HttpResponseRedirect, HttpResponse
from django.template import RequestContext
from django.core.mail import BadHeaderError
from contact.forms import ContactForm
def contact(request):
if request.method == 'POST':
try:
contactform = ContactForm()
contactform.save_and_email
except BadHeaderError:
return HttpResponse(_('Invalid header found.'))
return HttpResponseRedirect('/contact/thankyou/')
return render_to_response('contact/contact.html', {'form': ContactForm()},
RequestContext(request))
I see two things here. On the view the method is not called. The method needs the () to be called.
Then the save_and_email method needs some corrections. First of all needs the self argument, or convert it to a .
My suggestion is as follows.
def save_and_email(self):
if self.is_valid():
contact = self.save(commit=False)
contact.timeOfMessage = datetime.now()
contact.answered = False
contact.save()
return True
else:
return False
And the view:
def contact(request):
if request.method == 'POST':
contactform = ContactForm(request.POST)
if contactform.save_and_email():
return HttpResponseRedirect('/contact/thankyou/')
return render_to_response('contact/contact.html', {'form': ContactForm()},
RequestContext(request))