Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: (fields.E300) Field defines a relation with 'Class' model , which is either not installed, or is abstract
Class model is a foreign key in File model I have no idea what causes the error above,I searched it and it mostly occurs when working with models in different apps, but that is not case in this situation, since both models are in the same models.py file. models.py from asyncio.windows_events import NULL from http.cookiejar import FileCookieJar from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractBaseUser,PermissionsMixin, BaseUserManager class Class (models.Model): name=models.CharField(max_length=256); def __str__(self): return self.name; class File (models.Model): file=models.FileField(); name=models.CharField(max_length=255); class_name=models.ForeignKey(Class,on_delete=models.CASCADE) def __str__(self): return self.name; class Class (models.Model): name=models.CharField(max_length=256); def __str__(self): return self.name; class CustomUserManager(BaseUserManager,): def create_superuser(self,email,name,surname,password,**other_fields): other_fields.setdefault('is_staff',True) other_fields.setdefault('is_superuser',True) other_fields.setdefault('is_active',True) if other_fields.get('is_staff') is not True: raise ValueError('super user must be assigned to is_staff= True') if other_fields.get('is_superuser') is not True: raise ValueError('Super user must be assigned to is_super_user=True') return self.create_user(email,name,surname, password,**other_fields) def create_user(self,email,name,surname,password,**other_fields): if not email: raise ValueError(('You must provide an email address')) email=self.normalize_email(email); #for example ignore the case sensitivity user=self.model(email=email,name=name,surname=surname,**other_fields) user.set_password(password) user.save() return user; class NewUser(AbstractBaseUser,PermissionsMixin): email=models.EmailField(max_length=255,unique=True,default=NULL,) name=models.CharField(max_length=255) surname=models.CharField(max_length=255) is_staff=models.BooleanField(default=False) is_active=models.BooleanField(default=True) is_teacher=models.BooleanField(default=False) classes=models.ManyToManyField(Class) objects=CustomUserManager(); USERNAME_FIELD='email' REQUIRED_FIELDS=['name','surname','is_teacher'] def __str__(self) : return self.name class Request(models.Model): requested_class=models.ForeignKey(Class,on_delete=models.CASCADE) requesting_student=models.ForeignKey(NewUser,on_delete=models.CASCADE) def __str__(self): return self.requesting_student.name # Create your models here. -
Django Authentification with class based views login() method
as I am trying to build a login/registration form, I came into a problem. I am building my form with class based views, and I want to use the login() method for the auth. The problem is that it won't work, even if I have followed the same example as the docs had. Here is my code: views.py: def login(request): if request.method == 'POST': form = MyLoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect("/home") else: messages.error(request, 'There Was An Error Logging In, Try Again...') else: form = MyLoginForm() return render(request, 'users/firstAction/login.html', {'form': form}) My template: <body> <div class="limiter"> <div class="container-login100" style="background:black;"> <div class="wrap-login100"> <span class="login100-form-logo"> <i class="zmdi zmdi-landscape"></i> </span> <span class="login100-form-title p-b-34 p-t-27"> Login </span> {% if messages %} <ul class="red"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} {% if form %} <form method="POST" novalidate class="login100-form validate-form"> {% csrf_token %} {% if form.non_field_errors %} {% for error in form.non_field_errors %} <div class="red"> <p>{{error}}</p> </div> {% endfor %} {% endif %} {% for field in form %} <div class="wrap-input100 … -
AttributeError at /account/oidc/callback/ '_RSAPrivateKey' object has no attribute 'verify'
AttributeError at /account/oidc/callback/ '_RSAPrivateKey' object has no attribute 'verify' Request Method: GET Request URL: http://localhost:8000/account/oidc/callback/?code=0.AQwA2kdaUAbvNU-5Y653jiyu-YHq0RPhP-9Cu3wqKQekVioMAJA.AQABAAIAAAD--DLA3VO7QrddgJg7Wevr6SStf98KkAv7heodBmkUKzmyvPGA7xsbND57p5XO-w3Cdn_KSw8Pbvcz5A1oB_i7zyj2emCgFtsFIlY-wI2MmRKmDBv0ZTJ07SUw_qJigWlRQeA5eXcCiE_f9WjU7qolelJFjA2GxgUXxH_7Fv7GMns1mXDPSicVwt_wBVzTDX-ONGIGqoR8tmsLMKOGBZtDKM9wy46LbXH3TOTR8ZwlyNZZDInpOuIWc2-RYyR73_fhjc57o07bVEJb7GT7sgzQ6Usp9a7pGAdLd3zaXZdPa-y3Dt71dlmLTqNkLi_COaTikBdzYRQEDRMMIjIKaLcSJXbCNRXd2pcPqDadXyS3_iZnhdfdFEK0-52vz-8pJUzZVGghTTiyTWojNd851369lriYC6SKn4qA7tcfLjqoHSJ71CkPVTD_dv1S_YZCPjzEBjuQ9FaKqJ6_EjhsQbwp1mrr6iJQg5fb-oGPEV21twaNvhppiApzhi_d7wKU-qRDv9xARGCuQ8R_w2smNNOrBamaSqQKph0pBVbq-N-04nT9ghp-83vhRCCrmPiCLRJfGb3xq-Pp2jwe4qBnoNhb2XNjZbtypPtel-EVY4XcqSAA&state=1TepMIKbpC2BHhWd0PpJJcBifzHqPrF6&session_state=bbe01820-0187-4e1e-9982-9431dc7bd273 Django Version: 1.9.7 Exception Type: AttributeError Exception Value: '_RSAPrivateKey' object has no attribute 'verify' Exception Location: C:\Users\hp\AppData\Local\Programs\Python\Python36\lib\site-packages\josepy\util.py in getattr, line 81 Python Executable: C:\Users\hp\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.5 -
How allow to fit read_only field for new record in TabularInline class in Django
I want to have a field readonly when record already saved but if admin adds a new record field must to be editable. Red arrows - read only; Blue arrow - edited. How I can achieve it? -
How to force a page-break on weasyprint?
I wonder if its possible to create a force break that splits the table rows? I think weasyprint does this in a sense but I want to break the rows in to specific counts (e.g 6 rows per page). Is that possible? I tried something like this: <table> <tr> <th>Header1</th> <th>Header2</th> </tr> {% for d in data %} {% if forloop.counter == 6 %} <p style="page-break-before: always;"></p> {% endif %} <tr> <td>{{ d.name }}</td> <td>{{ d.age }}</td> </tr> {% endfor %} </table> but it just break each row in different pages. Any help would be appreciated. -
Can I somehow combine columns into array of objects (list of dicts) by Django ORM?
I use PostgreSQL as a DB. And I have the following situation: Say, we have the following data (we got it joining two tables - orgs and markers). What I want to get by SELECT is Using raw SQL I would do something like this SELECT orgs.org_id, json_agg( json_build_object( 'id', markers.marker_id, 'name', markers.name ) ) as markers_data FROM orgs INNER JOIN markers ON orgs.org_id = markers.org_id GROUP BY orgs.org_id; But I want to combine those columns this way using Django ORM. Is it possible to do on SQL level not Python? So I don't have to just extract data from the DB and modify it to a desired format on Python level. -
How do I remove unused CSS when using Django, Sass and a frontend framework?
I am using a SCSS-based frontend framework (namely cirrus-ui) with my Django project. For compiling the CSS stylesheet with Sass, I use webpack to compile the static files (Presently only CSS stylesheets but I'm sure some JavaScript will probably work its way in there eventually). In the Python project, I use django-webpack-loader. My compiled, minified CSS stylesheet is a whopping 265 KiB. This is not ideal. I know about PurgeCSS and uncss. While I have not used them before, I think I understand how to call these from the webpack.config.js. What I don't know is how to utilize these or something similar with Django and its templates. Notes: I use Yarn to manage packages. main.scss (example excerpt). @use "cirrus-ui/src/cirrus-all" as *; I actually do provide a custom configuration map, but I don't see how that's relevant to the question. Relevant Django Configuration Details (settings.py) WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, 'STATS_FILE': BASE_DIR / 'frontend/webpack-stats.json', 'POLL_INTERVAL': 0.1, 'IGNORE': [r'.*\.hot-update.js', r'.*\.map'], } } STATICFILES_DIRS = [ './frontend/static', ] Project layout PROJECT ROOT/ - djangoproject/ - settings.py - templates (TEMP)/ - manage.py - frontend/ - .yarn/ - static/ - (Compiled Static Files Here) - assets/scss/main.css - webpack.config.js - webpack-stats.json - package.json … -
how to link a div using <a href> to appear in the middle of the screen instead of top?
this is to go back to home page that has a listview of posts and to keep the screen at where the post is located after clicking go back button in the post details page. <a href="/users/home#post{{ post.id }}"><button class="button" style="float: right; margin-right: 5px;">Go back</button><br></a> However, since there is a sticky nav bar at the top, it covers the post after clicking go back button. I want to make the post appear in the middle of the screen instead of at the top. -
DRF ModelSerializer meta extra_kwargs not working for related fields
I am designing API in DRF and have stumbled upon one issue that hopefully you can help me to solve. Let's assume I have the following model and a serializer: class SomeModel(models.Model): property = models.ForeignKey( Property, on_delete=models.PROTECT, ) name = models.CharField() address = models.OneToOneField(null=True, blank=True) ...more class SomeModelSerializer(serializer.ModelSerializer): class Meta: model = SomeModel fields = "__all__"" extra_kwargs = { "name": {"required": True}, "address": {"required": True}, "property": {"required": True}, } As you can see I am trying to add field kwargs by using extra_kwargs. The issue is that it won't work for a related field e.g. property or address field. I know I can just override it by defining a field manually and passing required=True, and that works but it's too long for my use case. Do you have any idea why this happen? Thanks. -
A problem with django using DefaultRouterWithNest
router2 = DefaultRouterWithNest() ( router2.register(r'eva',eval.Evadetail, basename='eva') .register(r'evand',eval.Evand,basename='eva-evand',parents_query_lookups=['eva_id']) .register(r'evard',eval.Evard,basename='eva-evard',parents_query_lookups=['eva_id','eva_nd_id']) ) problems: NameError: name 'DefaultRouterWithNest' is not defined what packeages should I import? -
Replacement in python package in Docker
GraphQL is still not supported in Django 4, so to use it I need to change the line: "from django.utils.encoding import force_text" to "from django.utils.encoding import force_str as force_text" in package "VENV/lib/PYTHON_VERSION/site-packages/graphene_django/utils/utils.py" The problem occurs when using Docker, how could I replace this line when building the container? -
Url decoding problem on deployment with IIS and FastCGI on windows server
I realized an app front Angular, back-end Django, deployed on Windows server using IIS and FastCGI. This app serves media files on a certain URL. It works fine locally on dev server. I can access all my files correctly on path "medias/myfilepath". The problem is in production on IIS. Special characters are encoded in a different way. I think it is FastCGI that does it. I cannot find the encoding rules, and my Django app is not able to decode properly so my requests end up with a 404 error. Here are some examples of the difference of encoding between local server and production server : à | local : %C3%80 | prod : %25C0 ù | local : %C3%99 | prod : %25D9 É | local : %C3%89 | prod : %25C9 I can't find any documentation on the subject, I don't have access to configurations on CGI side. I could update decoding on Django side to fit it, but I can't find which one applies ... Someone would have some ideas on that subject ? -
WARNING: autodoc: failed to import module 'upload_data_to_server' from module 'manual';
I'm trying to document a Django project using Sphinx's autodoc extension. I have two main problems: It's documenting excessivelly in some modules (importing documentation that I don't want from django) It's not documenting one of the packages at all. Here is my django tree: |main_app | core | migrations | static | templates | consumers.py | forms.py | models.py | routing.py | serializers.py | urls.py | views.py | main_app | asgi.py | settings.py | urls.py | wsgi.py | manual | upload_data_to_server.py | manage.py | docs | _build | _static | _templates | conf.py | index.rst | make.bat | Makefile The docs file is the one I created to host the files created by sphinx-quickstart. Then, I changed the conf.py file adding this lines: import os import sys import django sys.path.insert(0, os.path.abspath('..')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main_app.settings") django.setup() extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] And I changed index.rst adding modules: Welcome to yourProject's documentation! ==================================== .. toctree:: :maxdepth: 2 :caption: Contents: modules Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` I executed sphinx-apidoc -o . .. and ./make html. I get something similar to what I want, but I said before, I get too many comments for django files, and no comments at all … -
How to optimize the downlaod big file problem in Django?
My Django project gives an download interface as def download_item_vector(request): return HttpResponse(np.load('item_vector.npy')) I want to return a big numpy array to the client. But it is very slow. Is there any good idea to do that? -
Testing UX with random IO?
So I've found a error in my UX that wasn't cought by test if I press besides a popup it goes into deadstate # they press ok btn = self.browser_adam.find_element(By.ID, "closeBtnMod").click() How do I catch things like reloading a page or this special case? -
Django model default value in response
I want to have a default value in my django model response value Sample model query myModel.objects.filter().values("username", "user_gender") I want to have a default value in response It must be like Select username, user_gender, 'delhi' as country from mytable Please let me know if any suggestions -
How to create a persigned url for a private s3 bucket using django rest framework
models.py def upload_org_logo(instance, filename): ts = calendar.timegm(time.gmtime()) filepath = f"Timesheet/org_logo/{ts}" if instance: base, extension = os.path.splitext(filename.lower()) filepath = f"Timesheet/org_logo/{instance.org_id}/{instance.org_name}{extension}" return filepath class Organisation(models.Model): """ Organisation model """ org_id = models.CharField(max_length=50,default=uuid.uuid4, editable=False, unique=True, primary_key=True) org_name = models.CharField(unique=True,max_length=100) org_code = models.CharField(unique=True,max_length=20) org_mail_id = models.EmailField(max_length=100) org_phone_number = models.CharField(max_length=20) org_address = models.JSONField(max_length=500, null=True) product = models.ManyToManyField(Product, related_name='products') org_logo = models.ImageField(upload_to=upload_org_logo, null=True, blank=True,) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I am saving the Org_logo in the private s3 bucket, I need to get the Image from the s3 bucket using a presigned url. I checked out some solutions but I am not sure how to use it specifically on where like in models or views or other? Can you please help me with how to use it and where to use based on my above code. AWS Settings.py AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' AWS_STORAGE_BUCKET_NAME = '' AWS_QUERYSTRING_AUTH = True AWS_S3_FILE_OVERWRITE = True AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_REGION_NAME = '' AWS_DEFAULT_ACL = None AWS_S3_VERIFY = True DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
how can i filter data between two time i am using date time field for it in django rest framework
I am trying to filter my data with date time field but in my case its not working so please someone suggest me how can i filter my date with time start_time = 2022-05-13 02:19:19.146009 end_time = 2022-05-13 02:20:19.146009 parser_order_mi = ParserOrderMenuItem.objects.filter(menu_item_id=menu_item_id, created_at__range=[start_time,end_end_time]) -
Adding field to Django model when the column already exists in the database
I have a model in Django which represents a MySQL table that has some extra columns. I want to add a field to the model for one of these extra columns but I'm not sure how best to do it. Let's say the person table has an age column. My model looks like: class Person(models.Model): name = models.CharField(min_length=200) If I add an age field like: age = models.IntegerField(db_column="age") then when I migrate I get an error about "Duplicate column name 'age'" because it tries to create it. Is there a way around this? What I've tried: Add the field with a new column and make a migration for that: age = models.IntegerField(db_column="age_2") Create a manual data migration to copy data from original column to new one: UPDATE person SET age_2 = age; Create a manual migration to drop the original column: ALTER TABLE person DROP COLUMN age; Create a manual migration to rename the new column: ALTER TABLE person RENAME COLUMN age_2 TO age; On the model change it to use the age column (db_column="age") and make an automatic migration. This works on my existing database, but when I run my tests, and it applies all the migrations to create … -
Django filtering on a queryset not working
I am trying to add a filter on an existing queryset based on a condition but it doesn't work. This works queryset = None if self.is_instructor == True: queryset = Issue.objects.filter(type=self.type, type_id=self.type_id).filter(status__in=self.status) else: queryset = Issue.objects.filter(type=self.type, type_id=self.type_id, created_by=self.created_by) This doesn't queryset = None if self.is_instructor == True: queryset = Issue.objects.filter(type=self.type, type_id=self.type_id) else: queryset = Issue.objects.filter(type=self.type, type_id=self.type_id, created_by=self.created_by) if len(self.status) > 0: queryset.filter( Q(status__in=self.status) ) queryset.order_by('-created_on') This is how my model looks like STATUS_CHOICES = ( ('UNC', 'Unconfirmed'), ('CNF', 'Confirmed'), ('INP', 'In Progress'), ('UAC', 'User Action Pending'), ('RES', 'Resolved'), ) class Issue(models.Model): UNCONFIRMED = 'UNC' title = models.CharField(max_length=512, blank=False) description = models.TextField(blank=False) created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='creator') created_on = models.DateTimeField(auto_now_add=True) status = models.CharField( max_length=3, choices=STATUS_CHOICES, default=UNCONFIRMED ) Assured, self.status holds the required data. I can't use get() because there are multiple records I have seen some other answers but couldn't make progress. Thanks in advance. Basant -
Django: how to count posts related to a category in django?
i have a model class Category and also a model class Course. i want to count all the courses that are related to a model e.g: Web Devlopment - 26 Courses i dont know how to go about this since the this are two diffrent models. class Category(models.Model): title = models.CharField(max_length=1000) class Course(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) course_title = models.CharField(max_length=100, null=True, blank=True) course_category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, null=True, blank=True) -
Indexing 80 million documents to elasticsearch from Django
I am using the latest version of django elasticsearch dsl and I am using the following command to index around 80 million documents: python manage.py search_index --rebuild --models <model> --parallel However, my system can't handle it and crashes at about 12gb of ram usage. CPU usage is 10% and seems to be fine. Is there a way to index this amount of django entries to elasticsearch safely? -
Why does Django use `Meta` inner class in models?
If I want to describe some information such as ordering, if the model is proxy or abstract, which fields must be unique together, then I need to put this information in class named Meta that is inside of my model class. But if I want to change the manager I put information about it in the model class itself. class Product(models.Model): class Meta: unique_together = ... ordering = ... objects = My manager() Why did Django developers made such design decision (forcing to put some information about the model in the Meta inner class instead of the model class itself)? -
Django - Hide labels in inline
How to hide labels in Django inlines? -
why does for loop not working in django template
this is my views : rooms = [ {'id': 1, 'name': 'room-1'}, {'id': 2, 'name': 'room-2'}, {'id': 3, 'name': 'room-3'}, {'id': 4, 'name': 'room-4'}, ] def rooms(request): return render(request, 'rooms.html', {'rooms': rooms}) and template codes : {% for room in rooms %} <li>{{room.id}} -- {{room.name}}</li> {% endfor %} unfortunately for loop is not working.