Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Autocomplete - Multifill Tag Field at Django Form
Hi! I want to use a tagfield like it is depicted here within django framework: https://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/ For the moment I followed the suggestion to use: taggit (https://django-taggit.readthedocs.io/en/latest/) and dal (https://django-autocomplete-light.readthedocs.io/en/master/) extension. I want to have a multipinput field, getting the tags from json-data, allowing autocomplete, using bootstrap design. I just got crazy over the last 5 days, to get this properly working, testing different approaches... !!!!grmxchl!!!! Is somebody out there, able to help me out and suggest a principal solution for that. My current implementation does showing the objects instead the values and furthermore seems to somehow destroy the values on certain cases. However it looks like so. And should look like so. My code: Model class SrsReqs(models.Model): uid_req = models.AutoField(db_column='uid_Req', primary_key=True) # Field name made lowercase. req_title = models.TextField(db_column='Req_title', blank=True, null=True) # Field name made lowercase. req_userstory = models.TextField(db_column='Req_userstory', blank=True, null=True) # Field name made lowercase. req_tags = models.ManyToManyField(SrsTags) req_issues = models.ManyToManyField(SrsWsIssues, related_name='req') # through='ReqIssues', tags = TaggableManager() class Meta: db_table = 'SRS_Reqs' ordering = ['uid_req'] def __str__(self): return self.req_userstory View from django.shortcuts import render, get_object_or_404 from .models import SrsReqs from taggit.models import Tag from .forms import UpdateReq class ModifyRequ(TemplateView): template_name = 'requirements/change_req.html' def __init__(self, *args, **kwargs): super(ModifyRequ, self).__init__() … -
allauth registeration request is returning 500 smallint out of range
I recently migrated my database to PostgreSQL, and up until then, everything was working fine. now when I send a registration request the server is returning the following error (Although the user is being created in the database just fine). I am getting 500 error smallint out of range although none of the posted data has integer as dataType DataError at /authentication/registeration/ smallint out of range Request Method: POST Request URL: http://127.0.0.1:8000/authentication/registeration/ Django Version: 4.0.4 Exception Type: DataError Exception Value: smallint out of range Exception Location: C:\Users\Saad\OneDrive\Documents\Scripts\python\venv\lib\site- packages\django\db\backends\utils.py, line 89, in _execute Python Executable: C:\Users\Saad\OneDrive\Documents\Scripts\python\venv\Scripts\python.exe Python Version: 3.10.7 Python Path: ['C:\\Users\\Saad\\OneDrive\\Documents\\Scripts\\python\\motanafisoun-backend', 'C:\\Users\\Saad\\AppData\\Local\\Programs\\Python\\Python310', 'C:\\Users\\Saad\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', 'C:\\Users\\Saad\\AppData\\Local\\Programs\\Python\\Python310\\DLLs', 'C:\\Users\\Saad\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\Users\\Saad\\OneDrive\\Documents\\Scripts\\python\\venv', 'C:\\Users\\Saad\\OneDrive\\Documents\\Scripts\\python\\venv\\lib\\site-packages'] Server time: Wed, 12 Oct 2022 13:05:57 +0300 my models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import PermissionsMixin from django.utils.translation import gettext as _ from django.utils import timezone from PIL import Image from io import BytesIO import random GERNDER_CHOICES = (("male", "Male"), ("female", "Female"), ("unknown", "Unknown")) class UserManager(BaseUserManager): use_in_migrations: True def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_superuser", False) if not email: raise ValueError("The given email must be set") user = self.model( email=self.normalize_email(email), **extra_fields, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) … -
Django update initialized model with get from DB one
I am trying to change the existing initialized and not saved model instance to a one that exist in database. Is this doable? # models.py from django.db import models class Book(models.Model): def cache_or_get(self, some_value): # ... do some cache stuff if not cached: try: from_db = Book.objects.get(some_value=some_value) self.__dict__.update(from_db) # or self = from_db except Book.DoesNotExist: # do some other stuff -
Django Rest Framework not pulling through data
I'm trying to get my data to pull through from my model using DRF. It's my first time using it so I'm trying to work out what I'm doing wrong, the below view pulls through a blank list in the API for "chartdata". Can anyone help with what I'm doing wrong? I would like to get the data pulling through first, and my ultimate goal is to pull through my data and display it on a chart with chart.js on the 'health_hub_tracker' view. One step at a time! Any help would be appreciated! views.py: class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): labels = "weight (lbs)" chartLabel = "weight (lbs)" serialized_stats = [] for stats in HealthStats.objects.filter(user=request.user.id): serialized_stats.append({ "weight": stats.weight, }) data = { "labels": labels, "chartLabel": chartLabel, "chartdata": serialized_stats, } return Response(data) models.py: from django.db import models from django.contrib.auth.models import User from django.urls import reverse from cloudinary.models import CloudinaryField class HealthStats(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) weight = models.DecimalField(max_digits=5, decimal_places=2) run_distance = models.DecimalField(max_digits=5, decimal_places=2) run_time = models.DurationField() class Meta: db_table = 'health_stats' ordering = ['-date'] def get_absolute_url(self): return reverse('HealthHub:health_hub_history') def __str__(self): return f"{self.user} | {self.date}" class Article(models.Model): title = models.CharField(max_length=200, unique=True) topic = … -
how to add data to jsonfield django from views in django
I have a model with field jsonfield where I store if a shop is opened or not throughout the week I got data from form, and made the data into a json and tried to save, but I got error saying field is required why? working_days['friday'] = True if request.POST.get('friday') is not None else False working_days['saturday'] = True if request.POST.get('saturday') is not None else False form.working_days = json.dumps(working_days) if form.is_valid(): form.save() if I print form.working_days, I get correct json data but yet it is not saved, why? -
How can I add file manager
I'm making a basic panel with Django, I add sidebar, navbar some process but I need to add a file manager but idk how and I searched but couldn't find anything. I ask this question before but didn't worked. Can you help me?? -
Django RestFramework Create Object Without Serializer
i am trying to create an API using POST method in REST that receives the information of a new product and uses them to create a new product. here is an example of what the output should look like after sending POST request: { "message": "new product added successfully", "product": { "name": "chips", "price": 5000 } } this is my code: @api_view(['POST']) def create_product(request): name = request.data['name'] price = request.data['price'] return Response({ "message": "new product added successfully", "product": { "name": name, "price": price } }, status=status.HTTP_201_CREATED) and this is the error i get when i send post request: HTTP 400 Bad Request Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)" } what do i have to change in my code? thanks for helping :3 -
Mobe Groups model in Django Admin to custom app
I created UserProfiles model in Django in my users app. What I want is to put Group model to the same group in Django admin as UsersProfiles. I tried to implement this solution: Get Django Custom user model listed under admin app `Authentication and Authorization` however I am getting such error: <class 'filer.admin.permissionadmin.PermissionAdmin'>: (admin.E039) An admin for model "Group" has to be registered to be referenced by PermissionAdmin.autocomplete_fields. The code from the solution is below: class Group(DjangoGroup): """Instead of trying to get new user under existing `Aunthentication and Authorization` banner, create a proxy group model under our Accounts app label. Refer to: https://github.com/tmm/django-username-email/blob/master/cuser/admin.py """ class Meta: verbose_name = _('group') verbose_name_plural = _('groups') proxy = True admin.site.unregister(DjangoGroup) @admin.register(Group) class GroupAdmin(BaseGroupAdmin): pass How can I fix it? My UserProfiles model is placed in user app. The only thing I want is to move Groups from auth to user app. -
Get common values in django queryset
I am building a Quiz Application. I have a simple queryset, where I want to filter all the right answers given by the user. So far so good. After that, I would like to obtain the results, divided per subject, si I am trying to figure a way to filter even more. I post some code for better understanding: models.py class QuestionDraft(models.Model): quiz_profile = models.ForeignKey(QuizProfile, on_delete=models.CASCADE, blank=True, null=True) question = models.ForeignKey(Question, on_delete=models.CASCADE, blank=True, null=True) text = models.TextField() is_answered = models.BooleanField(blank=True, null=True) is_correct = models.BooleanField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Question(models.Model): id = models.CharField(max_length=7, default=generate_question_id, unique=True, primary_key=True, editable=False) question_subject = models.ForeignKey( QuestionSubject, on_delete=models.CASCADE) text = models.TextField() mark = models.IntegerField(default=1) is_published = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class QuestionSubject(models.Model): quiz_course = models.ForeignKey(QuizTheoryCourse, on_delete=models.CASCADE) name = models.CharField(max_length=200) exam_questions_num = models.IntegerField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) In my views I am trying, initially to filter the correct answers (which I am getting right) and after that to group the right answers per subject. Let's say, I have 10 different subjects views.py def test_report(request, pk): quiz_profile = QuizProfile.objects.get(id=pk) question_drafts = QuestionDraft.objects.filter(quiz_profile=quiz_profile) total_questions = question_drafts.count() right_answers = quiz_profile.right_answer quiz_percentage = ((right_answers * 100) / total_questions) wrong_answers = total_questions - … -
gunicorn - ModuleNotFoundError: No module named 'environ'
I am running the Django project with gunicorn: gunicorn --bind 0.0.0.0:8000 project.wsgi but I am getting the error below : [2022-10-12 12:05:11 +0300] [33444] [INFO] Starting gunicorn 20.1.0 [2022-10-12 12:05:11 +0300] [33444] [INFO] Listening at: http://0.0.0.0:8000 (33444) [2022-10-12 12:05:11 +0300] [33444] [INFO] Using worker: sync [2022-10-12 12:05:11 +0300] [33446] [INFO] Booting worker with pid: 33446 [2022-10-12 12:05:12 +0300] [33446] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/idris/.local/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/home/idris/.local/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/home/idris/.local/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/home/idris/.local/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/idris/.local/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/home/idris/.local/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/home/idris/.local/lib/python3.8/site-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/idris/Documents/workspace_captiq/venv/captiq/captiq/wsgi.py", line 8, in <module> application = get_wsgi_application() File "/home/idris/.local/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/home/idris/.local/lib/python3.8/site-packages/django/__init__.py", line 19, in setup … -
How to make Django values() exclude some fields?
I have multiple models which has fields like "created_at" "updated_at" which I don't want to get with objects.values() Does Django has any way to exclude fields in values(). I know people refer to defer(), but it doesn't return QuerySet<Dict> like values() instead returns QuerySet<Model>. I tried objects.defer("created_at", "updated_at").values(), but it includes those 2 deferred fields in the resulting Dict. I see defer().query only selecting the non-exluded fields in the SQL, but using defer(..).values() resets the deferred fields and selects all fields. I cannot specify which field I want, since different model has different fields, I can only specity which fields I don't want. So I cannot use values('name', 'age', ...) I'm planning to use a CustomeManager, which I can use in all model. Eg: class CustomManager(models.Manager): def values_excluded(self): return self.values() # somehow exlude the fields and return QuerySet<Dict> class ExampleModel(models.Model): name = models.CharField(max_length=20) age = models.IntegerField() created_at = models.DateTimeField() updated_at = models.DateTimeField() objects = CustomManager() ExampleModel.objects.values_excluded() Is there any way in Django or do I have to manually delete those keys from the resulting Dict from values()? -
Django -- concatenate filter on a many_to_many relation create unexpected join
class ProductionOrderProductionOrderStatus(sf_models.BaseModel): production_order = models.ForeignKey(ProductionOrder, on_delete=models.CASCADE) production_order_status = models.ForeignKey(ProductionOrderStatus, on_delete=models.CASCADE) class ProductionOrderStatus(sf_models.BaseModel): status = models.IntegerField(null=False) begin_datetime = models.DateTimeField(default=timezone.now) end_datetime = models.DateTimeField(null=True, blank=True) class ProductionOrder(sf_models.BaseModel): statuses = models.ManyToManyField(ProductionOrderStatus, through='ProductionOrderProductionOrderStatus', related_name='production_orders') if i concatenate 2 filter like this -> ProductionOrder.objects.filter(statuses__status=2).filter(statuses__end_datetime=None) i get this sql: 'SELECT ... FROM "production_order_productionorder" INNER JOIN "production_order_productionorderproductionorderstatus" ON ("production_order_productionorder"."id" = "production_order_productionorderproductionorderstatus"."production_order_id") INNER JOIN "production_order_productionorderstatus" ON ("production_order_productionorderproductionorderstatus"."production_order_status_id" = "production_order_productionorderstatus"."id") LEFT OUTER JOIN "production_order_productionorderproductionorderstatus" T4 ON ("production_order_productionorder"."id" = T4."production_order_id") LEFT OUTER JOIN "production_order_productionorderstatus" T5 ON (T4."production_order_status_id" = T5."id") WHERE ("production_order_productionorderstatus"."status" = 2 AND T5."end_datetime" IS NULL)' if i put on the same filter like this -> ProductionOrder.objects.filter(statuses__status=2, statuses__end_datetime=None) i get this sql: 'SELECT ... FROM "production_order_productionorder" INNER JOIN "production_order_productionorderproductionorderstatus" ON ("production_order_productionorder"."id" = "production_order_productionorderproductionorderstatus"."production_order_id") INNER JOIN "production_order_productionorderstatus" ON ("production_order_productionorderproductionorderstatus"."production_order_status_id" = "production_order_productionorderstatus"."id") WHERE ("production_order_productionorderstatus"."end_datetime" IS NULL AND "production_order_productionorderstatus"."status" = 2)' if i have a queryset created with this condition: ProductionOrder.objects.filter(statuses__status=2) how can i concatenate the second condition? is there a solution to get a dict of the already filtered condition? (to get for example {'statuses__status':2}, so i can concatenate the second condition and recreate the query) -
Django error ValueError: Field 'id' expected a number but got ''
I create django model for keep api_key as char like this. class DeviceKey(models.Model): api_key=models.CharField(max_length=100,unique=True) limit_device=models.IntegerField() created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) def __str__(self): return self.api_key class Meta: ordering=('api_key',) verbose_name='DEVICE KEY' verbose_name_plural='DEVICE KEY' class Device(models.Model): api_key=models.ForeignKey(DeviceKey,on_delete=models.CASCADE) name = models.CharField(max_length=100) status=models.BooleanField() switch=models.BooleanField(default=False) timer=models.BooleanField(default=False) category=models.ForeignKey(Category,on_delete=models.CASCADE) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) def __str__(self): return self.name class Meta: ordering=('api_key',) I create function device() in views.py for get data by using api_key like this. def device(request): key = request.GET.getlist('key') data=Device.objects.filter(api_key__in=key).values_list('name','status') return JsonResponse(list(data), safe=False) In admin page I create sample api_key as 2eaWe. when I run and send api_key to function device() it show error like this. ValueError: Field 'id' expected a number but got '2eaWe'. -
Aggregate return null values if queryset is none even if using Coalesce with default value
currently, I am trying to aggregate on queryset. it's working perfectly but the problem is if my queryset is none Coalesce function is not working so default value is set null rather than 0 . aggregated_data = queryset.aggregate( total_trips=Coalesce(Sum("total_trips"), 0, output_field=IntegerField()), total_orders=Coalesce(Sum("total_orders"), 0, output_field=IntegerField()), total_expense=Coalesce(Sum("total_expense"), 0, output_field=IntegerField()), total_payment=Coalesce(Sum("total_payment"), 0, output_field=IntegerField()), total_collected_payment=Coalesce(Sum("total_collected_payment"), 0, output_field=IntegerField()), total_driver=Coalesce(Sum("total_drivers"), 0, output_field=IntegerField()), total_utilized_driver=Coalesce(Sum("total_utilized_drivers"), 0, output_field=IntegerField()), total_vehicles=Coalesce(Sum("total_vehicles"), 0, output_field=IntegerField()), total_utilized_vehicles=Coalesce(Sum("total_utilized_vehicles"), 0, output_field=IntegerField()), ) current output if queryset is none : { "total_trips": null, "total_orders": null, "total_expense": null, "total_payment": null, "total_collected_payment": null, "total_driver": null, "total_utilized_driver": null, "total_vehicles": null, "total_utilized_vehicles": null } expected output : { "total_trips": 0, "total_orders": 0, "total_expense": 0, "total_payment": 0, "total_collected_payment": 0, "total_driver": 0, "total_utilized_driver": 0, "total_vehicles": 0, "total_utilized_vehicles": 0 } -
Django: how to save instance to a foreign key field based on the fields equally
So I have a user model that has a foreign key relation with class/room, I want a user to be able to press one button and all the users/students would be equally distributed throughout the class/room foreign key based on fields from the model like age, height and other fields. so if there are 4 students 2 with age 14 and 2 with age 15 and there are two classes, the function should put one 14-year-old and one 15-year-old in 1 class and the same in the other class as well, just iterate through the users and distribute them by the selected field values equally, any resource or code snippet would be highly appreciated. -
how to use AWS access keys in django?
I've currently configured my access keys as part of the environment variables and using that on the code: code However, when I host the application and someone tries using it, it will only work if they have the keys configured the same way. Is there any other way around this? -
Django Rest Framework and Group permissions [closed]
Is it possible to manage App level permissions using groups in DRF? My goal is to have different apps, and grant permissions to each of them based on group permission. So, each application has its own group, and only users in this group can access the app's endpoints. -
How to upload multiple images in django rest framework
I want to upload multiple images using image model not like a nested serializer Here is my serializer class ProjectImageSerializer(ModelSerializer): class Meta: model = ProjectImage fields = ( 'id', 'file', 'project', ) This is the model class ProjectImage(models.Model): file = models.ImageField( upload_to='apps/projects/ProjectImage/file/', ) user = models.ForeignKey( 'users.User', on_delete=models.CASCADE, related_name='project_image_set', ) project = models.ForeignKey( 'Project', on_delete=models.CASCADE, related_name='image_set', ) created = CreatedField() last_modified = LastModifiedField() def __str__(self): return basename(self.file.name) and here is Views.py class ProjectImageViewSet(viewsets.ModelViewSet): parser_classes = [ MultiPartParser, ] queryset = ProjectImage.objects.all() serializer_class = ProjectImageSerializer can anyone help me when I try with postman its selecting multiple images but posting only one -
How does the Django setting of letting it know about your app really work?
I've been learning django for a few weeks , but i still cant fully understand how some of the settings really work,like the most basic one that when i create a new app called 'base' inside my django project then i should let django know about my app so i write like as most of the people do 'INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base.apps.BaseConfig', ]' but if i write just only my app name 'base' , it still works , so can someone tell me what is the difference between this two? 'INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base', ]' -
I need to get the value of the field that we enter in the form and immediately take action on it
I need to get the value of the field that we enter in the form (in this case, these are the days of reservation) and immediately calculate the cost of the reservation based on it And the problem is that I don’t understand how to get the value of these very fields (so this is not QuerySet request, and not accessing the database) This is my views: def booking(request): error = '' if request.method == 'POST': form = BookingForm(request.POST) if form.is_valid(): booking = form.save(commit=False) booking.user = request.user booking.sum = #create sum function form.save() return redirect('account') else: error = 'Форма не корректна' form = BookingForm() context = { 'form': form, 'error': error } return render(request, 'bookings/booking.html', context) And this is models: class Booking(models.Model): startdate = models.DateField('Startgdate') finishdate = models.DateField('Finishdate') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) sum = models.PositiveIntegerField('Sum') fullname = models.CharField('Full name', max_length=50) pnumber = models.PositiveBigIntegerField('Phone number') def __str__(self): return self.fullname class Meta: verbose_name = 'Booking' verbose_name_plural = 'Bookings' thanks in advance -
How to return a folder in django views for using it in nginx proxy_pass?
I have 1 main server, where django and html with css, js located. While I am also have proxy server, that contains only nginx file that proxy_pass to django main server(by domain name) and receive site html code and another static. Here is my nginx file: server { server_name 11.111.111.111; index index.html location / { proxy_pass http://example.com/api/v1/render/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Photo $scheme; } } And after this I have 404 error. What I am need to do in django view /api/v1/render to return a folder with index.html, css and js scripts, that would be shown on 11.111.111.111 url? It also hasn't traces, that proxy_pass really works, because main server don't receive any requests. Thanks for help. -
how to use ccextractor with python?
I'm working on a django application to generate subtitles for videos. I'm required to use only ccextractor for this. I have figured out a way to use it using wsl: code However, it returns errors when I run it in other systems, since not everyone has ubuntu configured. Looking for a way to do this without using wsl. Any help is appreciated. -
Django admin file upload button not clickable
I was building an app and had the image upload section working previously, however, 2 weeks on in the project for some reason the upload file button in Django admin is no longer doing anything when clicked. I can't work out what is blocking it as it's in the admin, Any suggestions? This is for any of the apps in the project. This is the admin.py from django.contrib import admin from desire import models admin.site.register(models.Desire) admin.site.register(models.RelatedProduct) from django.contrib import admin from django.contrib.auth.admin import UserAdmin from account.models import Account class AccountAdmin(UserAdmin): list_display = ('email','username','date_joined', 'last_login', 'is_admin','is_staff') search_fields = ('email','username',) readonly_fields=('id', 'date_joined', 'last_login') filter_horizontal = () list_filter = () fieldsets = () admin.site.register(Account, AccountAdmin) settings BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = [ # my APPs 'personal', 'account', 'ckeditor', 'ckeditor_uploader', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', 'bootstrap4', 'fontawesome', 'cropperjs', 'django.contrib.humanize', ] AUTH_USER_MODEL = 'account.Account' # TODO: ADD THIS LINE. AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.AllowAllUsersModelBackend', 'account.backends.CaseInsensitiveModelBackend', ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] DATA_UPLOAD_MAX_MEMORY_SIZE = 10485760 STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'media'), ] STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn') MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn') TEMP = os.path.join(BASE_DIR, 'media_cdn/temp') BASE_URL = "http://127.0.0.1:8000" -
Inline form validation based on Parentform - Django Admin
Below is my admin form Class RequestedAreaInilne(admin.StackedInline): model = RequestedArea fields = ("area", "building") class BuildingAdmin(admin.ModelAdmin): fields = ("special_access", "user_id", etc ....) inlines = (RequestedAreaInline,) While saving the BuildingAdmin form I need to validate inline form (ie RequestedAreaInilne). Validation should happen based on the value from the BuildingAdmin form field . To add more information , special_access of the BuildingAdmin is boolean field(True or False). If the user selection is True , I want to check if they have entered value for RequestedAreaInline. If it is not entered I need show them a message that "You should enter data for this" I tried doing the validation in save_formset(). But I am not getting inline field. How can I validate the inline formset based on parent form -
How SQL query Case and When works in django ORM?
I have a SQL query and when writing in Django ORM it returns an error. But the SQL query works perfectly on MySQL Command Line Client. Would anyone please explain the error or working of CASE and When in Django ORM? SQL query:- SELECT CASE WHEN LENGTH(au.first_name) < 1 THEN au.username ELSE concat(au.first_name,' ',au.last_name) END AS fullname FROM rewards_usercard ru RIGHT JOIN auth_user au ON ru.user_id = au.id; Django Models code:- queryset = UserCard.objects.annotate( full_name = models.Case( models.When(condition=models.Q( models.lookups.LessThan(models.functions.Length('user__first_name'),1) ), then='user__username'), default = models.functions.Concat('user__first_name', models.Value(' '), 'user__last_name'), output_field=models.CharField() ) ) Error:- cannot unpack non-iterable LessThan object