I have an django app,But i want to make its API so just i created it
after runing the server
Page not found (404)
But my django app is running,After the running the url of API i got the error of Page not found
List/views.py
from django.http import Http404
from django.shortcuts import render
from django.views.generic import ListView,DetailView
from .models import List
from django.http import HttpResponse,JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from List.serializers import ListSerializers
class MainListView(ListView):
queryset = List.objects.all()
# temp = List.objects.all()
template_name = "main_list.html"
def get_context_data(self, *args, **kwargs):
context = super(MainListView, self).get_context_data(*args, **kwargs)
context['temp'] = List.objects.all()
return context
class MainListView(ListView):
queryset = List.objects.all()
# temp = List.objects.all()
template_name = "List/list.html"
def get_context_data(self, *args, **kwargs):
context = super(MainListView, self).get_context_data(*args, **kwargs)
context['temp'] = List.objects.all()
return context
class MainDetailSlugView(DetailView):
queryset = List.objects.all()
template_name = "news/detail.html"
#csrf_exempt
def head_list(request):
if request.method == 'GET':
queryset = List.objects.all()
serializer = ListSerializer(queryset, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = ListSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
#csrf_exempt
def head_detail(request, pk):
try:
head = List.objects.get(pk=pk)
except List.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = ListSerializer(list)
return JsonResponse(serializer.data)
elif request.method == 'PUT':
data = JSONParser().parse(request)
serializer = SnippetSerializer(head, data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
head.delete()
return HttpResponse(status=204)
List/urls.py
from django.urls import path
from List import views
from .views import(
# ListlistView,
MainListView,
MainDetailSlugView,
head_list,
head_detail
)
urlpatterns = [
# url(r'^$',ListlistView.as_view()),
path('',MainListView.as_view(),name='list'),
path('(<pk>\d+)(?:/(<slug>[\w\d-]+))',MainDetailSlugView.as_view(), name='List'),
path('list/',views.list_list),
path('lists/<int:pk>/',views.list_detail),
]
List/serializers.py
from rest_framework import serializers
from List.models import List
class ListSerializers(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
title = serializers.CharField(required=True, allow_blank=False,max_length=120)
slug = serializers.SlugField(required=False,)
description= serializers.CharField(required=True, allow_blank=False)
image = serializers.ImageField(required=True,)
timestamp = serializers.DateTimeField(required=True,)
code = serializers.CharField(style={'base_template': 'textarea.html'})
language = serializers.CharField(default='python')
style = serializers.CharField(default='friendly')
def create(self, validated_data):
return List.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.title = validated_data.get('title', instance.title)
instance.descritption = validated_data.get('descritption', instance.descritption)
instance.image = validated_data.get('image', instance.image)
instance.timestamp = validated_data.get('timestamp',instance.timestamp)
instance.language = validated_data.get('language',instance.language)
instance.style = validated_data.get('style',)
instance.save()
return instance
List/models.py
import random
import os
from django.db import models
from django.urls import reverse
from django.db.models.signals import pre_save, post_save
from lokswar.utils import unique_slug_generator
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0],item[0]) for item in LEXERS])
STYLE_CHOICES = sorted((item,item) for item in get_all_styles())
def get_filename_ext(filepath):
base_name = os.path.basename(filepath)
name, ext = os.path.splitext(base_name)
return name,ext
def upload_image_path(instence, filename):
new_filename = random.randint(1,396548799)
name, ext = get_filename_ext(filename)
final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext= ext)
return "card/{new_filename}/{final_filename}".format(new_filename=new_filename,
final_filename=final_filename)
class ListQuerySet(models.query.QuerySet):
def active(self):
return self.filter(active=True)
class ListManager(models.Manager):
def get_queryset(self):
return ListQuerySet(self.model, using=self._db)
def all(self):
return self.get_queryset().active()
class List(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=120)
slug = models.SlugField(blank=True, unique=True)
description= models.TextField()
image = models.ImageField(upload_to=upload_image_path,null=True, blank=True)
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True)
code = models.TextField(default=True)
language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
objects = ListManager()
class Meta:
ordering = ('created',)
def get_absolute_url(self):
return reverse('List', kwargs={'pk': self.pk, 'slug': self.slug })
def __str__(self):
return self.title
def __unicode__(self):
return self.title
Please help me to solve this error.
I am trying to run my API through this url http://127.0.0.1:8000/List/list/
urls.py
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
from .views import HomeListView
urlpatterns = [
path('List',include('List.urls'), name="List"),
path('news/',include('news.urls'), name="news"),
path('', HomeListView.as_view(), name='home'),
path('sports/',include('sports.urls'), name="sports"),
path('movie/',include('movie.urls'), name="movie"),
path('business/',include('business.urls'), name="business"),
path('api-auth/', include('rest_framework.urls')),
path('admin/', admin.site.urls),
]
You make a small mistake in url at url.py file.
Change:
path('List',include('List.urls'), name="List"),
Into:
path('List/',include('List.urls'), name="List"),
urlpatterns = [
path('',MainListView.as_view(),name='list'),
path('(<pk>\d+)(?:/(<slug>[\w\d-]+))',MainDetailSlugView.as_view(), name='List'),
path('list/',views.list_list),
path('lists/<int:pk>/',views.list_detail),
]
As you can see above, you have two urls defined that apply here
/list/
/lists/<int> # which applies to something like /lists/293749
you're URL calling is /List/list, which doesn't apply to any URLs here unless you define a project-level URLs.py with something like
urlpatterns = [
path('list/', include('List.urls'))
]
Couple things:
Take a look at python conventions. Classes are capitalized and PascalCase whereas variables, methods and functions are snake_case. No reason for you to have a module capitalized
Don't use the same names as python/django builtins and reserved words. That causes issues and is a good habit to get into.
I believe django treats urls as case sensitive when they come in the URL parser. You call /List, but the url definition is /list
Related
When i add product to my home function in views.py I got this error :
No product matches the given query.
image
Why do I get this error?
views:
class productviewset(viewsets.ModelViewSet):
queryset=product.objects.all()
serializer_class = productSerializer
def create(self, request):
serialized = productSerializer(data=request.data, many=True)
if serialized.is_valid():
serialized.save()
return Response(serialized.data, status=status.HTTP_201_CREATED)
return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
#action (detail=False , methods=['post'])
def delete(self,request):
product.objects.all().delete()
return Response('success')
def home(request ):
p=get_object_or_404(product,pk=1)
return render(request,'home.html',{'p':p})
def foods(request):
return render(request,'foods.html',{'p':category.objects.all()})
models:
class category(models.Model):
name=models.CharField(max_length=255, db_index=True)
def __str__(self):
return self.name
class product(models.Model):
category = models.ForeignKey(category, related_name='products',on_delete=models.CASCADE)
image=models.CharField(max_length=500)
description=models.CharField(max_length=500)
price=models.CharField(max_length=50)
buy=models.CharField(max_length=100)
urls:
from django.urls import include, path
from rest_framework import routers
from quick.views import productviewset
from quick import views
from django.contrib import admin
urlpatterns = [
path('api/', include(router.urls)),
path('',views.home),
path('foods',views.foods),
path('admin/',admin.site.urls),
]
Try like this:
views.py
def home(request, id):
p=get_object_or_404(product, id=id)
return render(request,'home.html',{'p':p})
urls.py
urlpatterns = [
...
path('<int:id>/', views.home, name='name'),
]
Note: Always add / at the end of every route.
Note: Models in django are written in PascalCase not smallcase, it will be better if you change it from category and product to Category and Product respectively.
Class based views are also written in PascalCase, you can change it to ProductViewSet.
this is the error I got when I wanted to create a dynamic sitemap.
sitemap.py
from django.contrib import sitemaps
from django.shortcuts import reverse
from django.utils import timezone
from django.contrib.sitemaps import Sitemap
#models
from home.models import Page
class StaticViewSitemap(sitemaps.Sitemap):
priority = 0.5
changefreq = "daily"
protocol = 'https'
def items(self):
return [
'home:about',
]
def location(self, item):
return reverse(item)
def lastmod(self, item):
return timezone.now()
class DynamicSitemap(Sitemap):
changefreq = "daily"
priority = 0.5
def items(self):
return Page.objects.all()
models.py
class Page(models.Model):
city = models.CharField(max_length=40, verbose_name="Şehir")
seo = models.CharField(max_length=50, verbose_name="Seo")
def __str__(self):
return self.city
def get_absolute_url(self):
return reverse('home:page', kwargs={'pk': self.pk})
home/urls.py:
app_name = "home"
urlpatterns = [
# ⋮,
path(r'page/<int:pk>', views.yardimsayfalari, name="page"),
# ⋮,
]
static sitemap works fine but dynamic sitemap I get the same error. Thank you to those who are interested so far.
I'm sorry for my bad english
Based on the get_absolute_url, you try to link this to:
path(r'page', views.yardimsayfalari, name='page'),
The name of your view is page, not Page. Furthermore you specified app_name = 'home', hence full name of the view is home:page. Finally your path does not contain any parameter, so args=(self.pk,) makes not much sense.
You thus likely should include a primary key parameter:
app_name = "home"
urlpatterns = [
# ⋮,
path('page/<int:pk>/', views.yardimsayfalari, name="page"),
# ⋮,
]
include that pk parameter in your view:
def yardimsayfalari(request, pk):
# …
# return HTTP response
and finally refer to the view with:
class Page(models.Model):
# ⋮
def get_absolute_url(self):
return reverse('home:page', args=(self.pk,))
It might also make more sense to work with a named parameter, so:
class Page(models.Model):
# ⋮
def get_absolute_url(self):
return reverse('home:page', kwargs={'pk': self.pk})
based on this, I would advise to (re)read the third part of the Django tutorial.
I am trying to reverse to the Detail View after the Update View and to List View after Delete View. How can I implement this. I am getting an error reverse not defined.
Thanks
#Contents of Models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
class Profile(models.Model):
OPTIONS_PROFILE_TYPE = (
('single', 'Single'),
('family', 'Family'),
)
OPTIONS_LOCATIONS = (
('USA', 'USA'),
('Canada', 'Canada'),
)
user = models.OneToOneField(User, on_delete=models.CASCADE, help_text='User Name')
display_name = models.CharField(null=True, max_length = 16, help_text='Optional Display Name' )
profile_type = models.CharField(null=True, choices=OPTIONS_PROFILE_TYPE, max_length=10)
location = models.CharField(null=True, max_length = 30, choices=OPTIONS_LOCATIONS, help_text='Optional Location')
biography = models.CharField(null=True, blank=True, max_length = 500, help_text='Optional Biography')
# Metadata
class Meta:
ordering = ['profile_type']
# Methods
def get_absolute_url(self):
#Returns the url to access a particular instance of MyModelName.
return reverse('profile-detail', args=[str(self.id)])
def __str__(self):
#String for representing the MyModelName object (in Admin site etc.).
return self.user.username
#Contents of Views.py
from datetime import datetime
from django.shortcuts import render
from django.urls import path
from django.http import HttpRequest
from .models import Profile
from django.views.generic import FormView, CreateView, DetailView, UpdateView, DeleteView, ListView
from django.shortcuts import redirect
from django.urls import reverse
class ProfileListView(ListView):
model = Profile
def get_context_data(self, **kwargs):
# Call the base implementation first to get the context
context = super(ProfileListView, self).get_context_data(**kwargs)
# Create any data and add it to the context
context['title'] = 'Users'
context['message'] = 'given below is a list of all users'
return context
class ProfileCreateView(CreateView):
model = Profile
fields = ['user', 'display_name', 'profile_type', 'location', 'biography']
def get_context_data(self, **kwargs):
# Call the base implementation first to get the context
context = super(ProfileCreateView, self).get_context_data(**kwargs)
# Create any data and add it to the context
context['title'] = 'Create User'
context['message'] = 'please use the form below to create the user'
return context
class ProfileDetailView(DetailView):
model = Profile
def get_context_data(self, **kwargs):
# Call the base implementation first to get the context
context = super(ProfileDetailView, self).get_context_data(**kwargs)
# Create any data and add it to the context
context['title'] = 'User Detail'
context['message'] = 'given below are the details of the user'
return context
class ProfileUpdateView(UpdateView):
model = Profile
fields = ['user', 'display_name', 'profile_type', 'location', 'biography']
def get_success_url(self):
return reverse('profile-detail', kwargs={'pk' : self.object.pk})
def get_context_data(self, **kwargs):
# Call the base implementation first to get the context
context = super(ProfileUpdateView, self).get_context_data(**kwargs)
# Create any data and add it to the context
context['title'] = 'Update User'
context['message'] = 'please use the form below to update the user'
return context
class ProfileDeleteView(DeleteView):
model = Profile
CONTENTS OF URLS.PY
from datetime import datetime
from django.urls import path
from django.contrib import admin
from django.contrib.auth.views import LoginView, LogoutView
from app import forms, views
from app.views import ProfileListView, ProfileDetailView, ProfileCreateView, ProfileUpdateView
urlpatterns += [
path('profiles/', views.ProfileListView.as_view(), name='profiles'),
path('profile/<int:pk>', views.ProfileDetailView.as_view(), name='profile-detail'),
path('create/', views.ProfileCreateView.as_view(), name='create'),
path('edit/<int:pk>/', views.ProfileUpdateView.as_view(), name='update'),
The error I am getting is - Reverse Not Defined when using the update view. I tried looking up and the solution which I have: Create View reverse to DetailView
requires me to migrate the get success url method to the views section. Is it possible to avoid this?
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
I have a urls.py file setup as follows
from django.conf.urls import patterns, include, url
from .views import *
urlpatterns = patterns('',
url(r'^$', BlogListView.as_view()),
url(r'(?P<blog_id>)\d{1,}/$', BlogDetailView.as_view())
)
with the correlating view
class BlogDetailView(View):
def get(self, request, blog_id, *args, **kwargs):
post = Blog.objects.get(post_id=blog_id).to_detail_json
return HttpResponse(json.dumps(post), mimetype='application/json')
I get an error when I visit 127.0.0.1:8000/blog/1/
ValueError at /blog/4/
invalid literal for int() with base 10: ''
but if I change
post = Blog.objects.get(post_id=blog_id).to_detail_json
to
post = Blog.objects.get(post_id=1).to_detail_json
then I get the correct response.
In case it is wanted, here is my model
from mongoengine import *
from collections import OrderedDict
import datetime
import json
class Blog(Document):
post_id = IntField(unique=True)
title = StringField(max_length=144, required=True)
date_created = DateTimeField(default=datetime.datetime.now)
body = StringField(required=True)
def __init__(self, *args, **kwargs):
self.schema = {
"title": self.title,
"date": str(self.date_created),
"id": self.post_id,
"body": self.body
}
super(Blog, self).__init__(*args, **kwargs)
#property
def to_detail_json(self):
fields = ["id","title", "date", "body"]
return {key:self.schema[key] for key in fields}
#property
def to_list_json(self):
fields = ["title", "date"]
return {key:self.schema[key] for key in fields}
Update
I changed the BlogDetailView to return
return HttpResponse(json.dumps(self.kwargs),mimetype='application/json')
and it gives me
{
blog_id: ""
}
Which leads me to believe it is something with my urls.py file, but I do not see the error.
try
post = Blog.objects.get(post_id=self.kwargs['blog_id']).to_detail_json
It turns out that
url(r'(?P<blog_id>)\d{1,}/$', BlogDetailView.as_view())
should be
url(r'(?P<blog_id>\d{1,})/$', BlogDetailView.as_view())