Django - I need to specify amount of price rows - django

So i need to post on page price-row like: name: medicalservice --> contains this prices --->
1# --- name --- price --- quantity
2# --- 2name --- 2price --- 2quantity
And i want to post them in one page
i need to take price rows exactly declared for this medical service
I cant get the idia how to get it done through admin panel (i dont know how to insert quantity value quantity into it)
I created an intermidiate model (services_count) but i think its not best idea :0
from django.db import models
from tinymce import models as tiny_models
from django.urls import reverse
class Medservices(models.Model):
public = 'pub'
private = 'priv'
status_post = [(public,'public'),(private,'private')]
position = models.IntegerField(default=1, verbose_name="Позиція")
status = models.CharField(max_length=10,default=public,choices=status_post, verbose_name="Статус показу")
photo = models.ImageField(verbose_name='Фото послуги або акції', upload_to='services_images', max_length=None)
date_start = models.DateField(verbose_name='Дата початку', auto_now=False, auto_now_add=False)
date_expire = models.DateField(verbose_name='Дата початку', auto_now=False, auto_now_add=False)
title = models.CharField(verbose_name='Назва послуги або акції', max_length=300)
text = text = tiny_models.HTMLField()
slug = models.SlugField(max_length=255,unique=True,verbose_name="URL",db_index=True)
def __str__(self):
return f"{self.price.all} - to {self.status}"
def get_absolute_url(self):
return reverse('service_page', kwargs={'post_slug': self.slug})
class services_count(models.Model):
quantity = models.IntegerField(verbose_name='Кількість цієї послуги у сервісі')
service = models.ForeignKey("medservices.Medservices", verbose_name='Послуга або акція', on_delete=models.CASCADE)
prices = models.ManyToManyField("price.Price", verbose_name='Ціни')
admin panel:
from django.contrib import admin
from medservices.models import Medservices, services_count
# Register your models here.
class MedservicesAdmin(admin.ModelAdmin):
list_filter = ('status','date_expire',)
list_display = ('title','date_start','date_expire')
prepopulated_fields = {"slug": ("title",)}
admin.site.register(Medservices, MedservicesAdmin)
class ServicesCountAdmin(admin.ModelAdmin):
list_display = ('quantity',)
admin.site.register(services_count, ServicesCountAdmin)
views.py :
from django.shortcuts import render
from . import models
# Create your views here.
def services_page(request):
services_list = models.Medservices.objects.filter(status__contains='pub').order_by('position').all()
services_list_dict = {
'service_rows':services_list,
'title': 'Послуги МЦ "Сторожик"'
}
return render(request, 'medservices/index.html', context=services_list_dict)
def service_page(request):
pass
Model Price from other app
from django.core import validators
from django.db import models
# Create your models here.
class Price(models.Model):
price_all_menu = 'Загальні'
doc_cons = 'Консультації'
analises = 'Аналізи'
UZD = 'УЗД'
Urology = 'Урологія'
Gynekology = 'Гінекологія'
price_menu = [(price_all_menu,'Загальні'),(doc_cons,'Консультації'),(analises,'Аналізи'),(UZD, 'УЗД'), (Urology, 'Урологія'), (Gynekology, 'Гінекологія')]
public = 'pub'
private = 'priv'
status_post = [(public,'public'),(private,'private')]
code = models.CharField(max_length=10)
name = models.CharField(max_length=300)
price = models.CharField(max_length=40)
position = models.IntegerField(default=1)
status = models.CharField(max_length=10,default=public,choices=status_post)
menu = models.CharField(max_length=100,default=price_all_menu,choices=price_menu)
def __str__(self):
return f"{self.code} -- {self.name} -- {self.price} - [{self.position}] - [{self.status}]"

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

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

Dynamically update fields in django

When I create new sesid in session I need all the courses to add to the sesid in Registration model.
I am creating a result management system using django.
What I want to do is to
create a session (it is done)
then automatically, all the courses from course model will be in the
session model ( I don't need to add individually) and then show a
page that enables to add batch to the added courses.
After submission all the students of the corresponding batch will be
added to the course and thus session and redirect to somewhere to enable user to assign each course to a specific teacher
each of the students have several marks fields to cover by the assigned teacher
the result will be calculated and saved in the database after input from a table (better as an imported excel file)
so far, I have made this:
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
class Course(models.Model):
cid = models.AutoField(primary_key=True)
cnam = models.CharField(max_length=200)
cidn = models.IntegerField()
cred = models.IntegerField()
def __str__(self):
return 'IT-' + str(self.cidn) + ' - ' + self.cnam
class Student(models.Model):
snam = models.CharField(max_length=200)
sid = models.AutoField(primary_key=True)
sroll = models.IntegerField()
sreg = models.IntegerField()
sbtc = models.IntegerField()
sses = models.CharField(max_length=10)
def __str__(self):
return self.snam
class Teacher(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
full_name = models.CharField(max_length=200, null=True)
umob = models.CharField(max_length=20, blank=True, default='')
ulogo = models.ImageField(upload_to='media', blank=True)
def __str__(self):
return self.user.username
def createprofile(selfsender, **kwargs):
if kwargs['created']:
user_profile = Teacher.objects.creeate(user=kwargs['instance'])
class Session(models.Model):
sesid = models.IntegerField(primary_key=True,verbose_name= ('Session'))
def __str__(self):
return str(self.sesid)
def get_absolute_url(selfself):
return reverse('Dashboard:session')
class Registration(models.Model):
session = models.ForeignKey(Session, on_delete=models.CASCADE)
teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
# def __str__(self):
# return str(self.session.sesid) + ' - ' + 'IT-' + self.str(course.cidn) + ' - ' + self.course.cnam + ' - ' + self.str(Teacher.user)
class Result(models.Model):
reg = models.ForeignKey(Registration, on_delete=models.CASCADE)
student = models.ForeignKey(Student, on_delete=models.CASCADE)
ct1 = models.FloatField(null=True, blank=True)
ct2 = models.FloatField(null=True, blank=True)
ct3 = models.FloatField(null=True, blank=True)
asn = models.FloatField(null=True, blank=True)
# avg
atd = models.IntegerField(null=True, blank=True)
#total
def __str__(self):
return str(self.reg.session) + ' - ' + 'IT-' + str(self.reg.course.cidn) + ' - ' + self.student.snam
views.py:
from django.urls import reverse_lazy
from django.views import generic
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView
from django.shortcuts import render, redirect
from django_tables2 import RequestConfig
from .tables import *
from .models import *
from .forms import CustomUserChangeForm
class Login(generic.CreateView):
form_class = CustomUserChangeForm
success_url = reverse_lazy('index')
template_name = 'Dashboard/login.html'
class IndexView(ListView):
template_name = 'Dashboard/index.html'
def get_queryset(self):
return Course.objects.all()
def course(request):
table = CourseTable(Course.objects.all())
RequestConfig(request).configure(table)
return render(request, 'Dashboard/course.html', {'table': table})
def teacher(request):
table = TeacherTable(Teacher.objects.all())
RequestConfig(request).configure(table)
return render(request, 'Dashboard/teacher.html', {'table' : table})
def student(request):
table = StudentTable(Student.objects.all())
RequestConfig(request).configure(table)
return render(request, 'Dashboard/student.html', {'table' : table})
def result(request):
table = ResultTable(Result.objects.all())
RequestConfig(request).configure(table)
return render(request, 'Dashboard/result.html', {'table' : table})
class SessionView(CreateView,ListView):
template_name = 'Dashboard/createSession.html'
model = Session
fields = ['sesid']
def get_queryset(self):
return Session.objects.all()
How can I approach to the dynamic update of database?
Based on the explanation in the comment, something like this should do the trick.
For reusability, you could also move the for course... bit to a method on Session, such as add_courses(self, teacher): ...
class SessionView(CreateView, ListView):
template_name = 'Dashboard/createSession.html'
model = Session
queryset = Session.objects.all()
fields = ['sesid']
def form_valid(self, form): # this will be the creation form
instance = form.save() # save the empty session
for course in Course.objects.all():
Registration.objects.create(
session=instance,
course=course,
teacher=self.request.user.teacher, # (Is this correct?)
)
return HttpResponseRedirect(self.get_success_url())

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.

Django Inline Forms newly added Foreign Key Field but not showing in newly added inline rows

I am quite newbie in Django world. My question is I ve two models shown below. It works quite well with Grapelli and inline-sortables. Only problem is whenever I add a new foreign key for "equipment" or "image type" fields. They don't show up in the drop down menu of newly added inline rows. I went through internet but couldn't find a smilar problem and a solution.
I would appreciate some help with this.
My model is:
from django.db import models
from datetime import datetime
from thumbs import ImageWithThumbsField
from positions.fields import PositionField
class Artist(models.Model):
name = models.CharField(max_length=55)
def __unicode__(self):
return self.name
class ImageType(models.Model):
name = models.CharField(max_length=55)
def __unicode__(self):
return self.name
class Equipment(models.Model):
name = models.CharField(max_length=55)
def __unicode__(self):
return self.name
class Image(models.Model):
name = models.CharField(max_length=255)
image_file = models.ImageField(upload_to = "images/%Y-%m-%d")
Image_Type = models.ForeignKey(ImageType)
upload_date = models.DateTimeField('date_published',default=datetime.now)
artist = models.ForeignKey(Artist)
equipment = models.ForeignKey(Equipment)
order = PositionField(collection='artist')
def __unicode__(self):
return self.name
class Meta:
ordering = ['order']
And My admin.py is:
from gallery.models import Image,ImageType,Artist,Equipment
from django.contrib import admin
class ImageUploadAdmin(admin.ModelAdmin):
fields = ['name','artist','equipment','image_file','Image_Type','upload_date']
list_filter = ['upload_date']
date_hierarchy = 'upload_date'
class ImageInline(admin.TabularInline):
model = Image
list_display = ('name','equipment','image_file','Image_Type','upload_date')
sortable_field_name = "order"
exclude = ('upload_date',)
extra = 0
class ArtistAdmin(admin.ModelAdmin):
inlines = [
ImageInline,
]
admin.site.register(Artist,ArtistAdmin)
admin.site.register(Image, ImageUploadAdmin)
admin.site.register(ImageType)
admin.site.register(Equipment)