Django User specific page - django

I m creating a Leave Web Application. I want to show each user's leave status according to the user who is logged in.
from django.db import models
from django.contrib.auth.models import User
types_of_leaves = (
('Sick Leave', 'Sick Leave'),
('Earned Leave', 'Earned Leave'),
('Annual Leave', 'Annual Leave'),
)
# Create your models here.
class LeaveApp(models.Model):
authuser = models.ForeignKey(User, on_delete=models.CASCADE)
fdate = models.DateField()
tdate=models.DateField()
type_of_leave=models.CharField(max_length=20 ,choices =types_of_leaves, default = "" )
reason = models.CharField(max_length=500)
def __str__(self):
return self.reason
class Sick_leave(models.Model):
leave=models.CharField(max_length = 40)
def __str__(self):
return self.leave

Related

AttributeError: Manager isn't available; 'auth.User' has been swapped for 'users.User'

I am working on a Django chat application using Django channels but I have run into a problem. I am getting the error AttributeError: Manager isn't available; 'auth.User' has been swapped for 'users.User' in my console and I cannot figure out how to solve this issue. In my project, I am checking whether users have an history in their chat, and if there is no history I create one.
Inside the users app where I am registering users, I have used the AbstractUser model and therefore I have AUTH_USER_MODEL='users.User' inside the setting.py.
Here is my Models.py for the chat application:
from django.contrib.auth import get_user_model
from django.conf import settings
User = get_user_model()
class TrackingModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Thread(TrackingModel):
THREAD_TYPE = (
('personal', 'Personal'),
('group', 'Group')
)
name = models.CharField(max_length=50, null=True, blank=True)
thread_type = models.CharField(max_length=15, choices=THREAD_TYPE, default='personal')
users = models.ManyToManyField('users.User')
objects = ThreadManager()
def __str__(self) -> str:
if self.thread_type == 'personal' and self.users.count() == 2:
return f'{self.users.first()} and {self.users.last()}'
return f'{self.name}'
class Message(TrackingModel):
thread = models.ForeignKey(Thread, on_delete=models.CASCADE)
sender = models.ForeignKey('users.User', on_delete=models.CASCADE)
text = models.TextField(blank=False, null=False)
def __str__(self) -> str:
return f'From <Thread - {self.thread}>'
And here is the Managers.py file:
User = get_user_model()
class ThreadManager(models.Manager):
def get_or_create_personal_thread(self, user1, user2):
threads = self.get_queryset().filter(thread_type='personal')
threads = threads.filter(users__in=[user1, user2]).distinct()
threads = threads.annotate(u_count=Count('users')).filter(u_count=2)
if threads.exists():
return threads.first()
else:
thread = self.create(thread_type='personal')
thread.users.add(user1)
thread.users.add(user2)
return thread
def by_user(self, user):
return self.get_queryset().filter(users__in=[user])
Any help will be highly appreciated.
I have tried replacing the line users = models.ManyToManyField('users.User') with users = models.ManyToManyField('auth.User') but it still gives the same error.

NOT NULL constraint failed: shipping_ship.user_id Django

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()

Cannot access field in Django Graphene

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

Delete an user object automatically after some time in django models

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.

django not add auto increment primary key id when save an article

I hava an article app installed in django admin site,when i finish editing one article,I click the save button,but an error page:
article/models.py
# blog category models
class Category(models.Model):
id = models.IntegerField(primary_key=True,help_text='primary key')
name = models.CharField(max_length=50,help_text='category name')
description = models.TextField(default='',help_text='category description')
createtime = models.DateTimeField(auto_now_add=True)
modifytime = models.DateTimeField(auto_now=True)
categories = models.Manager()
class Meta:
db_table = 'article_category'
def __str__(self):
return self.name
#blog article models
class Article(models.Model):
STATUS = (
(0,'on'),
(1,'off')
)
id = models.IntegerField(primary_key=True,help_text='primary key')
category = models.ForeignKey(Category,help_text='foreigner key reference Category')
title = models.CharField(max_length=100,help_text='article title')
content = models.TextField(help_text='article content')
like = models.IntegerField(default=0,help_text='like numbers')
secretcode = models.CharField(max_length=512,help_text='who has the code can scan')
status = models.IntegerField(choices=STATUS,help_text='status of the article')
createtime = models.DateTimeField(auto_now_add=True,help_text='time that first created')
modifytime = models.DateTimeField(auto_now=True,help_text='time when modified')
articles = models.Manager()
class Meta:
db_table = 'article'
article/widgets.py
from pagedown.widgets import AdminPagedownWidget
from django import forms
from .models import Article
class ArticleModelForm(forms.ModelForm):
content = forms.CharField(widget=AdminPagedownWidget())
class Meta:
model = Article
fields = ('title','category', 'content', 'secretcode', 'status')
article/admin.py
from django.contrib import admin
from .widgets import ArticleModelForm
from .models import Article,ArticleImage,Category
class MMBArticleAdmin(admin.ModelAdmin):
form = ArticleModelForm
admin.site.register(Article,MMBArticleAdmin)
admin.site.register(Category)
admin.site.register(ArticleImage)
the page in the admin site looks likeļ¼š
and then I click save ,the error page show up like above!why did this happen?and how to fix it?
You've overridden the default automatic field with a manual non-autoincrementing ID. Don't do that. Remove your id fields altogether.