In tutorial here I get down to where you run was_published_recently and I get this error:
ImproperlyConfigured at /admin/polls/poll/
PollAdmin.list_display[2], 'was_published_recently' is not a callable or an attribute of 'PollAdmin' or found in the model 'Poll'.
Request Method: GET
Request URL: /admin/polls/poll/
Django Version: 1.4
Exception Type: ImproperlyConfigured
Exception Value:
PollAdmin.list_display[2], 'was_published_recently' is not a callable or an attribute of 'PollAdmin' or found in the model 'Poll'.
Exception Location: C:\Python27\lib\site-packages\django\contrib\admin\validation.py in validate, line 38
here is my code:
from polls.models import Poll
from django.contrib import admin
from polls.models import Choice
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
class PollAdmin(admin.ModelAdmin):
# ...
list_display = ('question', 'pub_date', 'was_published_recently')
admin.site.register(Poll, PollAdmin)
here is my poll model
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
class Poll(models.Model):
# ...
def __unicode__(self):
return self.question
class Choice(models.Model):
# ...
def __unicode__(self):
return self.choice
Can you update your question with your Poll model?
It looks like you may have made a mistake when adding the was_published_recently method to your Poll model in the Playing with the API step in Tutorial 1.
Update:
Now that you've posted your model, it does look as if you've missed out the was_published_recently method. Go back over tutorial 1 and add it in.
Secondly, don't include each model more than once in models.py - the second one will replace the first.
Related
I want to create an entry on UserExtended model after registering an user on Django default user model.
here is UserExtended model:
class UserExtended(models.Model):
extended_id = models.AutoField(primary_key=True, editable=False)
avatar = models.ImageField(null=True, blank=True, default='Capture.PNG')
user = models.OneToOneField(User, on_delete=models.CASCADE, null=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
here is the view function that registering the user
#api_view(['POST'])
def register_user(request):
data = request.data
user = User.objects.create(
first_name=data['name'],
username=data['username'],
email=data['email'],
password=make_password(data['password'])
)
serializer = UserSerializerWithToken(user, many=False)
return Response(serializer.data)
here is the serializer
class UserSerializer(serializers.ModelSerializer):
name = serializers.SerializerMethodField(read_only=True)
isAdmin = serializers.SerializerMethodField(read_only=True)
avatar = serializers.SerializerMethodField()
def get_avatar(self, obj):
avatar = obj.userextended.avatar.url
print(avatar)
if avatar == '':
avatar = 'null'
return avatar
class Meta:
model = User
fields = ['id', 'username', 'email', 'name', 'avatar', 'isAdmin']
def get_name(self, obj):
name = obj.first_name
if name == '':
name = obj.email
return name
def get_isAdmin(self, obj):
return obj.is_staff
class UserSerializerWithToken(UserSerializer):
token = serializers.SerializerMethodField(read_only=True)
class Meta:
model = User
fields = ['id', 'username', 'email', 'name', 'isAdmin', 'token']
here is the signal.py:
from django.db.models.signals import post_save, pre_delete
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import UserExtended
#receiver(post_save, sender=User)
def create_user_extended(sender, instance, created, **kwargs):
if created:
UserExtended.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_extended(sender, instance, **kwargs):
instance.userextended.save()
but the signal is not working to create an default avatar file for an new registered user
I am new. Please help me.
Django does not look for any file named signal.py, etc. by default. Hence what is happening it that your signals are never registered (in fact the file you write them in is never run). The general solution to adding signals is to write them in a separate file and then import / register them in the app config's ready method.
In the app in which you write signal.py there should be a file apps.py in which there should be a class inheriting from AppConfig edit this class and add a ready method to it and import your signals there:
from django.apps import AppConfig
# The parts marked as "Don't edit" mean to keep them as it already is in _your_ code and not copy it
class YourAppConfig(AppConfig): # Don't edit
default_auto_field = 'django.db.models.BigAutoField' # Don't edit
name = 'your_app' # Don't edit
# Copy only the code below
def ready(self):
# models, signals etc. are imported only here because otherwise the models might not be loaded yet
from . import signal
I have made a product model in django. I'm able to insert products, but now i'hanving problems to get the products. When i list the products, i get all items. But when i try get only one, the restframework is giving me this error:
I'm trying to acessing the product by using this url http://localhost:4444/products/1
TypeError at /products/1
'NoneType' object is not callable
Request Method: GET
Request URL: http://localhost:4444/products/1
Django Version: 2.2.8
Exception Type: TypeError
Exception Value:
'NoneType' object is not callable
Exception Location: C:\Users\vini\Documents\VirtualEnv\mystore\lib\site-packages\rest_framework\generics.py in get_serializer, line 110
Python Executable: C:\Users\vini\Documents\VirtualEnv\mystore\Scripts\python.exe
Python Version: 3.8.0
Python Path:
['C:\\Users\\vini\\Documents\\GitHub\\mystore-backend',
'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore\\Scripts\\python38.zip',
'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore\\DLLs',
'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore\\lib',
'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore\\Scripts',
'c:\\users\\vini\\appdata\\local\\programs\\python\\python38\\Lib',
'c:\\users\\vini\\appdata\\local\\programs\\python\\python38\\DLLs',
'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore',
'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore\\lib\\site-packages']
Server time: Sab, 15 Fev 2020 19:41:00 +0000
Model:
class Product(UGCModel):
class Meta:
app_label = 'product'
avatar = models.ForeignKey('image.Image',
related_name='product_image',
on_delete=models.CASCADE)
# Variable to hide in store
hide = models.BooleanField(default=False)
# Value of product
value = models.DecimalField(max_digits=6, decimal_places=2,
validators=[MinValueValidator(0)])
# Name of the product
title = models.CharField(max_length=150, null=False, blank=False)
# Quantity of product in stock
quantity = models.IntegerField(default=0, blank=False, null=False,
validators=[MinValueValidator(0)])
# Discount of the product
discount = models.IntegerField(default=0,
validators=[MaxValueValidator(100),
MinValueValidator(0)])
# description of the product
resume = models.CharField(max_length=1000, blank=True)
def __str__(self):
return '(Product)%s' % self.uid
Url:
from django.urls import path
from . import views
import product.views as v
product_detail = v.ProductViewSet.as_view({'get': 'retrieve',
'delete': 'destroy',
'patch': 'partial_update'})
product_list = v.ProductViewSet.as_view({'post': 'create', 'get': 'list'})
urlpatterns = [
path('products/<int:id>', product_detail),
path('products', product_list),
]
View:
from rest_framework import viewsets
from .models import Product
from .serializers import (ProductListSerializer, ProductCreateSerializer)
from rest_framework.response import Response
from rest_framework import status, generics
class ProductViewSet(viewsets.ModelViewSet):
lookup_field = 'id'
model = Product
queryset = Product.objects.all()
serializer_class = ProductListSerializer
def get_serializer_class(self):
if self.request.method == 'GET':
return ProductListSerializer
elif self.request.method == 'POST':
return ProductCreateSerializer
serializers:
from .models import Product
from rest_framework import serializers
import image.fields as f
import image.serializers as s
class ProductListSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ['uid', 'title', 'avatar', 'value',
'quantity', 'discount', 'resume']
avatar = s.ImageListSerializer()
class ProductCreateSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ['uid', 'title', 'avatar', 'value', 'hide',
'quantity', 'discount', 'resume']
avatar = f.ImageField()
As #Vinicus Morais said you need to make the serializer_class = ProductListSerializer. that should fix the error.
Having the following Model:
class Book(models.Model):
name = models.CharField()
author = models.CharField()
date = models.DateField()
class Meta:
unique_together = ('name', 'author')
class BookSerializerWrite(serializers.ModelSerializer):
class Meta:
model = Book
class BookView(ApiView):
def put(self, request, *args, **kwargs):
serializer = BookSerializerWrite(data=request.data)
if serializer.is_valid():
serializer.save()
The view above does not work as the serializer.is_valid() is False.
The message is:
'The fields name, author must make a unique set'
Which is the constraint of the model.
How do I update the model?
I would rather not override the serializer's validation method.
I also cannot access the validated_data for an update as in
https://www.django-rest-framework.org/api-guide/serializers/#saving-instances
as this is empty due to the fact that the form does not validate.
Is there a builtin solution?
You can achieve it using UpdateAPIview
serializers.py
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('name', 'author', 'date')
views.py
from rest_framework.generics import UpdateAPIview
from .serializers import BookSerializer
class BookUpdateView(UpdateAPIView):
serializer_class = BookSerializer
urls.py
from django.urls import path
from . import views
url_patterns = [
path('api/book/<int:pk>/update/', views.BookUpdateView.as_view(), name="book_update"),
]
Now, post your data to above url. It should work.
Reference: https://github.com/encode/django-rest-framework/blob/master/rest_framework/generics.py
I am following the Django Poll tutorial, I just changed the models a little: https://docs.djangoproject.com/en/1.5/intro/tutorial02/
I am wondering why my alarm does not show in the admin interface when I add/edit/change a pill. The admin only shows to edit the name, not the related alarm object.
It should display inline, according to the tutorial.
admin.py:
from django.contrib import admin
from pills.models import Alarm,Pill
class AlarmInline(admin.TabularInline):
model = Alarm
extra = 3
class PillAdmin(admin.ModelAdmin):
fieldsets = [
('Drug information', {'fields': ['name']}),
]
inlines = [AlarmInline]
list_display = ('name')
admin.site.register(Pill, PillAdmin)
models.py
from django.db import models
class Pill(models.Model):
name = models.CharField(max_length=200)
def __unicode__(self):
return self.name
class Alarm(models.Model):
pill = models.ForeignKey(Pill)
time = models.DateTimeField('Alarm time')
def __unicode__(self):
return self.time.strftime('%c')
All my models validate. I tried rebuilding the database etc...
Any ideas?
If you've correctly reproduced your code above, the problem is your indentation.
It should be:
class PillAdmin(admin.ModelAdmin):
fieldsets = [
('Drug information', {'fields': ['name']}),
]
inlines = [AlarmInline]
list_display = ('name')
inlines is an attribute of the admin class - it and list_display need to be part of the class definition, not statements at the module level.
I'm new to Python and especially to Django. While trying to dive in subj. framework, and run through its official tutorial I got some pain in the neck error which says:
Attribute error: 'Poll' object has no attribute 'was_published_recently'
I type the next in django shell (invoked by: "python manage.py shell" from projects directory):
>>> from polls.models import Poll, Choice
>>> from django.utils import timezone
>>> p = Poll.objects.get(pk=1)
>>> p.was_published_recently()
and I get the next shell output:
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'Poll' object has no attribute 'was_published_recently'"
Can someone help me to get what am I doing wrong here? Because I just have no idea what can lead to such an error... (Already googled inside out the question, but didn't find an answer that could solve my situation).
I use:
Django version 1.5.1
Python version 2.7.5
Here're my "Poll" model code:
import datetime
from django.utils import timezone
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
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
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
Also, here's my "Admin" file:
from django.contrib import admin
from polls.models import Choice, Poll
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question', 'pub_date', 'was_published_recently')
admin.site.register(Choice)
admin.site.register(Poll, PollAdmin)
make sure you use 4 spaces as indentation instead Tab character, tab makes function does not recognize.
I think that all it is saying is that you haven't included any was_published_recently function in the class. Thanks for including the admin.py & polls.py files, but I think it's in your models.py file that you need to ensure a couple things. It looks like you need to make sure that
from django.utils import timezone
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
are included in your models.py file.