When a Tasks instance is deleted i want to create a new Instance of Completed Tasks, which stores the deleted task.
Here is my code -
from django.db import models
from django.db.models.signals import post_delete, pre_delete
from django.urls import reverse, reverse_lazy
from django.contrib.auth.models import User
class Tasks(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
TaskName = models.CharField(max_length=100)
Description = models.CharField(max_length=400)
DueDate = models.DateField(help_text="YYYY-MM-DD")
priority = models.IntegerField()
def __str__(self):
return self.TaskName
def get_absolute_url(self):
return reverse('tasks:detail', kwargs={'pk': self.pk})
pre_delete.connect(lambda instance,**kwargs:CompletedTasks.obbjects.create(task = instance))
class CompletedTasks(models.Model):
task = models.ForeignKey(Tasks, on_delete=None)
But , it is not working , instances of CompletedTasks are not being created.
You cannot have a foreign key reference to a non existent object, I suggest that you have a field in the Tasks model that keeps track of the status of the Task.
Something like this:
class Tasks(models.Model):
STATUSES = (
('C','Completed'),
('A', 'Active'),
)
user = models.ForeignKey(User, on_delete=models.CASCADE)
task_name = models.CharField(max_length=100)
description = models.CharField(max_length=400)
due_date = models.DateField(help_text="YYYY-MM-DD")
priority = models.IntegerField()
status = models.CharField(max_length=1, choices=STATUSES, default='A')
Related
So I'm working on a shipping website with the django rest framework. The website brings two to four people together so they can easily ship their goods together at the same time. But I'm facing a major stumbling block on the views where user book a shipping the code is below.
models.py
from django.db import models
from django.contrib import get_user_model
User = get_user_model()
class Container(models.Model):
container_type = models.Charfield(max_length = 30, blank=False, null = False)
max_users = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places =2, default=0, blank=True, null=True)
users = models.ManyToManyField(User)
class Ship(models.Model):
container = models.ForeignKey(Container, related_name='cont', on_delete=models.CASCADE)
user = models.ForeignKey(User, related_name='shipper', on_delete=models.CASCADE)
location = (
('France', 'France'),
)
from_location = models.CharField(max_length=30, choices=location, blank=False, null=False)
to_location = (
('Lagos', 'Lagos'),
('Abuja', 'Abuja'),
('Abeokuta', 'Abeokuta'),
('Osun', 'Osun'),
)
to_location = models.CharField(max_length=30, choices=to_location, blank=False, null=False)
date_leaving = models.DateField(auto_now=False)
price = models.DecimalField(max_digits=10, decimal_places=2, default=0, blank=True, null=True)
def __str__(self):
return self.user
then my serializer.py file
from rest_framework import serializers
from .models import Container, Ship
class ContainerSerializer(serializers.ModelSerializer):
class Meta:
model = Container
fields = '__all__'
class MiniContainerSerializer(serializers.ModelSerializer):
class Meta:
model = Container
fields =['container_type', 'price']
class ShipSerializer(serializers.ModelSerializer):
class Meta:
model = Ship
fields = '__all__'
read_only_fields = ('user', 'price')
class MiniShipSerializer(serializers.ModelSerializer):
class Meta:
model = Ship
fields = ['container', 'from_location', 'to_location']
and now my views.py file which I have issues with
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from rest_framework.generics import ListCreateAPIView, CreateAPIView, ListAPIView, RetrieveUpdateDestroyAPIView, RetrieveAPIView
from .serializers import ContainerSerializer, MiniContainerSerializer, ShipSerializer, MiniShipSerializer
from rest_framework import permissions, status
from rest_framework.response import Response
from .models import Container, Ship
class ShipAPI(ListCreateAPIView):
serializer_class = ShipSerializer
def get_queryset(self):
user = self.request.user
queryset = Ship.objects.filter(user=user)
return queryset
def Book_shipping(self, request, *args, **kwargs):
user = request.user
container = get_object_or_404(Container, pk=request.data['container'])
if container.users.count() >= container.max_users:
return Response('container already full')# here i'm trying to set limits so the users joining each container won't surpass the max users.
cont = container(users=user)
cont.save()
from_location = (request.data['from_location'])
to_location = (request.data['to_location'])
date_leaving = int(request.data['date_leaving'])
price = container.price / container.max_users
cart = Ship(container=container, user=user, from_location=from_location, to_location=to_location, date_leaving=date_leaving, price=price)
cart.save()
serializer = ShipSerializer(cart)
data ={'message': 'shipping successfully created',
'data':serializer.data}
return Response(data=data, status=status.HTTP_201_CREATED)
and then after testing the endpoint it returns this error:
IntegrityError at /Shipping/Ship/
NOT NULL constraint failed: shipping_ship.user_id
I've tried debugging and looking at it over and over again can someone please help me? Thanks in advance. And yes I've tried deleting migrations and the database.
As your Container model have a ManyToMany relationship with the User model.
So it may not work like cont = container(users=user)
For me it worked like this:
cont = container.users.add(user)
cont.save()
The field which is specified in my models file is not included in the GraphiQL, I have tried to rename the field, delete it and define it again, even changing the type of field also updating the graphene-django package. None of these I have mentioned didn't work. The name of the field I can't get is named book
models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from books.models import Book
class Borrowing(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
book = models.OneToOneField(Book, null=True, on_delete=models.CASCADE)
date = models.DateTimeField(default=timezone.now)
returned = models.BooleanField(default=False)
date_borrowed = models.CharField(blank=True, null=True, max_length=50)
date_returned = models.CharField(blank=True, null=True, max_length=50)
class Meta:
ordering = ['-date']
def __str__(self):
return f'{self.user.username} borrowed {self.book.title}'
schema.py
import graphene
from .mutations.borrowings import *
from backend.functions import pagination
PAGE_SIZE = 12
class BorrowingMutation(graphene.ObjectType):
borrow_book = BorrowBook.Field()
return_book = ReturnBook.Field()
class BorrowingQuery(graphene.ObjectType):
borrowings = graphene.List(BorrowingType)
users_borrowings = graphene.List(BorrowingType, page=graphene.Int())
def resolve_borrowings(self, info):
return Borrowing.objects.all()
def resolve_users_borrowings(self, info, page):
user = info.context.user
borrowings = Borrowing.objects.filter(user=user, returned=False)
borrowings = pagination(PAGE_SIZE, page, borrowings)
return borrowings
Type
class BorrowingType(DjangoObjectType):
class Meta:
model = Borrowing
I want automatically delete the user object or make default="" in my model after 2 min.
Here is my model. What am I doing wrong!!
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime, timedelta
from django.utils import timezone
from datetime import date
class Action(models.TextChoices):
REQUESTED = 'Requested'
ACCEPTED = 'Accepted'
REJECTED = 'Rejected'
class UserMembership(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=255, default='')
student_id = models.CharField(max_length=10, default='')
membership_type = models.CharField(max_length=50)
membership_action = models.CharField(max_length=50, choices=Action.choices, default=Action.REQUESTED)
start_date = models.DateTimeField(default=timezone.now,blank=True,)
#property
def delete_after_thirty_days(self):
time = self.start_date + datetime.timedelta(minutes=2)
if time < datetime.datetime.now():
e = UserMembership.objects.get(user=self.user)
e.delete()
return True
else:
return False
def __str__(self):
return self.name
Basically, after 2 minutes the values of the UserMembership model related to the specific user should be deleted or change back to default values. currently, nothing happens and I don't get any errors as well. Thank you for your time.
My models Book and ReadList related and I can use them on Django Admin but I want to fetch bookPageCount field of selected object and save it to pageCount field of new object when save.
from django.db import models
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
# Create your models here.
class Book(models.Model):
bookname = models.CharField(max_length=200, verbose_name='Kitap Adı')
bookAuthor = models.CharField(max_length=100, verbose_name='Yazar Adı')
bookPublisher = models.CharField(max_length=100, verbose_name='Yayın Evi')
bookPageCount = models.PositiveIntegerField(verbose_name='Sayfa Sayısı')
bookAddDate = models.DateField(verbose_name='Kitaplığa Eklenme Tarihi')
class Meta:
verbose_name = 'Kitap'
verbose_name_plural = 'Kitaplar'
def __str__(self):
return self.bookname
class ReadList(models.Model):
bookName = models.ForeignKey('kitaplik.Book', related_name='book', on_delete=models.CASCADE, verbose_name='Kitap Adı')
readerName = models.ForeignKey('ogrenciler.Students', on_delete=models.CASCADE, related_name='readerName', verbose_name='Okuyan Kişi')
dateOfRead = models.DateField(verbose_name='Okuma Tarihi')
pageCount = models.PositiveIntegerField(verbose_name='Sayfa Sayısı',blank=True, null=True)
class Meta:
verbose_name = 'Okuma Günlüğü'
#receiver(post_save, sender=ReadList)
def get_pageCount(sender, instance, **kwargs):
instance.pageCount = instance.Book.bookPageCount
instance.save
EDIT: Changes been made after Higor's reminder but I still have problem as the same. The error I get is 'ReadList' object has no attribute 'Book'
I think you've mistaken some names.
#receiver(post_save, sender=ReadList)
def get_pageCount(sender, instance, **kwargs):
instance.pageCount = instance.book.bookpageCount
instance.save()
bookName is the field name
#receiver(post_save, sender=ReadList)
def get_pageCount(sender, instance, **kwargs):
instance.pageCount = instance.bookName.bookPageCount
instance.save()
I am following a tutorial online for Django. The presenter loads in random data as follows:
for i in xrange(100): Vote(link = Link.objects.order_by('?')[0],voter=a).save()
From what I could understand, it goes from 0 to 100 and creates a new vote. The vote object has a link object. I don't understand what the order_by('?') means.
Here is the model.py file:
from django.db import models
from django.contrib.auth.models import User
from django.db.models import Count
class LinkVoteCountManager(models.Manager):
def get_query_set(self):
return super(LinkVoteCountManager, self).get_query_set().annotate(
votes=Count('vote')).order_by("-votes")
class Link(models.Model):
title = models.CharField("Headline", max_length=100)
submitter = models.ForeignKey(User)
submitted_on = models.DateTimeField(auto_now=True)
rank_score = models.FloatField(default=0.0)
url = models.URLField("URL", max_length=250, blank=True)
description = models.TextField(blank=True)
with_votes = LinkVoteCountManager()
objects = models.Manager()
def __unicode__(self):
return self.title
class Vote(models.Model):
voter = models.ForeignKey(User)
link = models.ForeignKey(Link)
def __unicode__(self):
return "%s voted %s" %(self.voter.username, self.link.title)