Get queryset for a ListView on a boolean field - django

I can't understand why this code doesn't work. I have a model called CustomUser with a BooleanField field called expert. I want to filter the users to include users where expert = True.
I've tried self.expert, user___expert and customuser__expert in place of "expert" and none of these worked.
views.py:
from django.shortcuts import render
from django.views.generic import TemplateView, ListView
from users.models import CustomUser
class BrowseView(ListView):
model = CustomUser
template = 'expert_list.html'
def get_queryset(self):
experts = CustomUser.objects.filter(expert == True)
return experts
models.py:
class CustomUser(AbstractUser):
objects = CustomUserManager()
position = models.CharField(max_length =50, null=True, default='')
bio = models.CharField(max_length=300, null=True, default='')
expert = models.BooleanField(blank=True, default=False)

You can filter by passing a named argument in the .filter(..) call, for example:
class BrowseView(ListView):
model = CustomUser
template = 'expert_list.html'
queryset = CustomUser.objects.filter(expert=True)

Related

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

Why Django form.save() returns object(None)?

from django.shortcuts import render
from django.forms import forms
from .models import Chart, ChartData
from .forms import ChartForm, ChartDataForm
import datetime
def home(request):
chart_form = ChartForm(request.POST)
chart_data_form = ChartDataForm(request.POST)
context = {
'chart_form': chart_form,
'chart_data_form': chart_data_form,
}
if chart_form.is_valid():
chart_obj = chart_form.save()
chart = Chart.objects.get(pk=23)
print(chart_obj)
print(chart)
return render(request, 'charts/home.html', context)
chart_form.save() returns "Chart object (None)
I have to eventually pass the chart_obj to another model for the foreign key, but right now it brakes there with error - save() prohibited to prevent data loss due to unsaved related object.
In the admin site I see that the object is created.
models.py below
import datetime
from django.db import models
from django.forms import DateTimeField
# Create your models here.
class Chart(models.Model):
id = models.IntegerField(primary_key=True)
type = models.CharField(max_length=10)
chartname = models.CharField(max_length=20, null=True)
class ChartData(models.Model):
dataY = models.IntegerField()
dataX = models.DateTimeField()
chart = models.ForeignKey(Chart, on_delete=models.CASCADE)
forms.py below
from django import forms
from .models import Chart, ChartData
class ChartForm(forms.ModelForm):
class Meta:
model = Chart
fields = ['type','chartname']
class ChartDataForm(forms.ModelForm):
class Meta:
model = ChartData
fields = ['dataY']
You should use an AutoField to populate the model object when you save the object, so:
class Chart(models.Model):
id = models.AutoField(primary_key=True)
type = models.CharField(max_length=10)
chartname = models.CharField(max_length=20, null=True)
or just without an id field:
class Chart(models.Model):
type = models.CharField(max_length=10)
chartname = models.CharField(max_length=20, null=True)
Here you don't need to define the id explicitly, because Django does the same thing for you. If you want to rename the primary key to another thing, you can use the method below.

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

how to create tag field in django form like youtube have

i want to create a tag field like youtube give tage field while uploading a vedio this is what i tried in in my blog form
my models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
# Create your models here.
class Blog(models.Model):
author = models.OneToOneField(User, on_delete=models.CASCADE,)
title = models.CharField(max_length=200,blank=False,)
thumbnail = models.ImageField(upload_to='blogs_thumbnail',default='blogdefa.png')
tags = models.CharField(max_length=500, blank=False, default='Blog')
data = models.TextField(blank=False,)
published_date = models.DateTimeField(default=timezone.now,editable=False)
update_at = models.DateTimeField(auto_now=True,editable=False)
def __str__(self):
return self.title
any idea how to do it i don,t know how to do it
my forms.py
from django import forms
from django.forms import ModelForm, Textarea
from django.contrib.auth.models import User
from .models import Blog, comment, report
forms here
class BlogForm(forms.ModelForm):
class Meta:
model = Blog
fields = '__all__'
widgets = {'data': Textarea(attrs={'cols': 80, 'rows': 20, 'placeholder':'Write Here'}),
'title':forms.TextInput(attrs={'placeholder':'Your Blog Title Here'}),
'tags': forms.TextInput(attrs={'placeholder':'Please enter you content related tags'}),
}
exclude = ['author','published_date','update_at']
all i want is user can create his own tag for blogs like in youtube and not like stackoverflow where you have use to choose you tag
please help
currently it look like this
which is not cool
First thing is that tags work. So to get them working you should relate it to your post.
So you should create a Tag model and use a ManytoManyRelated field to relate tags because you need to get to the post/result at the end using tags.
from django.db import models
from django_extensions.db.fields import AutoSlugField
from django.db.models import CharField, TextField, DateField, EmailField, ManyToManyField
class Tag(models.Model):
name = CharField(max_length=31, unique=True, default="tag-django")
slug = AutoSlugField(max_length=31, unique=True, populate_from=["name"])
def __str__(self):
return self.name
class YourPost(models.Model):
name = CharField(max_length=31, db_index=True)
slug = AutoSlugField(max_length=31, unique=True, populate_from=["name"])
description = TextField()
date_founded = DateField(auto_now_add=True)
contact = EmailField()
tags = ManyToManyField(Tag, related_name="tags")
class Meta:
get_latest_by = ["date_founded"]
def __str__(self):
return self.name
Go on from here.
Create serializers, Viewsets. Relate your tags to your post.

how to upload an image from django rest framework using browse button?

i am new to django-rest-framework,i am unble to get the image as browse button in my rest framework,i am getting text field,here is my code as follows...........
views.py
from django.shortcuts import render
from serializers import *
from rest_framework import viewsets
class newsViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = news.objects.all()
serializer_class = newsSerializer
class news_categoriesViewSet(viewsets.ModelViewSet):
queryset = news_categories.objects.all()
serializer_class = news_categoriesSerializer
models.py
from django.db import models
from django.utils.encoding import smart_unicode
class news_categories(models.Model):
cat_name = models.CharField(max_length=30, null=True)
created_at = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return smart_unicode(self.cat_name)
def Content_files(instance, filename):
return '/'.join(['Media','News Image', filename])
class news(models.Model):
name = models.CharField(max_length=30,null=True)
description = models.TextField()
cat_id = models.ForeignKey('news_categories')
image = models.FileField(upload_to=Content_files,null=True)
date = models.DateField()
created_at = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return smart_unicode(self.name)
serializers.py
from django.forms import widgets
from rest_framework import serializers
from models import *
class newsSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = news
fields = ('url','id','name','description','cat_id','image','date')
class news_categoriesSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = news_categories
fields = ('url','id','cat_name')
Any one can Help me?Thanks in Advance....
the problem with settings.py and version of rest framework ,use 2.4.4
I stumbled upon the same problem when I updated to version 3.0. The solution is to define the FileField or ImageField in your serializer using a style attribute:
file = serializers.FileField(style = {'input_type': 'file'})