getting error on browser in django - python

i am beginner in django and i dont know how to solve this problem
i am getting error on browser as:
Using the URLconf defined in mysite.urls, Django tried these URL
patterns, in this order: ^admin/
The current URL, api/Entry/, didn't
match any of these.
all my files are:
mysite/myapp/models.py:
from tastypie.utils.timezone import now
from django.contrib.auth.models import User
from django.db import models
from django.utils.text import slugify
class Entry(models.Model):
user = models.ForeignKey(User)
pub_date = models.DateTimeField(default=now)
title = models.CharField(max_length=200)
slug = models.SlugField()
body = models.TextField()
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
# For automatic slug generation.
if not self.slug:
self.slug = slugify(self.title)[:50]
return super(Entry, self).save(*args, **kwargs)
mysite/myapp/api.py:
from tastypie.resources import ModelResource
from myapp.models import Entry
class EntryResource(ModelResource):
class Meta:
queryset = Entry.objects.all()
resource_name = 'Entry'
mysite/myapp/urls.py:
from django.conf.urls.defaults import *
from myapp.api import EntryResource
entry_resource = EntryResource()
urlpatterns = patterns('',
# The normal jazz here...
(r'^blog/', include('myapp.urls')),
(r'^api/', include(entry_resource.urls)),
mysite/mysite/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls))
)
where my 'mysite' is my project name and 'myapp' is my app
please help me out
Thanks

Your project-level urls.py doesn't include your application-level urls.py. Change mysite/mysite/urls.py to this:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^', include('myapp.urls')),
url(r'^admin/', include(admin.site.urls))
)
Also, get rid of (r'^blog/', include('myapp.urls')), in mysite/myapp/urls.py.
Hope that helps.

Related

Error in Serving media images with Django

Problem - When trying to fetch an image leads to 404 error
URL Declarations -
from django.urls import include, path
from rest_framework import routers
from django.conf.urls.static import static
from django.conf import settings
from my_awesome_api.views import PersonViewSet, SpeciesViewSet
router = routers.DefaultRouter()
router.register(r'people', PersonViewSet)
router.register(r'species', SpeciesViewSet)
urlpatterns = [
path('', include(router.urls)),
]
urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
print('avail url patterns')
print(urlpatterns)
VIEW DECLARATION -
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework import permissions
from my_awesome_api.serializers import PersonSerializer, SpeciesSerializer
from my_awesome_api.models import Person, Species
class PersonViewSet(viewsets.ModelViewSet):
queryset = Person.objects.all()
serializer_class = PersonSerializer
parser_classes = (MultiPartParser, FormParser)
#permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def perform_create(self, serializer):
serializer.save()
class SpeciesViewSet(viewsets.ModelViewSet):
queryset = Species.objects.all()
serializer_class = SpeciesSerializer
parser_classes = (MultiPartParser, FormParser)
#permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def perform_create(self, serializer):
serializer.save()
MODEL DECLARATION -
from django.db import models
# Create your models here.
class Species(models.Model):
name = models.CharField(max_length=100)
classification = models.CharField(max_length=100)
language = models.CharField(max_length=100)
image_url = models.ImageField(blank=True, null=True)
class Person(models.Model):
name = models.CharField(max_length=100)
birth_year = models.CharField(max_length=10)
eye_color = models.CharField(max_length=10)
species = models.ForeignKey(Species, on_delete=models.DO_NOTHING)
image_url = models.ImageField(blank=True, null=True)
SETTING DECLARATION
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media')
print(MEDIA_ROOT)
print('value of media root')
# URL used to access the media
MEDIA_URL = 'media/'
In an effort to troubleshoot the problem, I printed out the media root path and it is correct
/Users/ss1/Desktop/drf/media
value of media root
Printing out the URLs give the output -
[<URLResolver (None:None) ''>, <URLPattern '^media/(?P.*)$'>]
Here is the URL from PROJECT
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("admin/", admin.site.urls),
path('star-wars/', include('my_awesome_api.urls')),
]
HERE IS THE URL FROM APP
from django.urls import include, path
from rest_framework import routers
from django.conf.urls.static import static
from django.conf import settings
from my_awesome_api.views import PersonViewSet, SpeciesViewSet
router = routers.DefaultRouter()
router.register(r'people', PersonViewSet)
router.register(r'species', SpeciesViewSet)
urlpatterns = [
path('', include(router.urls)),
]
urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
print('avail url patterns')
print(urlpatterns)
Here is the screenshot confirming successful image uploads --
What did I miss here ?

Django Admin Panel URL GO WRONG

I am trying to add a document file from the admin panel Django but I am getting 404 not found URL errors.
admin file
from django.contrib import admin
from .models import Category, Document
# Register your models here.
admin.site.register(Category)
admin.site.register(Document)
from django.db import models
class Document(models.Model):
doc_name = models.CharField(max_length=100)
doc_slug = models.CharField(max_length=100)
doc_file = models.FileField(upload_to='docs')
doc_price = models.IntegerField()
doc_cat = models.CharField(max_length=100)
doc_desc = models.TextField()
doc_var = models.TextField()
Main URLs
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', include('UserAccount.urls')),
path('dashboard/', include('Dashboard.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
What could possibly be the error?
404 error means that path to the admin panel doesn't declarated.
Check main urls.py file. There should be this import statement: from django.contrib import admin and path('admin/', admin.site.urls) line in urlpatterns var.

Circular import error when I open the Django server

When I open the server(Django) I get this error: "The included URLconf 'admin.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import."
I have found out that by removing .views import from urls.py I fix the issue. So I think the problem is inside views.py.
App urls.py
from django.contrib import admin
from django.urls import include
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path('/api', include('crud.urls')),
]
views.py
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import User
from .serializers import UserSerializer
class UserView(APIView):
def get(self, request):
users = User.objects.all()
serializer = UserSerializer(users, many=True)
return Response({"users": users})
serializer.py
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
name = serializers.CharField(max_length=255)
email = serializers.EmailField()
password = serializers.CharField(max_length=255)
disease = serializers.CharField(max_length=255)
logo = serializers.TextField()
crud urls.py
Here, the issue is at the second line: if I remove that line I fix the error
from django.urls import path
from .views import UserView
app_name='crud'
# app_name will help us do a reverse look-up latter.
urlpatterns = [
path('users/', UserView.as_view()),
]
Please add error trace for better understanding of the issue.
Meanwhile try changing this:
path('/api', include('crud.urls'))
to:
path('api/', include('crud.urls')),
and
from .views import UserView
to:
from crud import views
urlpatterns = [
path('users/', views.UserView.as_view()),
]

Django doesn't show model in admin

I am new to Django and I have simple model like this.
from django.db import models
from django.contrib.auth.models import User
class Todo(models.Model):
owner = models.ForeignKey(User)
description = models.CharField(max_length=30)
done = models.BooleanField()
updated = models.DateTimeField(auto_now_add=True)
class News(models.Model):
title = models.TextField(max_length=400000)
description = models.TextField(max_length=400000)
created = models.DateTimeField(editable=False)
modified = models.DateTimeField()
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.created = timezone.now()
self.modified = timezone.now()
return super(User, self).save(*args, **kwargs)
In url,
from django.conf.urls import patterns, include, url
from todo import views
from rest_framework import viewsets, routers
from django.contrib import admin
router = routers.DefaultRouter()
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', admin.site.urls),
url(r'^', include(router.urls)),
)
I check in stackoverflow and they say autodiscover should be removed. But if I remove, I see like this. How shall I do so that my model is shown in admin?
in your admin.py file do this
from django.contrib import admin
from .models import Todo, News
# Register your models here.
admin.site.register(Todo)
admin.site.register(News)
Your app is probably not registered in INSTALLED_APPS, if it dosent' find your app it fails without giving an error
You must register model in admin app
see https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#modeladmin-objects

error with serialization in django rest framework

I use django rest framework and have this error:
base_name argument not specified, and could not automatically determine the name from the viewset, as it does not have a .model or .queryset attribute.
This is my code
urls.py
from django.conf.urls import patterns, include, url
from rest_framework import viewsets, routers
import views
router = routers.SimpleRouter()
router.register(r'book', views.BookViewSet.as_view())
views.py
from django.shortcuts import render_to_response
from mobileapp.models import Book
from rest_framework import generics
from mobileapp.serializers import BookSerializer
class BookViewSet(generics.ListAPIView):
serializer_class = BookSerializer
def get_queryset(self):
queryset = Book.objects.filter(user=self.request.user)
return queryset.order_by('-id')
serializers.py
from mobileapp.models import Book
from rest_framework import serializers
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('id', 'url', 'date', 'comment')
Have you google'd error statement?
https://github.com/tomchristie/django-rest-framework/issues/933
http://django-rest-framework.org/api-guide/routers.html#usage
I'v solved my problem. There is code.
urls.py
from django.conf.urls import patterns, include, url
from views import BookList, BookDetail
from rest_framework.urlpatterns import format_suffix_patterns
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^book/$', BookList.as_view(), name='book-list'),
url(r'^book/(?P<pk>\d+)/$', BookDetail.as_view(), name='book-detail'),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
)
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'api'])
views.py
class BookList(generics.ListCreateAPIView):
serializer_class = BookSerializer
def get_queryset(self):
queryset = Book.objects.filter(user=self.request.user)
return queryset.order_by('-id')
class BookDetail(generics.RetrieveUpdateDestroyAPIView):
model = Book
serializer_class = BookSerializer

Categories

Resources