Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to register with Django admin approval?
In the system I created with Django, users should not log in without the admin approval after registration. For example, after the user fills in the registration form, user will see the warning waiting for admin approval and cannot login to the system without approval from the admin panel. views.py def signup(request): form_class = SignUpForm if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() # load the profile instance created by the signal user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) user.first_name = form.data['first_name'] user.last_name = form.data['last_name'] user.rank = form.data['rank'] user.comp_name = form.data['comp_name'] login(request, user) return redirect('/') else: form = form_class() return render(request, 'signup.html', {'form': form}) models.py class UserProfile(AbstractUser): ranks = ( ('analyst', 'Analyst'), ... ) comp_name = models.CharField(max_length=200, default="Choose") user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True) username = models.CharField(max_length=500, unique=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) password = models.CharField(max_length=50) email = models.EmailField(max_length=254) rank = models.CharField(max_length=200, choices=ranks) -
Django Project is not hosting in Cpanel
Problem occuring My Django project is not hosting on cpanel. I have created 2 app in my django project(Affiliate, members). app and project file -
Wagtail-bakery and routable pages implementation
I have a simple Wagtail CMS blog. My models are straightforward but include a routable BlogIndexPage page so I can serve different versions of this page, with filters for category (BlogCategory) or tag (BlogPageTag): from django.db import models from wagtail.admin.edit_handlers import FieldPanel from wagtail.contrib.routable_page.models import RoutablePageMixin, route from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.search import index from wagtail.snippets.models import register_snippet from taggit.models import TaggedItemBase from modelcluster.contrib.taggit import ClusterTaggableManager from modelcluster.fields import ParentalKey from wagtailcodeblock.blocks import CodeBlock from .blocks import * class HomePage(Page): def get_context(self, request): context = super().get_context(request) # temporary instead of insta feed@ context['posts'] = BlogPage.objects.live() return context class BlogPageTag(TaggedItemBase): content_object = ParentalKey( 'BlogPage', related_name='tagged_items', on_delete=models.CASCADE ) @register_snippet class BlogCategory(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(unique=True, max_length=80) display_order = models.IntegerField(null=True, blank=True) panels = [ FieldPanel('name'), FieldPanel('slug'), FieldPanel('display_order'), ] def __str__(self): return self.name class Meta: verbose_name = "Category" verbose_name_plural = "Categories" class BlogPage(Page): date = models.DateField("Post date") intro = models.TextField() tags = ClusterTaggableManager(through=BlogPageTag, blank=True) soundcloud_link = models.TextField(blank=True) main_image = models.ForeignKey( 'wagtailimages.Image', on_delete=models.SET_NULL, related_name='+', null=True, blank=True ) category = models.ForeignKey( BlogCategory, on_delete=models.SET_NULL, related_name='+', null=True, blank=True ) body = StreamField( [ ('h1_fluid', H1FluidBlock(),), ('h2_fluid', H2FluidBlock(),), ('paragraph', blocks.RichTextBlock()), ('fluid_paragraph', ParagraphFluidBlock()), ('code', CodeBlock(label='Code')), ('image', ImageSrcset(label='Image w/ srcset')), … -
Django - How to make view only acessible to user
How to make a view only accessible only for active user no, staff or superuser can access it only active user. -
Lost with django-social-auth and custom oauth2 backen
This may not be a very good stackoverflow question because I am so lost I think my question will appear like I have made no effort. I want to get the user's email from Xero, a cloud accounting app which specifically allows for this (https://developer.xero.com/documentation/oauth2/sign-in) When I create a Xero "app" to get the necessary credentials, I need to provide an OAuth 2.0 redirect URI, and I think this is very common or even universal for oauth2 authentication. I can't see an example of how I provide this URL to the configuration of my backend (a subclass of BaseOAuth2). Apart from being a redirect URL, it must also be provided in the AUTHORIZATION_URL. The Xero URL template is https://login.xero.com/identity/connect/authorize?response_type=code&client_id=YOURCLIENTID&redirect_uri=YOURREDIRECTURI&scope=email&state=1234 I have read quite a few tutorials. I can't find any on adding a custom oauth2 backend, but in this tutorial there are examples for GitHub and Twitter: https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html In both cases, the tutorial says to provide a callback URL of the form http://localhost:8000/oauth/complete/twitter/ when defining the app on the authenticator's side. Is this a hard-coded, undocumented default? Or do I need to define it somewhere in my configuration? In the tutorial, I can't see any reference to a callback url … -
Django DRF Unable to implement logic Foreign Key
I am making a rest api in django and is unable to implement a particular feature in my api. I have 3 models in total in my api.Listed below: class ProductInfo(models.Model): title = models.CharField(max_length=15) image = models.TextField() price = models.CharField(max_length=5) def __str__(self): return self.title + '| ' + str(self.id) class OrderItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(ProductInfo, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) proceed = models.BooleanField(default=True) def __str__(self): return self.item.title + ' | ' + self.user.username + ' | ' + str(self.id) class BoughtItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) item = models.ForeignKey(ProductInfo, on_delete=models.CASCADE) quantity = models.IntegerField() def __str__(self): return self.user.username + ' | ' + self.item.title In my model named Bought Item , I want to save multiple item (which is a foreign key) in a single hit.I know how to save one by one with the item id but I want to pass a list in it and also I want the user to be same with also the corresponding quantity of every item in the Bought Item model.I know its quite complicated and so I am unable to do it.I am using it in rest api , so I also need to create a serializer but I … -
How to make make carousel card to to being as tall as the tallest card
I am using the glidejs to make this carousel. I can't figure out how to make the cards have the same height as the tallest one and being responsive at the same time. (See below) I have tried to set the .glide__slides to have height: 35vh and make the card height 100%. This makes the cards have the same height but there is a big white gap at the bottom as shown below when on a smaller width screen Here is part of my code <div class="container-fluid bg-light"> <div class="container"> <div class="row"> <div class="col-lg-2 my-auto"> <h1>Latest Products 2021</h1> </div> <div class="col-lg-10 mt-3"> <div class="glide"> <div class="glide__track" data-glide-el="track"> <ul class="glide__slides"> {% for product in latest_products %} <li class="glide__slide"> <div class="card px-2 h-100"> <a href="{{ product.get_absolute_url }}"> <img src="{{ product.image.url }}" class="carousel-image" alt="{{ product.name }}"> </a> <div class="card-body"> <a href="{{ product.get_absolute_url }}" class="text-decoration-none"> <h5 class="card-title">{{ product.name|truncatechars:30 }}</h5> </a> <h6 class="card-subtitle mb-2 text-muted">RM {{ product.price }}</h6> <button class="btn btn-sm btn-success">Add to Cart</button> </div> </div> </li> {% endfor %} </div> </div> <div class="glide__arrows" data-glide-el="controls"> <button class="glide__arrow glide__arrow--left text-dark" data-glide-dir="<"><i class="fas fa-arrow-left"></i></button> <button class="glide__arrow glide__arrow--right text-dark" data-glide-dir=">"><i class="fas fa-arrow-right"></i></button> </div> </div> </div> </div> </div> </div> -
Django admin How to solve the problem that all parts are not visible?
I created a system with Django. I create an abstract user model with some custom fields. My form is working but in the admin page I cannot see my custom models. models.py class UserProfile(AbstractUser): ranks = ( ... ('cfo', 'Chief Financial Officier'), ) comp_name = models.CharField(max_length=200, default="Choose") user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True) username = models.CharField(max_length=500, unique=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) password = models.CharField(max_length=50) email = models.EmailField(max_length=254) rank = models.CharField(max_length=200, choices=ranks) def __str__(self): return self.username class CompanyProfile(models.Model): ... admin.py admin.site.register(CompanyProfile) class CustomUser(UserAdmin): add_form = SignUpForm model = UserProfile form = SignUpChangeForm list_display = ('username', 'first_name', 'email', 'last_name', 'rank', 'comp_name') fieldsets = ( (None, {'fields': ('email', 'password')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2', 'rank', 'comp_name')} ), ) search_fields = 'email' admin.site.register(UserProfile, UserAdmin) admin view As you can see in admin view there is no ranks and company name field. How can I solve it? -
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'app1.myUser' that has not been installed
In my Django project, I have an app1 named app. I create a model named myUser in my app1 app's model.py like this: from django.contrib.auth.models import User, AbstractUser class myUser(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Student(models.Model): user = models.OneToOneField(myUser, on_delete=models.CASCADE, primary_key=True) roll = models.IntegerField(blank=True) I also set AUTH_USER_MODEL in settings.py like this: AUTH_USER_MODEL = 'app1.myUser' Here, admin.site.register(myUser) is also done in admin.py and app1 is also installed in INSTALLED_APPS list in settings.py. Now I have face following error in my console when I use migrate or runserver: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "G:\Python\lib\site-packages\django\apps\config.py", line 178, in get_model return self.models[model_name.lower()] KeyError: 'myuser' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "G:\Python\lib\site-packages\django\contrib\auth\__init__.py", line 156, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "G:\Python\lib\site-packages\django\apps\registry.py", line 210, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "G:\Python\lib\site-packages\django\apps\config.py", line 180, in get_model raise LookupError( LookupError: App 'app1' doesn't have a 'myUser' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "G:\Python\lib\threading.py", line 932, in _bootstrap_inner self.run() self._target(*self._args, **self._kwargs) File "G:\Python\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "G:\Python\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() … -
drf use different serializer show 'You cannot call `.save()` after accessing `serializer.data`
i want post question info first , and post options list with question id at "opt_ser.save()" it show "'You cannot call .save() after accessing serializer.data.If you need to access data before committing to the database then inspect \'serializer.validated_data\' instead. '" class QuestionAddApiView(APIView): def post(self, request, *args, **kwargs): option_list = request.data.pop('option_list') question_serializer = QuestionReadAndWriteSerializer(data=request.data) try: if question_serializer.is_valid(): question_serializer.save() question = question_serializer.instance opt_response = [] for option_item in option_list: option_item['question'] = question opt_ser = OptionSerializer(data=option_item) if opt_ser.is_valid(): opt_ser.save() opt_response.append(opt_ser.data) question['option_list'] = opt_response return BResponse(question, status=status.HTTP_200_OK) except Exception as e: return BResponse(question_serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
multiple joins on django queryset
For the below sample schema # schema sameple class A(models.Model): n = models.ForeignKey(N, on_delete=models.CASCADE) d = models.ForeignKey(D, on_delete=models.PROTECT) class N(models.Model): id = models.AutoField(primary_key=True, editable=False) d = models.ForeignKey(D, on_delete=models.PROTECT) class D(models.Model): dsid = models.CharField(max_length=255, primary_key=True) class P(models.Model): id = models.AutoField(primary_key=True, editable=False) name = models.CharField(max_length=255) n = models.ForeignKey(N, on_delete=models.CASCADE) # raw query for the result I want # SELECT * # FROM P, N, A # WHERE (P.n_id = N.id # AND A.n_id = N.id # AND A.d_id = \'MY_DSID\' # AND P.name = \'MY_NAME\') What am I trying to achieve? Well, I’m trying to find a way somehow be able to write a single queryset which does the same as what the above raw query does. So far I was able to do it by writing two queryset, and use the result from one queryset and then using that queryset I wrote the second one, to get the final DB records. However that’s 2 hits to the DB, and I want to optimize it by just doing everything in one DB hit. What will be the queryset for this kinda raw query ? or is there a better way to do it ? Above code is here https://dpaste.org/DZg2 -
Django admin how to solve abstract user problem? [duplicate]
I created a system with Django. I create an abstract user model with some custom fields. My form is working but in the admin page I cannot see my custom models. models.py class UserProfile(AbstractUser): ranks = ( ... ('cfo', 'Chief Financial Officier'), ) comp_name = models.CharField(max_length=200, default="Choose") user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True) username = models.CharField(max_length=500, unique=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) password = models.CharField(max_length=50) email = models.EmailField(max_length=254) rank = models.CharField(max_length=200, choices=ranks) def __str__(self): return self.username class CompanyProfile(models.Model): ... admin.py admin.site.register(CompanyProfile) class CustomUser(UserAdmin): add_form = SignUpForm model = UserProfile form = SignUpChangeForm list_display = ['username', 'first_name', 'email', 'last_name', 'rank', 'comp_name'] admin.site.register(UserProfile, UserAdmin) As you can see in admin view there is no ranks and company name field. How can I solve it? -
in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (name) specified for User
[i tryin to create a registration form and while trying to make migration I got this issue any clue what causing error like this][1] -
Django ModelFormset Forms Returning Empty Data
I have been trying to solve this for weeks to no avail, and would really appreciate some help. Background I'm creating a Django app which takes input of a user's educational experience, and wanted to provide users with the ability to add new experiences via an "Add More" button (i.e if they had an undergrad and masters). I'm doing this using ModelFormsets and Jquery, following this answer: Dynamically adding a form to a Django formset with Ajax. Problem When accessing the cleaned_data of the formset, only the first initial form has values in its cleaned_data, the additional generated forms return an empty dictionary with no cleaned data in them. Views.py EducationFormset = modelformset_factory(Education, form=EducationForm, fields=('institution', 'degree', 'major', 'major_start_date', 'major_end_date', 'major_description', 'gpa',)) if request.method == 'POST': formset = EducationFormset(request.POST, request.Files) if formset.is_valid(): formset.save() for form in formset.forms: print(form.cleaned_data) else: print(formset.errors) else: formset = EducationFormset(queryset=Education.objects.none()) context = { 'user_form': user_form, 'education_form': education_form, 'experience_form': experience_form, 'formset':formset, } return render(request, 'create.html', context) HTML {{ formset.management_form }} <div id="form_set"> <div class="form-group"> {% for form in formset.forms %} {{form.errors}} <table class="no_error"> {{form.as_table}} </table> {% endfor %} </div> </div> <div id="empty_form" style="display:none"> <table class="no_error"> {{formset.empty_form.as_table}} </table> </div> <script> $('#add_more').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) … -
Django - Grouping data and showing the choices's name in template
I am trying to create a pie chart (chart.js). My goal is grouping titles and displaying how many people work by title in piechart. Models.py class Personel(models.Model): name = models.CharField(max_length=30) surName = models.CharField(max_length=20) titles= models.IntegerField(choices=((1,"Researcher"),(2,"Technician"),(3, "Support Personel")),default=1) def __str__(self): return f"{self.name},{self.surName}" class Meta: db_table = "personel" verbose_name_plural = "Ar-Ge Personeller" Views.py def index(request): personel_titles = Personel.objects.values('titles').annotate(Count('titles')) context = { "personel_titles" : personel_titles, } return render(request, 'core/index.html',context) >>> print(personel_titles) >>> {'titles': 1, 'titles__count': 10} {'titles': 2, 'titles__count': 11} {'titles': 3, 'titles__count': 3}> It is okay for me and all I need is in here. But I couldn't figure out how can I display title's name in my template(also in chart label) Template {% for title in personel_titles %}<p>{{ title.get_titles_display }}</p>{% endfor %} What am I missing? How can I return the choice's name in values? -
django rest framework apis using legacy db without creating django default tables
I am going to develop django rest framework apis using postgres legacy database in which apart from the existing tables no other default django tables should be created. I would like to know without creating any django default tables or doing migrations, can i able to access records from tables using ORM? Can i able to access admin page without creating django auth table (i.e superuser)? If no for both questions, only way to connect to db is using any db adapter like psycopg2? -
Convert Django model form based system into a raw HTML based form system for signup
I have a class-based view system for signup in Django which uses Django's model form. but I need to render my custom build HTML form in place of that. My models.py: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) quizzes = models.ManyToManyField(Quiz, through='TakenQuiz') interests = models.ManyToManyField(Subject, related_name='interested_students') And views.py: class StudentSignUpView(CreateView): model = User form_class = StudentSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'student' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('students:quiz_list') This system has a form.py also which made the hard work and render the Django model form. Now I need to replace these types of Django's default model form with my custom build HTML form something like this link. How can I use the following types of simple system which will receive data from views.py and will create a user? if request.method == 'POST': this_username = request.POST['username'] this_password = request.POST['password'] this_otherKindofStuff = request.POST['otherKindofStuff'] Student_signup = TableA.objects.create(name=this_name, password=this_password, otherKindofStuff=this_otherKindofStuff) Student_signup.save() -
Page not found at /
I'm new to django and according to tutorial i've created the project: views.py code: from django.http import HttpResponse def home(request): return HttpResponse("This is the home page") def about(request): data = "This is our about page" return HttpResponse(data) urls.py code: from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('home/', views.home), path('about/', views.about), ] Error i get while running the app: what am i missing? -
Foreign key default value in django model
I'm starting an app with django; i love it so far but i've trouble initializing my database. To sum up, i need a table user and a table role; a user has a FK to role. Upon creation a user must have this role set explicitly or defaulting to a default role 'Regular user'. I could create the model without the database, then manually create the role, then add the default and migrate; but that does not look nice; I tried adding to the database in-between the two models definition but obviously it does not work as the tables are not created during the makemigration command. Is there any way to achieve what I want ? Here is my current models if it helps; feel free to report any non-sense in this; i'm learning. Thx ;) from django.db import models class Role(models.Model): name = models.CharField(max_length=100) identifier = models.CharField(max_length=20) ts_create = models.DateTimeField(auto_now_add=True) ts_update = models.DateTimeField(auto_now=True, default=None, null=True) def __str__(self): return self.name userRole = Role.objects.get_or_create(name="Regular user", identifier="USER") adminRole = Role.objects.get_or_create(name="Administrator", identifier="ADMIN") ownerRole = Role.objects.get_or_create(name="Owner", identifier="OWNER") class User(models.Model): username = models.CharField(max_length=100, unique=True) user_type = models.ForeignKey(Role, related_name="user_type", on_delete=models.PROTECT, default=userRole) roles = models.ManyToManyField(Role, related_name="roles", db_table="core_roles_assignations") ts_create = models.DateTimeField(auto_now_add=True) ts_update = models.DateTimeField(auto_now=True, default=None, null=True) def __str__(self): … -
Django: Booking() got an unexpected keyword argument 'chek_in'
I'm creating a booking appin django and I'm a bit new on this, when I try to book a room I keep getting the following error: Booking( ) got an unexpected keyword argument 'chek_in' I'm following the code on the following git address, but I keep making the same mistake no matter how many times I keep writing the code: https://github.com/Darshan4114/Django_HMS I appreciate any help you can bring. Below my codes: Availability.py import datetime from hotel.models import Room, Booking def check_availability(room, check_in, check_out): avail_list = [] booking_list = Booking.objects.filter(room=room) for booking in booking_list: if check_in > booking.check_out or booking.check_out < check_in: avail_list.append(True) else: avail_list.append(False) return all(avail_list) Views from django.shortcuts import render, HttpResponse from django.views.generic import ListView, FormView, View from .models import Room, Booking from .forms import AvailabilityForm from hotel.booking_functions.availability import check_availability class RoomListView(ListView): model=Room class BookingList(ListView): model=Booking class RoomDetailView(View): def get(self, request, *args, **kwargs): category = self.kwargs.get('category', None) form = AvailabilityForm() room_list = Room.objects.filter(category=category) if len(room_list)>0: room = room_list[0] room_category = dict(room.ROOM_CATEGORIES).get(room.category, None) context = { 'room_category': room_category, 'form': form, } return render(request, 'room_detail_view.html', context) else: return HttpResponse ('Category does not exist') def post(self, request, *args, **kwargs): category = self.kwargs.get('category', None) room_list = Room.objects.filter(category=category) form = AvailabilityForm(request.POST) if form.is_valid(): data … -
Django import-export Sheet Name
I'm using the third party library Django-import-export for importing/exporting data from template. When i try to export data from view , i want to define Sheet name myself (in xlsx format default is Tablib Dataset). When i do in dataset dataset = Dataset(title="cogs") i can define title myself. def export(request): modelResource = ModelResource() model = Model.objects.filter(boolField =True ) dataset = modelResource.export(model) response = HttpResponse(dataset.xlsx, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="model.xlsx"' return response When this function works , SheetName is Tablib Dataset , but if i export the file in csv , sheetname is same as filename. Is there any way that i can define sheetname myself ? -
Django Image Upload working but not General File
I am facing a situation where I am able to upload Images, but not general files. I am using javascript to track the progress, which says file upload is successful, but file is not there in the media folder. When I do that for images, it works. Basically, image upload was working, and I tried to copy the same thing and do it for general file upload. Here is the code below. Models class Upload(models.Model): # image upload model image = models.ImageField(upload_to='images') def __str__(self): return str(self.pk) class FileUpload(models.Model): # file upload model video = models.FileField(upload_to='fileuploads/') def __str__(self): return str(self.pk) Forms: class UploadForm(forms.ModelForm): class Meta: model = Upload fields = ('image',) class FileUploadForm(forms.ModelForm): class Meta: model = FileUpload fields = ('video',) Views: def home_view(request): form = UploadForm(request.POST or None, request.FILES or None) if request.is_ajax(): if form.is_valid(): form.save() return JsonResponse({'message': 'hell yeah'}) context = { 'form': form, } return render(request, 'uploads/main.html', context) def file_view(request): form = FileUploadForm(request.POST or None, request.FILES or None) if request.is_ajax(): if form.is_valid(): form.save() return JsonResponse({'message': 'hell yeah'}) context = { 'form': form, } return render(request, 'uploads/main1.html', context) The HTML template for Image Upload {% extends "uploads/base.html" %} {% block content %} <div id="alert-box"></div> <div id="image-box"></div> <br> <form action="" … -
Django Server Side Implementation. Database per client vs a single database
I am curious on how some of more seasoned backend devs would do this. I am writing an app and I have 2 options. Have it multi tenants vs Single For example, Say I am writing a recipe app, there are ingredients and there recipes, and restaurants. Each Restaurant can have recipes, Each recipe can have ingredients and other recipes, So it can be nested. Now with every request beside authentication I need to check if a recipe or ingredient is owned by the right restaurant. So this gets complicated as one can imagine. I have to write validations. Also since technically one should only do semantic validations in serializer do I have to do these validations in my modelView. I literally have to check if my nested json( since there is recipes in recipes) is valid via my serializer (serialier does this nicely with out an hassle) but then I have to parse the json and read each ID of ingredient and/or recipe id and check if it belongs to the right restaurant. There is also another issue. Recipe A can have Recipe B which can Have recipe A, but I am saving that for another post. If i … -
Django Group By using annotate
i have there 2 models class Car(TimeStampedModel): name = models.CharField(_('Car Name'), max_length=50) manager = models.ForeignKey( 'cars.Manager', verbose_name=_('Car Manager'), related_name='cars', on_delete=models.CASCADE ) def __str__(self): return self.name class Manager(models.Model): name = models.CharField(_('Name'), max_length=25) class Meta: verbose_name = _('Car Manager') verbose_name_plural = _('Car Managers') def __str__(self): return self.name and then on the serializer, i try to get number_of_managed_cars by each manager using this way def get(self, request): cars_managers = Manager.objects.all().annotate(number_of_managed_cars=Count('cars')) serializer = CarManagerSerializer(cars_managers, many=True) serializer_data = serializer.data return Response(serializer_data, status=status.HTTP_200_OK) then i try to hit the endpoint: { { "id": 1, "name": "John Doe", } } there's no number_of_managed_cars on the result. where did i miss ? -
Django - KeyError at /auctions/create 'category.' (New to Django, any help is appreciated!)
I am new to Django and creating a dropdown menu so that users can choose a category from the dropdown. This category will be saved on an entry on the website, when a user creates a new entry. I migrated the model, but I'm getting: KeyError at /auctions/create 'category.' Any help is really appreciated. Views.py (Code for creating the dropdown menu for categories) models.py forms.py Here is the create part in views.py for creating a new entry. 'form' for CreateForm() is the model form for creating the entry. 'form1' for CategoryForm() is the model form for the category drop down list. The create function was working completely fine, until I added in the parts for the categories and category form. urls.py for applicable functions (I have tried many variations for the category one but I'm still having trouble figuring out what it should be, I have tried str and int.) Sorry I'm a beginner but any help would be great! path("auctions/create", views.create, name="create"), path("listings/<int:id>", views.listingpage, name="listingpage"), path("cat/<int:id>", views.cat, name="cat"),