Error message AttributeError: 'NoneType' object has no attribute 'add'
am trying to create an instance of a model.
the card model is suppose to be an instance of the patient model and the patient model has a foreign key relations with the user model.
Its like a patient who has a card in the hospital.
My error is coming from the perform_create method
views.py
class PatientCardListAPIView(ListCreateAPIView):
serializer_class = PatientsCardSerializer
queryset = Card.objects.all()
permission_classes = (permissions.IsAuthenticated, IsOwner, )
def perform_create(self, serializer):
serializer.save()
serializer.instance.owner.add(self.request.user)
models.py
from django.db import models
from authentication.models import User
# Create your models here.
class Patient(models.Model):
name = models.CharField(max_length=255, null=True)
country = models.CharField(max_length=255, null=True)
state = models.CharField(max_length=255, null=True)
phone = models.CharField(max_length=255, null=True)
email = models.CharField(max_length=255, null=True)
owner = models.ForeignKey(to=User, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Card(models.Model):
name = models.CharField(max_length=255, null=True)
card_number = models.CharField(max_length=255, null=True)
owner = models.OneToOneField(Patient, null=True, blank=True, on_delete=models.CASCADE)
def __str__(self):
return self.name
It should be as
class PatientCardListAPIView(ListCreateAPIView):
serializer_class = PatientsCardSerializer
queryset = Card.objects.all()
permission_classes = (permissions.IsAuthenticated, IsOwner,)
def perform_create(self, serializer):
serializer.save(owner = self.request.user)
This should be:
def perform_create(self, serializer):
model_instance = serializer.save(owner=self.request.user)
OR
def perform_create(self, serializer):
model_instance = serializer.save()
model_instance.owner = self.request.user
Edited
..............
A closer look at your model shows that you need to redefine the model. As you've defined, the owner field under Patient class indicated that you can have a User who can be many Patient...(a query of: patient=Patient.objects.get(owner=self.request.user) may return more than one instance. ). Suggested model should be:
class Patient(models.Model):
name = models.CharField(max_length=255, null=True)
country = models.CharField(max_length=255, null=True)
state = models.CharField(max_length=255, null=True)
phone = models.CharField(max_length=255, null=True)
email = models.CharField(max_length=255, null=True)
**owner = models.OneToOneField(User, null=True)**
def __str__(self):
return self.name
class Card(models.Model):
name = models.CharField(max_length=255, null=True)
card_number = models.CharField(max_length=255, null=True)
owner = models.OneToOneField(Patient, null=True, blank=True, on_delete=models.CASCADE)
def __str__(self):
return self.name
Then you can have your view:
class PatientCardListAPIView(ListCreateAPIView):
serializer_class = PatientsCardSerializer
queryset = Card.objects.all()
permission_classes = (permissions.IsAuthenticated, IsOwner, )
def perform_create(self, serializer):
card_instance = serializer.save()
patient = Patient.objects.get(owner=self.request.user)
card_instance.owner = patient
Appreciation
I was almost discouraged with programming for the past 24hrs because of this problem, but this community helped me, even though they did not give the answer i needed, they led me into discovering the answer myself, and i say Thank you to stackoverflow community...
Solved
I finally discovered what i was doing wrong.
a card does not just belong to a patient, it also belongs to a hospital, so the card needs a relation to both the hospital and the patient.
models.py
class Patient(models.Model):
name = models.CharField(max_length=255, null=True)
country = models.CharField(max_length=255, null=True)
state = models.CharField(max_length=255, null=True)
phone = models.CharField(max_length=255, null=True)
email = models.CharField(max_length=255, null=True)
owner = models.ForeignKey(to=User, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Card(models.Model):
name = models.CharField(max_length=255, null=True)
card_number = models.CharField(max_length=255, null=True)
owner = models.OneToOneField(Patient, null=True, blank=True, on_delete=models.CASCADE)
hospital = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
def __str__(self):
return self.name
views.py
class PatientCardListAPIView(ListCreateAPIView):
serializer_class = PatientsCardSerializer
queryset = Card.objects.all()
permission_classes = (permissions.IsAuthenticated, IsOwner, )
def perform_create(self, serializer):
return serializer.save(hospital=self.request.user)
def get_queryset(self):
return self.queryset.filter(hospital=self.request.user)
class PatientCardDetailAPIView(RetrieveUpdateDestroyAPIView):
serializer_class = PatientsCardSerializer
permission_classes = (permissions.IsAuthenticated, IsOwner,)
queryset = Card.objects.all()
lookup_field = "id"
def get_queryset(self):
return self.queryset.filter(hospital=self.request.user)
Related
So the user can take some quiz and earn xp only at first try. From the second try on I only want to calculate how many correct answer scored but not xp will be earn.
My models:
class ClassAttempt(models.Model):
user = models.ForeignKey(to=User,on_delete= models.PROTECT, null=True)
related_class = models.ForeignKey(to=Class, related_name='attempt', on_delete= models.PROTECT, null=True)
collected_xp = models.IntegerField(null=True, blank=True, default=0)
status = models.CharField(
verbose_name='status',
max_length=20,
choices=(
('no-completed', 'no-completed'),
('completed', 'completed'),
),
default='no-completed'
)
try_num = models.IntegerField(null=True, blank=True, default=1)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class UserClassQuestionsRecord(models.Model):
user = models.ForeignKey(to=User, related_name='user_class_question_record', on_delete=models.CASCADE, null=True)
question = models.ForeignKey(to=ClassQuiz, related_name='question_selected', on_delete=models.PROTECT, null=True, blank=True)
selected_answer = models.ForeignKey(to=QuizAnsClass, related_name='answer_selected', on_delete=models.PROTECT, null=True, blank=True)
is_correct = models.CharField(
verbose_name='status',
max_length=10,
choices=(
('True', 'True'),
('False', 'False'),
),
default=''
)
try_num = models.IntegerField(null=True, blank=True, default=1)
xp_collected = models.IntegerField(null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
My View:
class UserClassScore(ListAPIView):
"""
Get User Score at the end of each class by Class ID
Get request
"""
queryset = ClassAttempt.objects.all()
serializer_class = UserClassScoreSerializer
permission_classes = [IsAuthenticated]
lookup_field = 'id'
def get_queryset(self):
queryset = self.queryset.filter(related_class_id=self.kwargs.get('id'), try_num=1)
if not queryset:
self.serializer_class = UserClassScoreSerializerNoXp
return queryset
else:
self.serializer_class = UserClassScoreSerializer
return queryset
My serializers :
class UserClassScoreSerializer(serializers.ModelSerializer):
score = serializers.SerializerMethodField()
xp_collected = serializers.SerializerMethodField()
def get_score(self, obj):
class_data = UserClassQuestionsRecord.objects.filter(user=self.context['request'].user,
question__singleclass_id=obj.related_class.id,
try_num=1,
is_correct='True').all()
return class_data.__len__()
def get_xp_collected(self, obj):
class_data = UserClassQuestionsRecord.objects.filter(user=self.context['request'].user,
question__singleclass_id=obj.related_class.id,
try_num=1,
is_correct='True').all()
obj_count = class_data.__len__()
return obj_count * 10
class Meta:
model = Class
fields = ['score', 'xp_collected']
class UserClassScoreSerializerNoXp(serializers.ModelSerializer):
score = serializers.SerializerMethodField()
xp_collected = serializers.SerializerMethodField()
def get_score(self, obj):
class_data = UserClassQuestionsRecord.objects.filter(user=self.context['request'].user,
question__singleclass_id=obj.related_class.id,
**try_num=2,**
is_correct='True').all()
return class_data.__len__()
def get_xp_collected(self, obj):
return 0
class Meta:
model = Class
fields = ['score', 'xp_collected']
So try_num is how I'm tracking on which attempt it is. The thing is that the user can take more that 2 attempts let's say to infinitive attempts.
You can get the first object in table using first()
MyModel.objects.first()
so calculate the xp from this result
or
MyModel.objects.all()[:number_for_question_you_want]
example:
MyModel.objects.all()[:5]
also you can use .values() or any other filter you want
My point is to implement the post method with a nested object which has just ID. When I use all fields of a nested object post method works fine. But I'd like to pass just one field and it is ID, other fields gotta be unrequired
Now I'm getting the error like
NOT NULL constraint failed: article_article.author_id
models.py
class Author(models.Model):
first_name = models.CharField(max_length=20, blank=True, null=True)
last_name = models.CharField(max_length=20, blank=True, null=True)
nickname = models.CharField(max_length=20, blank=True, null=True)
def __str__(self):
return self.nickname
class Article(models.Model):
title = models.CharField(max_length=120, unique=True)
description = models.TextField(blank=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='articles')
created_at = models.DateTimeField(auto_now_add=True, blank=True)
updated_at = models.DateTimeField(auto_now=True, blank=True)
def __str__(self):
return self.title
views.py
class ArticleView(APIView):
def get(self, request, pk=None):
if pk:
article = Article.objects.get(pk=pk)
serializer = ArticleSerializer(article, many=False)
else:
articles = Article.objects.all()
serializer = ArticleSerializer(articles, many=True)
return Response(serializer.data)
def post(self, request):
data = request.data
serializer = ArticleSerializer(data=data)
if serializer.is_valid(raise_exception=True):
article_saved = serializer.save()
return Response({"success": "Article '' created successfully".format(article_saved.title)},
status=status.HTTP_201_CREATED)
serializers.py
class AuthorSerializer(serializers.Serializer):
first_name = serializers.CharField(required=False)
last_name = serializers.CharField(required=False)
nickname = serializers.CharField(required=False)
class ArticleSerializer(serializers.Serializer):
title = serializers.CharField(max_length=120)
description = serializers.CharField()
author = AuthorSerializer(required=False)
def create(self, validated_data):
author_data = validated_data.pop('author', None)
if author_data:
author = Author.objects.get_or_create(**author_data)[0]
validated_data['author'] = author
return Article.objects.create(**validated_data)
I got it. I should just have added to a serializer the field ID
class AuthorSerializer(serializers.Serializer):
first_name = serializers.CharField(required=False)
last_name = serializers.CharField(required=False)
nickname = serializers.CharField(required=False)
id = serializers.IntegerField()
i have in models.py
class Variants(Model):
class Meta:
db_table = 'variants'
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255, blank=False, null=False)
client = models.ForeignKey(Client, on_delete=models.CASCADE, null=False, blank=False)
created_at = models.DateField(auto_created=True, default=now, blank=True)
updated_at = models.DateField(auto_now=True, null=True, blank=True)
and
class VariantOptions(Model):
class Meta:
db_table = 'variant_options'
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255, blank=False, null=False)
variant = models.ForeignKey(Variants, on_delete=models.CASCADE, null=False, blank=False)
created_at = models.DateField(auto_created=True, default=now, blank=True)
updated_at = models.DateField(auto_now=True, null=True, blank=True)
and in serializers.py
class VariantOptionsSerializer(serializers.ModelSerializer):
class Meta:
model = models.VariantOptions
fields = ['name']
class VariantsSerializer(serializers.ModelSerializer):
options = VariantOptionsSerializer(many=True)
class Meta:
model = models.Variants
fields = ['name','client','options']
def create(self, validated_data):
options_data = validated_data.pop('options')
variant = models.Variants.objects.create(**validated_data)
for option_data in options_data:
models.VariantOptions.objects.create(variant=variant, **option_data)
return variant
and my view
class VariantsCreate(APIView):
permission_classes = (permissions.IsAuthenticated,)
serializer_class = serializers.VariantsSerializer
def post(self, request, format=None):
serializer = serializers.VariantsSerializer(data=request.data)
if serializer.is_valid():
saved = serializer.save()
return Response(serializer.data) ==> serializer.data gives error
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
i have this error
Got AttributeError when attempting to get a value for field options on serializer VariantsSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the Variants instance.
Original exception text was: 'Variants' object has no attribute 'options'.
but the data has already been validated by the call to is_valid()
why return Response(serializer.data) gives error ?
Try to change
variant = models.ForeignKey(Variants, on_delete=models.CASCADE, null=False, blank=False)
with
variant = models.ForeignKey(Variants, related_name='options', on_delete=models.CASCADE, null=False, blank=False)
I am a total newbie in Python and new on StackOverFlow. If I am missing something please let me know
This is Django-scheduler App:- https://github.com/llazzaro/django-scheduler
It giver various options to create events and occurrences
Documentation is here:- http://django-scheduler.readthedocs.io/en/latest/
I have a model known as Product in Django. Which is defined as below
`class Products(models.Model):
product_choice = (
('1' ,'sightseeing'),
('2','daytour'),
('3','activity'),
('3','experience'),
('4','rentals'),
('3','multidaytrip'),
)
product_type = models.CharField(max_length=20,choices=product_choice, null=True)
category = models.ForeignKey(Category, null=True)
title = models.CharField(max_length=100, blank=True, default='')
pic1 = models.ImageField(upload_to='media', default='media/ross-island-2.jpg')
pic2 = models.ImageField(upload_to='media', default='media/ross-island-2.jpg')
pic3 = models.ImageField(upload_to='media', default='media/ross-island-2.jpg')
shared_code = models.BooleanField(blank=True, default=False)
age_requirements = models.CharField(max_length=100, blank=True, default='')
time_slots = models.CharField(max_length=100 ,blank=True, default='')
location = models.CharField(max_length=100 ,blank=True, default='')
duration = models.CharField(max_length=100 ,blank=True, default='')
affiliated_institutions = models.CharField(max_length=100, null=True)
includes = models.TextField(blank=True)
excludes = models.TextField(blank=True)
medical_requirements = models.CharField(max_length=100, blank=True, default='')
perks_included = models.CharField(max_length=100, blank=True, default='')
product_detail = models.TextField()
vender_name = models.CharField(max_length=100, blank=False)
user = models.ManyToManyField(settings.AUTH_USER_MODEL)
vendor_id = models.IntegerField(blank=True)
about_vender = models.TextField()
price = models.IntegerField(default=0)
child_price = models.IntegerField(default=0)
infant_price = models.IntegerField(default=0)
product_detail = models.TextField(blank=True)
slug = models.SlugField(unique=True, blank=True)
total_slots = models.IntegerField(blank=True, null=True)
open_slots = models.IntegerField(blank=True , null=True)
cancellation_policy = models.TextField(blank=True)
def __unicode__(self):
return str(self.title)
def __str__(self):
return str(self.title)
`
I have installed the Django-Scheduler in my Django Application, however it is installed as a separate app.
I am using Django Rest Framework(DRF) and doing all these alterations via DRF.
class ProductListAPIView(ListAPIView):
queryset = Products.objects.all()
permission_classes = (IsAdminOrReadOnly, )
serializer_class = ProductSerializer
def get_queryset(self):
return Products.objects.all()
def get(self, request, format=None):
snippets = Products.objects.all()
serializer_class = ProductSerializer(snippets, many=True)
return Response(serializer_class.data)
def post(self, request, format=None):
serializer = ProductSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
`
Now I need to create events with the help of Django-Scheduler while creating the Product when a new request comes via Django Rest Framework.
Thanks in anticipation, Please let me know if I am missing on any part.
I have this simple model and I am having difficult in inserting related field of 'notes' through django rest framework.
class Student(models.Model):
firstName = models.CharField(max_length=100, blank=True, null=True)
lastName = models.CharField(max_length=100, blank=True, null=True)
prefLocation = models.ManyToManyField("Location", blank=True, null=True, related_name = 'prefLocation')
def __unicode__(self):
return self.firstName
class LocationRegion(models.Model):
regionName = models.CharField(max_length=100)
def __unicode__(self):
return self.regionName
class Location(models.Model):
locationName = models.CharField(max_length=100)
region = models.ForeignKey(LocationRegion, null=True, blank=True, related_name='locations')
def __unicode__(self):
return self.locationName
class Note(models.Model):
text = models.CharField(max_length=1000)
student = models.ForeignKey(Student, null=True, blank=True, related_name='notes')
def __unicode__(self):
return self.text
class StudentViewSet(viewsets.ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializer
I am unsure if I need to use ModelSerializer or generic Serializer. Validated_data doesn't return 'note' field in the deserialized data. I would appreciate any help with the serializer.
Thanks
Here are my serializers :
class StudentSerializer(serializers.ModelSerializer):
def create(self, validated_data):
def get_notes(self, obj):
return validated_data['note']
note = serializers.SerializerMethodField('get_notes')
return Candidate.objects.create(**validated_data)
class Meta:
model = Student
fields = ('id', 'firstName', 'lastName', 'note')
class NoteSerializer(serializers.ModelSerializer):
class Meta:
model = Note