Django rest framework partial update with where query - django

I just want to update two fields of table where id_payment = 1. How to do it? It showing me the error bellow.
IntegrityError at /receivePendingPayment/
(1048, "Column 'bank_id' cannot be null")
#View
#permission_classes([IsAuthenticated])
#api_view(['PATCH'])
def receivePendingPayment(request):
id_payment = request.data['id_payment']
data = {'accountant_received_by': request.user.id, 'accounts_status': 'Received'}
BankPaymentHistory.objects.filter(id=id_payment)
serializer = BankPaymentUpdateSerializer(data=data, partial=True, many=False)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#Serializer
class BankPaymentUpdateSerializer(serializers.ModelSerializer):
class Meta:
model = BankPaymentHistory
fields = ('accounts_status','accountant_received_by')
#Model
class BankPaymentHistory(models.Model):
activation_enum = (('Active', 'Active'), ('Deactive', 'Deactive'))
accounts_status_enum = (('Pending', 'Pending'), ('Received', 'Received'))
bank = models.ForeignKey(Bank, on_delete=models.CASCADE)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
file = models.ForeignKey(File, on_delete=models.CASCADE)
salesperson = models.ForeignKey(SalesPerson, on_delete=models.CASCADE)
paymentmode = models.ForeignKey(PaymentModes, on_delete=models.CASCADE)
amount = models.PositiveIntegerField()
chequeno = models.CharField(max_length=50, unique=True)
chequedate = models.DateField()
paymentdate = models.DateField()
remark = models.TextField(blank=True, null=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
accountant_received_by = models.ForeignKey(User, related_name='%(class)s_accountant_received_by', on_delete=models.CASCADE, null = True)
accountant_received_date = models.DateTimeField(default=datetime.now)
create_date = models.DateTimeField(default=datetime.now)
activation_status = models.CharField(max_length=20, choices=activation_enum, default='Active')
accounts_status = models.CharField(max_length=20, choices=accounts_status_enum, default='Pending')

Pass an instance to the serializer, so it can know that it should do an update.
instance = BankPaymentHistory.objects.filter(id=id_payment).first()
serializer = BankPaymentUpdateSerializer(instance=instance, data=data, partial=True, many=False)

Related

Cannot assign "'user_name'": "Class.user" must be a "Account_class" instance

enter image descripI am getting this error when I try to make a post requesttion here
How to can I solve this problem?
Here is my model:
class Coffee(models.Model):
name = models.CharField(max_length=60)
ratings = models.CharField(max_length=5)
taste = models.TextField()
coffeeType = models.CharField(max_length=60)
price = models.CharField(max_length=60)
img = models.CharField(max_length=200)
updated_at = models.DateTimeField(auto_now_add=True)
shopName = models.CharField(max_length=60)
coffeeShopID = models.CharField(max_length=200)
location = models.CharField(max_length=200)
user = models.ForeignKey(Account, on_delete=models.CASCADE, null=False, blank=False, related_name='user')
def __str__(self):
return self.name[0:50]
class Meta:
ordering = ['-updated_at']
Here is the serializer of that model:
class CoffeeSerializers(serializers.ModelSerializer):
class Meta:
model = Coffee
fields = '__all__'
Here is views for post request:
def addCoffee(request):
data = request.data
coffee = Coffee.objects.create(
name=data['name'],
ratings=data['ratings'],
taste=data['taste'],
coffeeType=data['coffeeType'],
price=data['price'],
img=data['img'],
shopName=data['shopName'],
coffeeShopID=data['coffeeShopID'],
location=data['location'],
user=data['user']
)
coffee.save()
serializer = CoffeeSerializers(coffee)
return Response(serializer.data)
i can only assume how your Account model looks like, problem is that you must send Account model, but you are sending string data['user']
def addCoffee(request):
data = request.data
account_object = Account.objects.get(THIS_IS_ACCOUNT_NAME = data['user'])
coffee = Coffee.objects.create(
name=data['name'],
ratings=data['ratings'],
taste=data['taste'],
coffeeType=data['coffeeType'],
price=data['price'],
img=data['img'],
shopName=data['shopName'],
coffeeShopID=data['coffeeShopID'],
location=data['location'],
user=account_object
)
coffee.save()
serializer = CoffeeSerializers(coffee)
return Response(serializer.data)

Testing POST request throwing a KeyError in Postman

I am currently testing my POST request for the Tagging model. For this, I have tried to override the create() method. I am not so sure I have done this correctly but I tried everything I could think of. I even removed it and tried testing the POST request without overriding it.
I keep getting this error while testing with Postman:
KeyError at /api/tagging 'user'
How can I get rid of this error? What is my create() method missing?
serializers.py
class TaggingSerializer(serializers.ModelSerializer):
tag = StringRelatedField()
resource = serializers.PrimaryKeyRelatedField(read_only=True)
gameround = serializers.PrimaryKeyRelatedField(read_only=True)
user = CustomUserSerializer(required=False, read_only=True)
class Meta:
model = Tagging
fields = ('id', 'user', 'gameround', 'resource', 'tag', 'created', 'score', 'origin')
def create(self, validated_data):
"""Create and return a new tagging"""
tagging = Tagging(
user=validated_data["user"],
gameround=validated_data["gameround"],
resource=validated_data["resource"],
tag=validated_data["tag"],
created=validated_data["created"],
score=validated_data["score"],
origin=validated_data["origin"]
)
tagging.save()
return tagging
def to_representation(self, data):
data = super().to_representation(data)
return data
If I change the create method to:
def create(self, validated_data):
"""Create and return a new tagging"""
tagging = Tagging(
user=validated_data.get("user"),
gameround=validated_data.get("gameround"),
resource=validated_data.get("resource"),
tag=validated_data.get("tag"),
created=validated_data.get("created"),
score=validated_data.get("score"),
origin=validated_data.get("origin")
)
tagging.save()
return tagging
I am getting an
IntegrityError: null value in column "created" of relation "app_tagging" violates not-null constraint
DETAIL: Failing row contains (15, null, 0, , null, null, null, null).
This is my post request:
def post(self, request, *args, **kwargs):
tagging_serializer = TaggingSerializer(data=request.data)
if tagging_serializer.is_valid(raise_exception=True):
tagging_serializer.save(tagging=request.data)
return Response({"status": "success", "data": tagging_serializer.data}, status=status.HTTP_200_OK)
else:
return Response({"status": "error", "data": tagging_serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
This is the JSON I am sending
{
"user": null,
"gameround": 1,
"resource": 602,
"tag": "RTTesttaggg",
"created": "2022-12-12T15:19:49.031000Z",
"score": 0,
"origin": ""
}
models.py
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(verbose_name='email address', unique=True)
username = models.CharField(max_length=256, unique=True, blank=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
first_name = models.CharField(max_length=256, null=True)
last_name = models.CharField(max_length=256, null=True)
date_joined = models.DateTimeField(editable=False, default=timezone.now)
is_superuser = models.BooleanField(default=False)
date_joined = models.DateTimeField(default=timezone.now)
is_uploader = models.BooleanField(default=False)
first_name = models.CharField(max_length=256)
last_name = models.CharField(max_length=256)
updated_at = models.DateTimeField(auto_now=True)
REQUIRED_FIELDS = ['username']
objects = CustomUserManager()
USERNAME_FIELD = 'email'
def get_username(self):
return self.username
def __str__(self):
return f'{self.email} ({self.username})' or ''
class Resource(models.Model):
id = models.PositiveIntegerField(null=False, primary_key=True)
hash_id = models.CharField(max_length=256)
creators = models.ManyToManyField(Creator)
titles = models.ManyToManyField(Title)
created_start = models.DateField(null=True)
created_end = models.DateField(null=True)
location = models.CharField(max_length=512, null=True)
institution_source = models.CharField(max_length=512, blank=True)
institution = models.CharField(max_length=512, blank=True)
origin = models.URLField(max_length=256, null=True)
enabled = models.BooleanField(default=True)
media_type = models.CharField(max_length=256, default='picture')
objects = models.Manager()
def __str__(self):
return self.hash_id or ''
#property
def tags(self):
tags = self.taggings.values('tag').annotate(count=Count('tag'))
return tags.values('tag_id', 'tag__name', 'tag__language', 'count')
class Gameround(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
gamesession = models.ForeignKey(Gamesession, on_delete=models.CASCADE)
created = models.DateTimeField(editable=False)
score = models.PositiveIntegerField(default=0)
objects = models.Manager()
#property
def tags(self):
tags = self.taggings.values('tag')
return tags.values('tag_id', 'tag__name', 'tag__language', 'resource_id')
class Tag(models.Model):
name = models.CharField(max_length=256)
language = models.CharField(max_length=256)
objects = models.Manager()
def __str__(self):
return self.name or ''
#property
def tags(self):
tags = self.tagging.values('tag')
return tags.values('tag_id', 'tag__name', 'tag__language')
class Tagging(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
gameround = models.ForeignKey(Gameround, on_delete=models.CASCADE, related_name='taggings')
resource = models.ForeignKey(Resource, on_delete=models.CASCADE, related_name='taggings')
tag = models.ForeignKey(Tag, on_delete=models.CASCADE, related_name='tagging')
created = models.DateTimeField(editable=False)
score = models.PositiveIntegerField(default=0)
origin = models.URLField(max_length=256, blank=True, default='')
objects = models.Manager()
def __str__(self):
return str(self.tag) or ''

KeyError Post DjangoRestFramework

I'm new on Django Rest Framework and when I want to POST data I get a error: KeyError: 'id_area' I do not know what I'm doing wrong. Here's my code:
in my models.py
class Area(models.Model):
id_area = models.AutoField(primary_key=True)
APM = 'apm'
BUSINESS = 'business'
DESARROLLO = 'desarrollo'
SISTEMAS = 'sistemas'
ATENTUSIANOS_CHOICES = (
(APM, 'Apm'),
(BUSINESS, 'Business'),
(DESARROLLO, 'Desarrollo'),
(SISTEMAS, 'Sistemas'),
)
nombre = models.CharField(max_length=255, choices=ATENTUSIANOS_CHOICES)
class Meta:
verbose_name = 'Área'
verbose_name_plural = 'Áreas'
def __str__(self):
return self.nombre
class Atentusiano(models.Model):
id_atentusiano = models.AutoField(primary_key=True)
nombre = models.CharField(max_length=255, blank=False, null=False)
apellido = models.CharField(max_length=255, blank=False, null=False)
correo = models.CharField(max_length=255, blank=False, null=False, unique=True)
anexo = models.CharField(max_length=255, blank=True, null=True)
area = models.ForeignKey(Area, related_name='areas', on_delete=models.CASCADE)
class Meta:
verbose_name = 'Atentusiano'
verbose_name_plural = 'Atentusianos'
ordering = ['nombre']
def __str__(self):
return self.nombre + ' ' + self.apellido
in my serializers.py
class AreaSerializer(serializers.ModelSerializer):
areas = serializers.CharField(read_only=True)
class Meta:
model = Area
fields = ('id_area', 'nombre', 'areas')
class AtentusianoSerializer(serializers.ModelSerializer):
atentusianos = serializers.CharField(read_only=True)
area = serializers.CharField(source='area.nombre', read_only=True)
id_area = serializers.CharField(source='area.id_area')
class Meta:
model = Atentusiano
fields = ['id_atentusiano', 'nombre', 'apellido', 'correo', 'anexo', 'id_area', 'area', 'atentusianos']
def create(self, validated_data):
area_data = validated_data.pop('id_area')
area = models.Area.objects.create(**area_data)
atentusiano = models.Atentusiano.objects.create(area=area, **validated_data)
return atentusiano
And in my views.py
class AtentusianoView(viewsets.ModelViewSet):
queryset = Atentusiano.objects.all()
serializer_class = AtentusianoSerializer
class AreaView(viewsets.ModelViewSet):
queryset = Area.objects.all()
serializer_class = AreaSerializer
The problem is that when I want to Post data, for example:
{
"nombre": "name",
"apellido": "lastname",
"correo": "email#gmail.com",
"anexo": "1364",
"id_area": "1"
}
i got this error area_data = validated_data.pop('id_area')
KeyError: 'id_area'
I need help please
you should pop like this,
class AtentusianoSerializer(serializers.ModelSerializer):
.....
.....
class Meta:
model = Atentusiano
fields = ['id_atentusiano', 'nombre', 'apellido', 'correo', 'anexo', 'id_area', 'area', 'atentusianos']
def create(self, validated_data):
id_area = validated_data.pop('area')['id_area'] # here the correction
area = Area.objects.create(id_area=id_area) # an additional correction
atentusiano = Atentusiano.objects.create(area=area, **validated_data)
return atentusiano
EDIT: As id_area value, you are passing a string instead of an integer which will through another error. Also not,
area = models.Area.objects.create(**area_data)
it should be,
area = Area.objects.create(id_area=id_area)

how to save multiple model-forms (which are in 1:1) simultaneously in a view (Django)

how to save multiple model-forms (lAWYER AND CATEGORY) (which are in 1:1) simultaneously in a view (Django)
class Lawyer(models.Model):
category = models.ForeignKey(Category, related_name='lawyer', on_delete=models.CASCADE)
profile = models.ForeignKey(Profile, related_name='profiles', on_delete=models.CASCADE)
name = models.CharField(max_length=100, db_index=True)
slug = models.SlugField(max_length=100, db_index=True)
class Category(models.Model):
profile = models.ForeignKey(Profile, related_name='profile', on_delete=models.CASCADE)
category_name = models.CharField(max_length=10, db_index=True,choices=CATEGORY_CHOICES)
slug = models.SlugField(max_length=150, unique=True, db_index=True)
city = models.CharField(max_length=20)
IN VIEWS.PY
def lawyer_list(request, category_slug=None):
if request.method == 'POST':
cat_form = CategoryForm(request.POST)
if cat_form.is_valid():
cat_obj = cat_form.save(commit=False)
cat_obj.profile = request.user.profile
cat_obj.save()
lawyer_form = LawyerForm(request.POST)
if lawyer_form.is_valid():
lawyer_form = lawyer_form.save(commit=False)
lawyer_form.profile = request.user.profile
lawyer_form.category = cat_obj
lawyer_form.save()
ALSO HAVE TWO FORMS
1) class LawyerForm(forms.ModelForm)
2)class CATEGORYForm(forms.ModelForm)
IN VIEWS I DONT WANT TO MAKE TWO OBJECT
Forms.py
enter code here
CATEGORY_CHOICES = (('CRIMINAL', 'Criminal'),('EMPLOYMENT', 'Employment'),
('CORPORATE', 'Corporate'),)
class CategoryForm(forms.ModelForm):
category_name = forms.CharField(max_length=3,
widget=forms.Select(choices=CATEGORY_CHOICES),)
class Meta:
model = Category
fields = ('category_name','city',)
class LawyerForm(forms.ModelForm):
class Meta:
model = Lawyer
fields = ('name','description','charge','available',)
class Lawyer(models.Model):
category = models.ForeignKey(Category, related_name='lawyer', on_delete=models.CASCADE)
profile = models.ForeignKey(Profile, related_name='profiles', on_delete=models.CASCADE)
name = models.CharField(max_length=100, db_index=True)
slug = models.SlugField(max_length=100, db_index=True)
class Category(models.Model):
profile = models.ForeignKey(Profile, related_name='profile', on_delete=models.CASCADE)
category_name = models.CharField(max_length=10, db_index=True,choices=CATEGORY_CHOICES)
slug = models.SlugField(max_length=150, unique=True, db_index=True)
city = models.CharField(max_length=20)
def save(self, *args, **kwargs):
lawyer=Lawyer(*args,**kwargs)
lawyer.category=self
lawyer.save()
super(Category, self).save(*args, **kwargs)
in views
def lawyer_list(request, category_slug=None):
if request.method == 'POST':
cat_form = CategoryForm(request.POST)
if cat_form.is_valid():
cat_obj = cat_form.save(commit=False)
cat_obj.profile = request.user.profile
cat_obj.save()

Django rest framework - cant serialize query set

I try to serialize query set
def do(self):
reservations = Reservation.objects.all()
serializer = ReservationSerializer(data=reservations, many=True)
if serializer.is_valid():
encoded_data = json.dumps(serializer.data)
r = requests.post('http://httpbin.org/post', headers={'Content-Type': 'application/json'}, data=encoded_data)
print(r.text)
else:
print(serializer.errors)
And I always get error of
{u'non_field_errors': [u'Expected a list of items but got type "QuerySet".']}
I tried to use values() on query set, and then convert to list, but this way I get objects without nested models
model
class Reservation(models.Model):
start = models.DateField(verbose_name='Заезд', auto_now=False, auto_now_add=False, blank=False)
end = models.DateField(verbose_name='Выезд', auto_now=False, auto_now_add=False, blank=False)
check_in_time = models.TimeField(verbose_name='Время заезда', blank=False)
check_out_time = models.TimeField(verbose_name='Время выезда', blank=False)
has_refund = models.BooleanField(verbose_name='Возвратная бронь', default=True)
payed = models.BooleanField(verbose_name='Оплачено', default=False)
reserved_days = models.ManyToManyField(Day, blank=False)
additional_services = models.ManyToManyField(AdditionalService)
guest_name = models.CharField(verbose_name='Имя гостя', max_length=200, blank=True)
reservation_number = models.CharField(verbose_name='Номер брони', max_length=200, blank=True)
class AdditionalService(models.Model):
payment_date = models.CharField(verbose_name='Дата оплаты', max_length=200, blank=True)
payment_type = models.CharField(verbose_name='Форма оплаты', max_length=200, blank=False)
service = models.CharField(verbose_name='Услуга', max_length=200, blank=False)
quantity = models.IntegerField(blank=False)
price = models.FloatField(blank=False)
class Day(models.Model):
date = models.DateField(auto_now=False, auto_now_add=False)
price = models.FloatField()
payment_method = models.CharField(max_length = 200, blank=True)
payment_date = models.CharField(max_length=200, blank=True)
room = models.ForeignKey(Room, null=True, blank=True, verbose_name='Номер', on_delete=models.CASCADE)
class Room(models.Model):
name = models.CharField(max_length = 200, null=True)
id = models.AutoField(primary_key=True)
room_id = models.CharField(max_length = 200, null=False)
def __unicode__(self):
return self.name
serializers
class ReservationSerializer(serializers.ModelSerializer):
reserved_days = DaySerializer(many=True)
additional_services = AdditionalServicesSerializer(many=True)
class Meta:
model = Reservation
fields = [
'start',
'end',
'check_in_time',
'check_out_time',
'reserved_days',
'additional_services',
'has_refund',
'payed',
'guest_name',
'reservation_number',
]
class DaySerializer(serializers.ModelSerializer):
room = RoomSerializer()
class Meta:
model = Day
fields = [
'date',
'price',
'payment_method',
'payment_date',
'room',
]
class AdditionalServicesSerializer(serializers.ModelSerializer):
class Meta:
model = AdditionalService
fields = [
'payment_date',
'payment_type',
'service',
'quantity',
'price',
]
class RoomSerializer(serializers.ModelSerializer):
class Meta:
model = Room
fields = [
'room_id',
]
For serialization you don't need to use data keyword, just pass queryset as first positional argument:
serializer = ReservationSerializer(reservations, many=True)
return serializer.data