Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to serialize multi object in django?
I used ajax to fetch data from database. How can i fetch objects and send them? views.py def fetchdata(request): if request.method == 'GET': val1 = request.GET['param1'] val2 = request.GET['param2'] obj = Reserve.objects.filter(~Q(con__title = val1 ), dt__title=val2 ).values('dt__title','con__title') ser_instance = serializers.serialize('json', [obj,]) return JsonResponse({"instance": ser_instance}, status=200) else: return HttpResponse("Request method is not a GET") con and dt are foregn keys fields. -
Django nested viesets on router
In my urls.py file in some app i have the following code: from rest_framework import routers from .viewsets import (JournalViewSet, StatisticViewSet, FuelLogViewSet, MoveLogViewSet, RestLogViewSet, WinLogViewSet, GreatfulLogViewSet) router = routers.DefaultRouter() router.register(r'journal', JournalViewSet) router.register(r'journal/statistic', StatisticViewSet) router.register(r'journal/fuel', FuelLogViewSet) router.register(r'journal/move', MoveLogViewSet) router.register(r'journal/rest', RestLogViewSet) router.register(r'journal/win', WinLogViewSet) router.register(r'journal/greatful', GreatfulLogViewSet) urlpatterns = router.urls All vievsets above are not something specific, and use only serializer_class and queryset. Swagger generate correct scheme, but DRF says, that i have no POST method allowed (in viesets i actually have) and when i try to open url like 127.0.0.1:8000/journal/win, drf return scheme for journal. When registers were not nested like router.register(r'move', MoveLogViewSet), I get all correct. I understand, that DRF maybe don't provide nested routs like I have. What should I do? -
How to get my messages to show on Django for a registration form?
I am creating a registration form using the Django framework and I want to display some error messages to the user if they enter the wrong confirm password, or an email already taken etc. I have written the code and it seems to be working, but I can't seem to get the messages to show on screen upon redirecting to back to registration page if there is an error in the form. I have imported messages on the views.py page (from django.contrib import messages) and I think my setting.py is all configured correct: setting.py Here is my views.py code: def register(request): if request.method == "GET": register_form = RegisterForm() return render(request, "main/register.html", { 'form': register_form }) else: register_form = RegisterForm(request.POST) if register_form.is_valid(): first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] confirm_password = request.POST['confirm_password'] if password == confirm_password: if User.objects.filter(email=email).exists(): messages.info(request, 'Email or user name Already taking') return redirect('register') elif User.objects.filter(username=username).exists(): messages.info(request, 'username is taken') return redirect('register') else: User.objects.get_or_create(username=username, first_name=first_name, last_name=last_name, email=email, password=password) return redirect('main/login.html') else: messages.error(request, 'Password Not Match') return redirect('register') #return redirect ('/') else: return render(request, 'main/login.html') and this is my register.html form: <form action="{% url 'register' %}" method="POST"> {% csrf_token %} <fieldset> … -
Django multiupload error: 'list' object has no attribute 'name'
I'm trying to use multiupload in django form for upload several images at once. I'm using django ModelForm but when i'm calling form.is_valid() in function-base view or using generic.FormView, i'm getting 'list' object has no attribute 'name' error. in generic.FormView neither of form_valid and form_invalid methods aren't called. although when I use request.POST.get(some_data) it works without any errors but I want to use generic.FormView for some validations. I think the validation of the form makes the error happen. so what should I do? here is my code. models.py class Post(models.Model): post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="posts") text = models.TextField(max_length=1000) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) ... class Image(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="images") image = models.ImageField(upload_to="images/posts/") forms.py class PostForm(forms.ModelForm): images = MultiImageField(min_num=1, max_num=3) class Meta: model = models.Post fields = ("text", "images") views.py class CreatePostView(LoginRequiredMixin, generic.FormView): template_name = "posts/post_create.html" form_class = forms.PostForm def get_success_url(self): return redirect("profile", slug=self.request.kwargs.slug) def form_valid(self, form): ... # some codes ... return super(CreatePostView, self).form_valid(form) -
CSRF cookie not set in react native axios
I am trying to do my first app in react native and django rest framework. I created a simple server based on tutorial with default login page. I am trying to make a POST to this login page, but I am getting error: Forbidden (CSRF cookie not set.): /api-auth/login/ My POST looks like: const sendLoginCredencials = (data) => { axios.defaults.headers.common['X-CSRF-TOKEN'] = data.csrf_token; axios.post('http://127.0.0.1:8000/api-auth/login/', { username: 'username', password: 'passwd', }, ) .then((response) => { console.log(response) }) .catch(error => { console.error('error', error); }); } Settings.py has this lines: from corsheaders.defaults import default_headers CORS_ALLOW_HEADERS = list(default_headers) + [ 'X-CSRF-TOKEN', ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_NAME = "csrftoken" CSRF_HEADER_NAME = 'X-CSRF-TOKEN' I have tested many answers and combinations. None of them worked and I admit that I feel confused. Could anyone tell me how to set the header correctly and what excatly I should set in settings.py ? Best regards! -
Sending AJAX request Django to previous pages
So i have a project with Django to detect some deepfake video. But i have some trouble. I have to send some Background process (inside predict function) into previous pages (inside index function). Maybe it would be like this [https://i.stack.imgur.com/nYWWV.png] That "TEMPAT PROSESSING" is the place for the background process. and the background process i mean is kinda like this: [https://i.stack.imgur.com/EHGJJ.png] And somebody tell me that it needs to used AJAX.But i never use it before. Can anyone tell me tell me how to do that? Thank you. Below is the code for detection process that i need to send # def predict_page(request) Start: Video Splitting print("\n<=== | Started Videos Splitting | ===>") split_start = time.time() cap = cv2.VideoCapture(video_file) frames = [] while(cap.isOpened()): ret, frame = cap.read() if ret==True: frames.append(frame) if cv2.waitKey(1) & 0xFF == ord('q'): break else: break cap.release() for i in range(1, sequence_length+1): frame = frames[i] split_time = ((time.time() - split_start)) print("---- %.2f seconds ----" % split_time) print("<=== | Videos Splitting Done | ===>") # Start: Face Cropping print("\n<=== | Started Face Cropping | ===>") crop_start = time.time() faces_cropped_images = [] padding = 50 faces_found = 0 for i in range(1, sequence_length+1): frame = frames[i] face_locations = face_recognition.face_locations(frame) … -
Django sitemap.xml for millions of producs
We have a big amount of products. About 50 million items What is the best way to generate sitemaps in Django? At the moment we generate them the following way: sitemaps.py class BookSitemap1(Sitemap): protocol = 'https' changefreq = 'weekly' priority = 0.9 def items(self): return Book.objects.all().order_by('id')[0:25000] class BookSitemap2(Sitemap): protocol = 'https' changefreq = 'weekly' priority = 0.9 def items(self): return Book.objects.all().order_by('id')[25000:50000] ... Urls.py sitemap_books_1 = {'books1': BookSitemap1} sitemap_books_2 = {'books2': BookSitemap2} ... path('books-1.xml', sitemap, {'sitemaps': sitemap_books_1}, name='django.contrib.sitemaps.views.sitemap'), path('books-2.xml', sitemap, {'sitemaps': sitemap_books_2}, name='django.contrib.sitemaps.views.sitemap'), ... And so on for all our 50 million products. But this is 2000 sitemaps... We can put 50000 ulrs in each sitemap. But this will be 1000 sitemaps again Is there any other solution to generate sitemaps in Django? Because this solutions is very inconvenient as for me -
Cannot display DataTable in django-plotly-dash
I am trying to diaplay a DataTable in django-plotly-dash and it is not appearing. other types of components like dropdowns and graphs are appearing and working fine. This is my app.py file import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import plotly.graph_objs as go from django_plotly_dash import DjangoDash import pandas as pd import dash_table df = pd.read_csv('home/dash_apps/finished_apps/app3/data/50000 Sales Records.csv') print(df.columns) app = DjangoDash('SimpleExample3') app.layout = html.Div([ html.H1('BLABLABLA'), dcc.Dropdown( id='dropdown_rows', options=[ {'label': i, 'value': i} for i in list(df.columns) ], multi=True ), dcc.Dropdown( id='dropdokkwn_rows', options=[ {'label': i, 'value': i} for i in list(df.columns) ], multi=True ), dash_table.DataTable( id='table_rows', columns=["Rows"], data=[{"Rows": 89}, {"Rows": 88}] ) ]) This is my settings.py file """ Django settings for project8 project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-y@k8s1r#v%jddkv$qd2ctzd)s6+i_dm$9waec%^4y&cp9$b%d3' # SECURITY WARNING: don't run with debug turned … -
How to assign permissions to custom roles in custom User Model in Django?
I have defined a custom User Model that has 2 new roles beside superuser, staff and active, viz. candidate and voter. I want to assign permissions to these roles so that when I create the user with one of these 'True', I get the role-specific permissions assigned to the user automatically. My User model is below class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=254, null=True, blank=True) email = models.EmailField(max_length=254, unique=True) first_name = models.CharField(max_length=254, null=True, blank=True) last_name = models.CharField(max_length=254, null=True, blank=True) pbc_id = models.CharField(max_length=254, null=True, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_candidate = models.BooleanField(default=False) is_voter = models.BooleanField(default=False) votes = models.IntegerField(default=0) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) My UserManager class is below: class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, is_candidate, is_voter, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( username=email, email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, is_candidate=is_candidate, is_voter=is_voter, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) user.pbc_id = "PBC-" + str(user.pk) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): user = self._create_user(email, password, False, False, False, False, **extra_fields) user.pbc_id = "PBC-" + … -
how to do arithmetic operations in django template
here I have two models Zone and DailyTask from that I made a template that looks like the below image and now I want to find the sum of a used task, unused tasks, and the total task of each time slot thanks in advance model Zone class Zone(models.Model): name = models.CharField(max_length=200) coordinates = models.TextField(null=True, blank=True) model DailyTask class DailyTask(models.Model): date = models.DateField() zone = models.ForeignKey(Zone, on_delete=models.SET_NULL, null=True) slot = models.ForeignKey(GeneralTimeSlot,related_name='daily_task', on_delete=models.CASCADE) total_tasks = models.IntegerField(default=0) used_tasks = models.IntegerField(default=0) unused_tasks = models.IntegerField(default=0) available_driver_slots = models.ManyToManyField(DriverTimeSlot) and current output image in the last three-row, I want the sum above columns ?????? its view is this class TimeSlotReportView(AdminOnlyMixin, generic.DetailView): template_name = 'reports/time_slot_report.html' def get(self, request, *args, **kwargs): zones = Zone.objects.all() # if request.is_ajax(): # # date_val = request.GET.get('date_val') # print(date_val) # daily_task = DailyTask.objects.filter(date=date_val) # html = render_to_string('tasks-zones/task-table-filter.html', {'daily_tasks': daily_task}, request) # return JsonResponse({'html': html}) # no_of_drivers = Driver.objects.all().count() today = datetime.date.today() daily_task = DailyTask.objects.filter(date="2022-06-04") used_tasks = DailyTask.objects.filter(date="2021-06-04").aggregate(Sum('used_tasks'))['used_tasks__sum'] print(used_tasks) unused_tasks = DailyTask.objects.filter(date="2021-06-04").aggregate(Sum('unused_tasks'))['unused_tasks__sum'] print(unused_tasks) # for zone in zones: # daily_tasks = DailyTask.objects.filter(zone=zone, date__gte=today) # for daily_task in daily_tasks: # dr_slots = DriverTimeSlot.objects.filter(driver__zone=daily_task.zone, # start_time=daily_task.slot.start_time) # daily_task.total_tasks = dr_slots.count() # daily_task.available_driver_slots.set(dr_slots) # daily_task.save() return render(request, self.template_name, {'zones': zones, 'daily_tasks': daily_task, 'total-used': used_tasks, 'total-unused': unused_tasks}) -
Django csrf for react
I have a Django backend api app as well as a frontend in React. I want to get csrf from backend to frontend (which I successfully did as per below). However, when I set the csrf token to the header on requests I keep getting that the CSRF token was invalid for various requests. Is there something else I'm supposed to do? I'm migrating the application from a Django view to React. It seems what im trying to do is possible but not working for me based on blogs and other SO posts. from django.middleware.csrf import get_token @require_http_methods(["GET"]) def csrf(request): return JsonResponse({'csrfToken': get_token(request)}) -
django.db.utils.IntegrityError: NOT NULL constraint failed: bankapp_userregistermodel.date_of_birth i m getting this error when i create the superuser
please help me how to solve this\ models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import BaseUserManager, AbstractBaseUser from django.contrib.auth.models import PermissionsMixin class MyuserManager(BaseUserManager): def create_user(self, mobile_number, password=None): if not mobile_number: raise ValueError("user must have an mobile number") user = self.model(mobile_number = mobile_number) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, mobile_number, password=None): user = self.create_user(mobile_number, password=password) user.is_admin = True user.save(using=self._db) return user class UserRegisterModel(AbstractBaseUser, PermissionsMixin): mobile_number = models.IntegerField(verbose_name="Mobile Number", unique=True) bank_ac = models.CharField(max_length=64) first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=64) user_name = models.CharField(max_length=64) email = models.EmailField() date_of_birth = models.DateField(null=False) address = models.CharField(max_length=160) pin_code = models.IntegerField() is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) is_admin = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) objects = MyuserManager() USERNAME_FIELD = "mobile_number" REQUIRED_FIELDS = [] def __str__(self): return self.mobile_number def has_perm(self, perm, obj=None): return True def has_module_perm(self, app_label): return True @property def is_superuser(self): return self.is_admin admin.py from django.contrib import admin from bankapp.models import UserRegisterModel from django.contrib.auth.admin import UserAdmin as BaseUserAdmin class UserAdmin(BaseUserAdmin): list_display = ['bank_ac','first_name','last_name','user_name','mobile_number','email','password','date_of_birth','address','pin_code'] list_filter = ['bank_ac'] search_fields = ['mobile_number'] ordering = ['mobile_number'] filter_horizontal = [] fieldsets = [] add_fieldssets = [ [None, { 'classes' : ['wide',], 'fields' : ['mobile_number','email','password'], }], ] admin.site.register(UserRegisterModel, UserAdmin) forms.py from django import forms from .models import UserRegisterModel import datetime from django.core.exceptions … -
does performing a `get` on a queryset evaluates the whole queryset or just one element of queryset?
pseudocode: class TestModel(models.Model): a = models.CharField() b = models.CharField() qs = Model.objects.filter(a="something") # returns qs containing 5 objects obj = qs.get(b='something_else') # evaluates the queryset and hits the db obj2 = qs.get(b='something_else_2') # evaluates again? hits db again? Now while assigning to obj2, will it hit db again? or even will it db while assigning to obj? -
Django - Adding comments on a post without redirecting
Blessings, Whenever I try to add a comment on a post it redirects me to the corresponding HTML page which in turn lets me comment. What I am trying to achieve here is the ability to comment on the post page without needing to redirect.. views.py # Post page class MovieDetail(DetailView): model = Movie def render_to_response(self, *args, **kwargs): self.object.refresh_from_db() self.object.views_count += 1 self.object.save() return super().render_to_response(*args, **kwargs) def get_context_data(self, **kwargs): context = super(MovieDetail, self).get_context_data(**kwargs) context['links'] = MovieLink.objects.filter(movie=self.get_object()) context['related_movies'] = Movie.objects.filter(category=self.get_object().category) return context @login_required(login_url='/accounts/login/') def comment_create(request, slug): movie = Movie.objects.get(slug=slug) if request.method == 'POST': form = forms.CommentForm(request.POST, request.FILES) if form.is_valid: comment = form.save(commit=False) comment.post = movie comment.author = request.user form.save() return redirect('movies:movie_detail', slug=slug) else: form = forms.CommentForm() return render(request, 'movie/add_comment.html', {'form': form}) forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'body') models.py class Comment(models.Model): post = models.ForeignKey(Movie, on_delete=models.CASCADE, related_name='comments') name = models.ForeignKey(User, default=None, on_delete=models.CASCADE) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) movie_detail.html <div id="respond"> {% if not movie.comments.all %} <p style="color: white">No Comments Added yet...</p> {% else %} {% for comment in movie.comments.all %} <section class="reply" style="padding: 10px; color: white;"> <h3><strong>{{ comment.name }}</strong></h3> <p>{{ comment.body | linebreaks … -
How to update only specific columns in database from Django admin panel?
I have a table suppose named "temp". It has 2 columns "a" and "b". Both column have 50 rows of data. Now I added another column "c" and I need that column to get filled with 50 rows of data. I have a excel file that contains the data for column "c". Now my question is how can I do this? How can I just update the values of column "c"? I know I can just update a file using the Django admin panel but it will update all the columns. I don't want that. Is there a way to use default Django import export functionality in the admin page and make only a certain column get updated? Also I am using mysql for database. I am new to Django. Kindly help me out. -
User.last_login not populating as expected in Django test
Why is user.last_login None in the following test: from django.test import TestCase, Client class TestModels(TestCase): @classmethod def setUpTestData(self): self.user = User.objects.create( username="testUser", password="testPassword" ) self.auth_client = Client() self.auth_client.login(username="testUser", password="testPassword") def test_user_last_login(self): user = User.objects.get(id=self.user.id) # pull the latest data print(user.last_login). # <-- this is None, why?! self.assertIsNotNone(user.last_login) I am clearly logging in, then querying the user from the database to refresh the data. -
Order by similarity keyword in Django
I want to sort by similarity with keyword in first item, how can i do that with Q object in Django? This is my views code. And this is display in my web, I want it should be the second item at the top that matches the keyword Maybe someone can help, thank you -
Django application returning 401 even if my jwt token is valid
I have deployed my django application using gunicorn and nginx. I have used this link as my reference for deployment. Deployment went perfectly fine, the status of both gunicorn and nginx are active. The problem arises when I try to access the resource. I am using JWT authentication. When I send the login request my app returns me with an access token but when I try to access any other endpoint using the access token it returns me with a 401 error even when my token is valid. This happens for 2-3 requests but when I request for the 4th time it gives me response data with 200 ok and this process repeats. I never faced this problem during my development, I am not able to figure out where the problem is, the gunicorn access logs are shown below. My configuration is exactly the same as provided in reference link above Gunicorn logs -
Django Aggregation - output field not working as expected
Book.objects.aggregate(price_diff=Max('price', output_field=FloatField()) - Avg('price')) Error : Expression contains mixed types: FloatField, De cimalField. You must set output_field. Even though output filed used -
How to make separate form radio buttons independent
To specify, I have a for loop running over each employee in an employee_list. I'm printing a form I have in forms.py for each employee, which just consists of a single radio button with the choices "Absent" or "Present". However, in the webpage, if I select any option for Employee 1, then click on any of the options for Employee 2, it deselects the one I selected for Employee 1, as for some reason it renders it as one radio choice? I want to be able to select separate options for each employee CODE mark_attendance.html {% extends 'base.html' %} {% block content %} <form action="{% url 'confirm' %}" method="post"> {% csrf_token %} <div class="card mb-3"> <div class="card-header"> <i class="fas fa-table"></i> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Employee name</th> <th></th> </tr> </thead> <tbody> {% for employee in employee_list %} {{<tr> <td>{{employee}}</td> <td> {{ form }} </td> </tr>}} {% endfor %} </tbody> </table> </div> </div> </div> <input class="btn btn-success" type="submit" value="Submit"> </form> {% endblock %} forms.py from django import forms class AttendanceForm(forms.Form): ATTENDANCE_CHOICES = [ ('Present', 'Present'), ('Absent', 'Absent'), ] decision = forms.CharField(label='Attendance', widget=forms.RadioSelect(choices=ATTENDANCE_CHOICES)) views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect from django.contrib.auth.decorators … -
Operational Error on Usage of Imported Django Model
I am new to the Django framework and was trying to save data to an AbstractUser table from a registration form. But when I try to import the table into views.py, it becomes unusable for later operations. Please help me find where I have made an error: from django.shortcuts import render from django.urls import reverse from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth import authenticate, login, logout from .models import User #from django.core.paginator import Paginator def index(request): return render(request, "index.html",{ }) def register(request): if request.method == "POST": username = request.POST["username"] email = request.POST["email"] # Ensure password matches confirmation password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render(request, "register.html", { "message": "Passwords must match." }) # Attempt to create new user try: test = User test2 = User.objects.all() user = User.objects.create_user(username, email, password) user.save() except IntegrityError: return render(request, "register.html", { "message": "Username already taken." }) login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "register.html") def login_page(request): if request.method == "POST": # Attempt to sign user in username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) # Check if authentication successful if user is not None: login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "login.html", { … -
How to choose which product will be released first in the online store at django [closed]
How to choose which product will be released first in the online store at django. How logic can work. Any help is appreciated -
date updated as many times, should not created another entry for date in DB
Models.py class FreezePrimaryCategory(models.Model): freeze_date = models.DateField(default=datetime.datetime.now) updated_date = models.DateTimeField(auto_now=True) def __str__(self) -> str: return str(self.freeze_date) Views.py class FreezePrimaryCategory(APIView): permission_classes = (IsAuthenticated,) @checkToken def post(self, request): data = request.data freeze_date = request.data.get("freeze_date") data = { 'freeze_date': freeze_date, } serializer = FreezeCategorySerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializers.py class FreezeCategorySerializer(serializers.ModelSerializer): class Meta: model = FreezePrimaryCategory fields = ['freeze_date'] def validate(self, data): today = date.today() if data['freeze_date'] >= today: raise serializers.ValidationError('Date cannot be greater than current Date') return data I want date api entry in db should be only once and updated as many times. -
Displaying choice from a Model form based on another model
Working on a project that I am stumped on and I can't seem to find a good solution to this. An overview of the problem I need to resolve. I have 3 models (Games, GameRoles, and Groups) I have a defined list of games and a user can create a group from that list. The games also have roles associated with them. So the idea is I want a user to create a group based on a game from my game model, each game has different roles associated with it. When the user creates a group I want those roles to display in a checkbox field so they can add these roles if they need them. My problem is I can't seem to find a good way to do this. I read the docs and I think what I need is an Iterating relationship choice class in my forms.py Games model.py from django.db import models from django.db.models.aggregates import Max from django.db.models.fields.related import ForeignKey # Create your models here. class Game(models.Model) : GENRE_CHOICES = [ ('Action', 'Action'), ('Acion-Adventure', 'Action-Adventure'), ('Adventure', 'Adventure'), ('MMO', 'MMO'), ('Puzzle', 'Puzzle'), ('Role Playing', 'Role Playing'), ('Simulation', 'Simulation'), ('Strategy', 'Strategy'), ('Sports', 'Sports') ] RATING_CHOICES = [ ('E', 'Everyone'), … -
Can I extend Django model fields without creating mixed types?
I have subclassed builtin model Fields to reduce repetition in similar columns. This triggers exceptions in tests against Django 3.2 (but interestingly does work in the otherwise now irrelevant, unsupported, version 2.2) django.core.exceptions.FieldError: Expression contains mixed types: DecimalField, DecimalFieldWithBenefits. You must set output_field. class DecimalFieldWithBenefits(DecimalField): def validators(self): return super().validators() + [MinValueValidator(0.1), ] ... class Repro(Model): fraction = DecimalFieldWithBenefits(max_digits=4, decimal_places=4, default=Decimal("0.101")) ... # 3.2: django.core.exceptions.FieldError # 2.2: works Repro.objects.annotate(decimal_annotation = Decimal(1) - F("fraction")) # 3.2: works # 2.2: works Repro.objects.annotate(decimal_annotation = -F("fraction") + Decimal(1)) I found this entry in the Django 3.2 release notes that could explain the change in behaviour from the earlier version: [..] resolving an output_field for database functions and combined expressions may now crash with mixed types when using Value(). You will need to explicitly set the output_field in such cases. That suggestion does not solve my problem. If I were to bloat all annotations with ExpressionWrapper/output_field=, I could just aswell bloat the model definition and not use the subclass in the first place. I am not trying to cast mixed types. I want the combined output_field of DecimalField and DecimalFieldWithBenefits to be DecimalField - regardless of order of super/subclass. How do I express that no mixing …