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
Related
I have a Datatable that's working perfectly, and I wanted Server-side process to be true and not client-side.
But when I enable server-side the sorting, paging and search became faulty.
TestCase: https://codepen.io/TheNerdy97/pen/gOvNeeo?html-preprocessor=pug
I'm using this module https://github.com/izimobil/django-rest-framework-datatables
For seamless integration between Django REST framework and Datatables.
I did as the doc said but it still won't work as expected.
models.py
from unittest.util import _MAX_LENGTH
from django.db import models
#from django.utils.translation import gettext as __
# Create your models here.
class Fresh(models.Model):
code = models.CharField(("code"), max_length=255)
orbs = models.IntegerField(("orbs"))
orbs_display = models.CharField(('orbs_display'), max_length=255)
price = models.IntegerField(("price"))
price_display = models.CharField(('price_display'), max_length=255)
images = models.CharField(("images"), max_length=10000000)
date = models.CharField(("date"), max_length=255)
class Meta:
ordering = ['code', 'orbs', 'price']
def __str__(self):
return self.code
views.py
from django.shortcuts import render
from accounts.models import Fresh, Orbs
from rest_framework import viewsets
from accounts.serializers import FreshSerializer
from django.core import serializers
# Create your views here.
def index (request):
return render(request, 'index.html')
class FreshViewSet(viewsets.ModelViewSet):
queryset = Fresh.objects.all().order_by('price')
serializer_class = FreshSerializer
urls.py
import accounts
from . import views
from django.urls import path, include, re_path
from rest_framework import routers
from main import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'fresh', views.FreshViewSet)
router.register(r'orbs', views.OrbsViewSet)
urlpatterns = [
path('', views.index, name='index'),
path('fresh', views.fresh, name='fresh'),
re_path('^api/', include(router.urls)),
]
I'm on this page: Filling the details
The link to the orange image is https://upload.wikimedia.org/wikipedia/commons/c/cb/Oranges_white_background.jpg
When I'm pressing 'save' it gives me this: Error message
Couldn't understand the issues I tried various ways to solve them like take another picture and re-run the server. From Mosh Hamedi tutorial: https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=20225s at 05:42:20
I do not know what this double space between 'user' and 'old' means and I really need help with this, I'm stuck on this from Sunday:
models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=255)
price = models.FloatField()
stock = models.IntegerField()
image_url = models.CharField(max_length=2083)
class Offer(models.Model):
code = models.CharField(max_length=10)
description = models.CharField(max_length=255)
discount = models.FloatField()
views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse('Hello World')
def new(request):
return HttpResponse('New Products')
admin.py
from django.contrib import admin
from .models import Product
admin.site.register(Product)
pyshop - urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path("products/", include('products.urls'))
]
products - urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('new', views.new)
]
Hey dont use Charfield with specific length in image field. Use either UrlField or an ImageField in models.
Then try to add from admin panel.
And also run makemigrations and migrate command.
I'm in this page:
Filling the details
The ling is https://upload.wikimedia.org/wikipedia/commons/c/cb/Oranges_white_background.jpg
When I'm pressing 'save' it gives me this: Error message
Couldn't understand the issues I tried various ways to solve it like take another picture and re-run the server.
From Mosh Hamedi tutorial: https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=20225s at 05:42:20
edit: adding code.
models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=255)
price = models.FloatField()
stock = models.IntegerField()
image_url = models.CharField(max_length=2083)
class Offer(models.Model):
code = models.CharField(max_length=10)
description = models.CharField(max_length=255)
discount = models.FloatField()
views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse('Hello World')
def new(request):
return HttpResponse('New Products')
admin.py
from django.contrib import admin
from .models import Product
admin.site.register(Product)
pyshop - urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path("products/", include('products.urls'))
]
products - urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('new', views.new)
]
Django is not able to find the table
main.auth_user__old
observe the double underscore between user and old. Are you sure it is correct?
Also, please upload your code.
Settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES':('rest_framework.authentication.BasicAuthentication',),
'DEFAULT_PERMISSION_CLASSES':('rest_framework.permissions.IsAuthenticated',)
}
models.py
from django.db import models
class Emp(models.Model):
eid = models.IntegerField()
ename = models.CharField(max_length=30)
sal = models.IntegerField()
def __str__(self):
return self.ename
admin.py
from django.contrib import admin
from .models import Emp
class AdminEmp(admin.ModelAdmin):
list_display = ['eid','ename','sal']
admin.site.register(Emp,AdminEmp)
serializers.py
from .models import Emp
from rest_framework import serializers
class EmpSerializer(serializers.ModelSerializer):
class Meta:
model = Emp
fields = ('eid','ename','sal')
views.py
from .serializers import EmpSerializer
from .models import Emp
from rest_framework import viewsets
from rest_framework.authentication import BaseAuthentication
from rest_framework.permissions import IsAuthenticated
class EmpViewSet2(viewsets.ModelViewSet):
authentication_classes = (BaseAuthentication,)
permission_classes = (IsAuthenticated,)
queryset = Emp.objects.all()
serializer_class = EmpSerializer
app level urls.py
from django.conf.urls import url,include
from .views import EmpViewSet2
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('emp_viewset',EmpViewSet2,base_name='emp_viewset2')
urlpatterns = [
url(r'',include(router.urls)) ]
Project level urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('Basic_Authentication_App.urls'))
]
Username and password window
Django Rest Framework window but when i click on this link
"emp_viewset":"http://127.0.0.1:3499/api/emp_viewset/"
it shows like below:
NotImplementedError at /api/emp_viewset/
.authenticate() must be overridden.
You need to write your own authentication back-end. You can see an example from the official django documentation that explains in detail how to implement (i.e. override) the authenticate function.
Of course, if you want to provide your own permissions, you can implement a custom authentication back-end.
Remove below code from views.py:-
authentication_classes = (BaseAuthentication,)
permission_classes = (IsAuthenticated,)
everything will work properly.
and if you want to change permissions than just add in views.py
permission_classes = []
no need to add
authentication_classes
So the
permission_classes
in views.py will override the permission given in settings.py..
Thankyou.
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.