Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django user doesn't inherit its groups permissions
In my Django project my jack user is in a group called 'Personals'. 'Personals' group has a permission named 'personal'. But jack doesn't inherit that permission from its group. How can I fix this problem? >>>jack = User.objects.get(username="jack") >>>jack_permissions = Permission.objects.filter(user=jack) >>>print(jack_permissions) <QuerySet []> #It gives a emty query. >>>jack_group = jack.groups.all() >>>print(jack_group) Personals >>>jacks_group = Group.objects.get(name="Personals") >>>jacks_groups_permissions = jacks_group.permissions.all() >>>print(jacks_groups_permissions) <QuerySet [<Permission: auth | user | The Personals>]> #The Group has the permission The Personals -
Django staticfiles not loading in AWS ec2
I've deployed a django webiste in AWS ec2 with the help of this digitalocean blog but the static files like css and javascripts are not loading after deployment. This is my django static code: STATIC_URL = '/static/' MEDIA_URL = 'media/' MEDIA_ROOT = 'media/' STATIC_ROOT = 'staticfiles/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] and this is my nginx code: server { listen 80; server_name mydomain.com; location = /favicon.ico { access_log off; log_not_found off; } location /staticfiles/ { root /home/sammy/project/myproject; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } And I'm using AWS S3 to host my static files. -
Build a query to get grouped average of multiples many to one instances
I'm having two models : class Club(models.Model): club_tag = models.CharField(primary_key=True) class Player(models.Model): rating = models.FloatField(default=0) club = models.ForeignKey(Club, ...) My objective is to get the top 10 of clubs with the best average rating players, in decreasing order. In this situation the Club has an average rating (Which is its player's average) and is ranked thanks to it. I'm having a hard time figuring out how to pull this request, can someone give me directions please ? Thanks -
Category API for products django
I have two models: Category, Products. And I want to create a separate url link like http://127.0.0.1:8000/api/categories/sneakers for each category to retrieve products from different APIs. Using foreign key I can separate them but don't really know how to give them a url. Could you help me with this, please? -
Cannot save Celery object in Django migrations
The problem is as follows I am using json to deserialise and populate Celery model with Intervals, Crontabs and vital PeriodicTasks serialisation / deserialisation works totally fine The problem is that if I run the following function from elsewhere in code or from Django shell - everything is working totally fine, but when I put it inside migration - objects are not getting saved, although I see with loggers that all steps are being passed Here is this simple function: for obj in serializers.deserialize("json", json_with_tasks): obj.save() -
In django how to generate a pdf file from django template maintaining the css style?
I have created a pdf file with the Django template. In the template whatever CSS is applied is not showing in generated pdf. Here is the code I have used : from io import BytesIO from xhtml2pdf import pisa from django.template.loader import get_template from django.http import HttpResponse from django.shortcuts import render def home(request): pdf = render_to_pdf("abc.html") return HttpResponse(pdf, content_type='application/pdf') def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') else return None -
Why is the Middleware not processed on 404 page in Django?
So I've set up a path in my URL config: path( "kitten/", views.Kitten.as_view(), name="kitten", ), and a handler for missing URLs to the same view. handler404 = views.Kitten.as_view() I have some middleware which sets some context data: class CookieConsentMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_template_response(self, request, response): response.context_data["hasCookie"] = False return response and the view is very straightforward, class Kitten(TemplateView): template_name = "kitten.html" and the template prints the value of hasCookie. Visiting kitten/ correctly displays the value of hasCookie, but visiting a URL that doesn't exist, displays no value for hasCookie (whilst showing the right template) Adding debugging statements to the middleware, it becomes apparent that whilst process_view, process_template_response and process_exception are called for kitten/, none of these are called for URLs that don't exist, so no code is called to set the value of hasCookie. (__init__ is called regardless at app startup) Why does it not call the middleware when the URL is not found in the URLconf? -
Django query for column value search?
What is the Django query for this? DB data - col1 | Col2 ------------------------- sahil1 | Cat 1.2.3 sahil2 | 1.2.3-XY2 sahil3 | 9.8.7,1.2.3,11.12.13 sahil4 | 1.2.3 sahil5 | 9.8.4,1.2.3-XY2,9.8.7 sahil6 | Cat 1.2.3,9.8.2,1.2.3 I only need record that contain "1.2.3" values not like - ("Cat 1.2.3" or "1.2.3-XY2" or any such value). And pattern "1.2.3" can be anywhere in column where column value can have comma separated values too. Desired Result - col1 | Col2 ------------------------- sahil3 | 9.8.7,1.2.3,11.12.13 sahil4 | 1.2.3 sahil6 | 1.2.3-XY2,9.8.2,1.2.3 When i am performing below Django query - col2_count = TableName.objects.filter(col2__contains="1.2.3") Getting all record but i only need record that contain "1.2.3" values not like - ("Cat 1.2.3" or "1.2.3-XY2" or any such value). How do I implement this in Django? -
decode() function is not working "AttributeError: 'str' object has no attribute 'decode'"
Hi I am trying to fix my test case buy decode function is not working this is my code in test Django ```class RefreshView(APIView): serializer_class = RefreshSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) try: active_jwt = Jwt.objects.get( refresh=serializer.validated_data["refresh"]) except Jwt.DoesNotExist: return Response({"error": "refresh token not found"}, status="400") if not Authentication.verify_token(serializer.validated_data["refresh"]): return Response({"error": "Token is invalid or has expired"}) access = get_access_token({"user_id": active_jwt.user.id}) refresh = get_refresh_token() active_jwt.access = access.decode() active_jwt.refresh = refresh.decode() active_jwt.save() return Response({"access": access, "refresh": refresh})``` enter image description here -
Django + React Routes
Hello I have issues with my routes, I am trying to add Root to App.js (frontend) I keep getting Blankpage maybe the issue is minor but really can't find the solution. If i replace Root for BrowserRouter, it displays fine. I want to add Store to my application so that is why I need Root. This is the Code Code Image - APP.JS enter image description hereRoot.JS -
Field specific validation error on ListSerializer
Is there a way to raise field aware ValidationError on validate method of ListSerializer? In my case putted data might contain conflicting records, so I have to validate it. After raising such error it returns Non-field error, but I'd love to return list of validated data, where records are empty {} if everything is fine and records are like {'first_name': 'name must be unique withing request'} -
How to get Django Admin pulldown list to just show the first "order by" item instead of the models.py default?
I am working on a website-builder program. When the user creates a new page, he has to choose a language (English, French, German for example). In Django Admin, in the language admin, the user can set an order. The language model contains: order = models.PositiveSmallIntegerField(default=0, verbose_name='display order') In the page parameters in Django Admin, the user has to choose a language. The page model contains: language = models.ForeignKey(Language, default=0, on_delete=models.PROTECT, verbose_name='language') The problem I have is that when the user creates a new page in Django Admin, language with PK 0 is always selected by default, even though it's not the first in the list. Language 0 is always pre-selected by Django, and the user is unable to set the default language of new pages by setting the display order of the languages. What I want is for Django to stop selecting the 2nd or 3rd item in the pulldown and have it default to the first item like a normal pulldown. I expect that the issue has to do with declaring that the default language is 0 in the page model, but I couldn't get it to work when I removed it. -
Django doesn't see static css files
Faced a problem: django does not see static files. In particular css. Here is the project structure: settings.py (DEBUG = True): STATIC_URL = '/static/' STATICFILES_DIRS = [] STATIC_ROOT = os.path.join(BASE_DIR, "static") aboutus.html {% extends 'mainapp/base.html' %} {% load static %} <html> <head> <link type="text/css" href="{% static 'mainapp/css/aboutus.css' %}" rel="stylesheet" /> # здесь aboutus.css pycharm подчеркивает, ибо не видит </head> <body> {% block title %} О нас {% endblock %} {% block content %} <div id='div1'> <span id='span1'>▼</span> Кто мы такие?</div> <div id='div2'> 1 <span class='span2'>2</span>3 <span class='span2'>4 </span><br> 5 <br> 6 <a href="https://www.youtube.com/watch?v=OWycy6WRv7w">7</a> </div> {% endblock %} </body> </html> aboutus.css : #div1 { font-size: 20px; text-align: center; margin-top: 30px; margin-bottom : 20px } #span1 { font-size: 9pt } #div2 { box-shadow: 0 0 10px rgba(0,0,0,0.5); background-color: rgb(255,255,255); border-radius: 5px; margin-left: 10px; margin-right: 10px; line-height: 2.5; text-align: center; margin-bottom : 20px; border: 1px solid gray } .span2 { color: red } urls.py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) 'django.contrib.staticfiles' in INSTALLED_APPS is. I use mac os. -
Pycharm Community Edition - Django-Admin Command Not Recognized
I cannot start my PyCharm project via the django-admin command. The terminal doesn't recognize it. Details: 1.) I have the package installed in Python. And it is installed in my project. 2.) It seems to be installed 2 levels down from the project directory, in \venv\Scripts. But the command isn't recognized there either. Can anyone help? -
Django - What's the most secure way to pass parameters?
I'm working on an app that handles some sensitive information (API keys, etc). I have a simple question that I cannot find answers to. I have an encrypt function implemented as to not store the data in plain text. Should I be passing the variables back and forth to encrypt/decrypt between functions using return, or using request.session? They both tend to work, but what's more secure? Would it be more secure to call the function and handle the return since that would only process on the backend, or should I use session variables? -
Email not case sensitive in django allauth
How can i set an email as no case sensitive with Django Allauth? I want to save it in lowercase in database but not exist a parameter like ACCOUNT_PRESERVE_USERNAME_CASING. -
Load jquery function in vue from an external file
I am working django integrated with vuejs via webpack loader. In django's "base.html" file all static files are loaded and there is the point where vue is rendered. In vue I have a page where there is a table where all the data is loaded. In the simple html template the table and the people were via the js file that used jquery. With vuejs I can't load it. In base.html: <body class="vertical-layout vertical-menu-modern navbar-floating footer-static " data-open="click" data-menu="vertical-menu-modern" data-col=""> <div id="app"> </div> {% render_bundle 'app' %} <script src="{% static 'dashboard/js/scripts/pages/app-user-list.js' %}"></script> </body> In app-user-list.js: $(function () { ('use strict'); var dtUserTable = $('.user-list-table'), newUserSidebar = $('.new-user-modal'), newUserForm = $('.add-new-user'), select = $('.select2'), dtContact = $('.dt-contact'), statusObj = { 1: { title: 'Pending', class: 'badge-light-warning' }, 2: { title: 'Active', class: 'badge-light-success' }, 3: { title: 'Inactive', class: 'badge-light-secondary' } }; // Users List datatable if (dtUserTable.length) { dtUserTable.DataTable({ ajax: "http://127.0.0.1:8000/static/dashboard/data/user-list.json", // JSON file to add data columns: [ other... The path in the code where ajax requests leads to a file with a list of users. In this way I have loading problems because the file is loaded once if I go through vue on the page where the … -
Using different languages(frameworks) in the same web project [closed]
Please is there a way to work on a project with different languages and their frameworks. For example, I have a to build an e-commerce website with a team of three backend developers One node.js, one django and one laravel The node.js developer is to work on the products section The django developer is to work on user registration and authentication While the laravel developer is to work on the payments system Is there a way the various parts can be linked to work together on the same project? -
Create multiple website templates with django cms or any tool
Can Django be used to create a website for creating custom websites depending on the user needs? There will be more than one template and each user will have a custom url for their websites. I don't know if this can this be achieved with Django CMS. -
Django migration: got relation does not exist or relation already exists errors
I tried to port a Diango app from one server to another and change database engine from sqllite3 to postgres. After I pulled the app from github to the new server and reconfigured database settings for postgres, I got a relation not existing error when I tried to migrate as shown below. $ python manage.py migrate Traceback (most recent call last): File "/data/apps/anaconda3/envs/parts_env/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "parts" does not exist LINE 1: SELECT "parts"."type" FROM "parts" ... But after I created the table in the database and tried again, I got a relation already exists error as shown below. $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, partsdb, sessions Running migrations: Applying partsdb.0001_initial...Traceback (most recent call last): File "/data/apps/anaconda3/envs/parts_env/lib/python3.8/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.DuplicateTable: relation "parts" already exists ... So I'd get the "relation does not exist" error if I dropped the table and I'd get the "relation already exists" error if I created the table. I omitted the tracing outputs which are from Django libraries and very lengthy, but I can supply them if they may help. Thanks. -
Django message + nginx: message showing after 3 times reload !! admin login redirects back to admin login page after giving right credentials
I have built a Django application. It was working fine in the development mode. But I tried to host it in the digital ocean, Every thing worked fine, but when any error message is sent as a response, It doesn't show instantly in the front-end. Weirdly enough, If I reload three times, the error message becomes visible. my nginx configuration: listen 80; server_name <domain name>; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/saadman/<project name>/staticfiles/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } my gunicorn service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=saadman Group=www-data WorkingDirectory=/home/saadman/<projectname> ExecStart=/home/saadman/<projectname>/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ <projectname>.wsgi:application [Install] WantedBy=multi-user.target -
Django Rest Framework - drf-spectacular add extra models to schemas
I used drf-spectacular and have two questions about this module. I wanna create custom Schemas and overwrite Schema in API endpoints. How to do this? I search a way to add custom models to Schemas but without connected this with endpoints. I see that i can add custom Schema by: """ inline_serializer( name='PasscodeResponse', fields={ 'passcode': serializers.CharField(), } ), But don't know where to put this. I wanna just see this in this Schemas like on screen: -
How to change backgrounf color of my HTML/CSS template?
I'm using this simple Boostrap template for a work and I just can't change the background color. I tried to change the background-color value over t my css file, and that has no effect at all. Tried to put the entire index file inside a div with a background-color tag, but my website is still white. Please help. -
Error in Django Model and Serializer - (1048, "Column 'dso_id' cannot be null")
I am trying to create a user profile, I feel i have everything correct but still it doesn't register. You see my codebase below, please help What i did: Models.py: class UserManager(BaseUserManager): def create_user(self, username, email, name, address,roleId,customerId,dso password=None,): if username is None: raise TypeError('User should have a userame') if email is None: raise TypeError('Users should have a Email') user = self.model(username=username , email = self.normalize_email(email)) user.set_password(password) user.save() return user def create_superuser(self, username, email, password=None): if password is None: raise TypeError('User should have a password') user=self.create_user(username,email,password,) user.is_superuser = True user.is_staff = True user.save() return user class User(models.Model): dso = models.ForeignKey(Dso,related_name='dso',default=NULL,blank=False,on_delete=models.CASCADE) name = models.CharField(max_length=70, blank=False, default='') email = models.EmailField(max_length=70, blank=False, default='') password = models.CharField(max_length=70, blank=False, default='') address = models.CharField(max_length=70, blank=False, default='') roleId = models.IntegerField(blank=False, default='1') isActive = models.BooleanField(blank=False, default=True) customerId = models.CharField(max_length=70, blank=False, default='') dateJoined = models.DateTimeField(auto_now_add=False, blank=False, default=NULL) @property def energy_data(self): energydata = EnergyData.objects.filter(customerId=self.customerId).first() return energydata Serializers.py: class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(max_length = 68, min_length=6, write_only = True) class Meta: model=User fields=['email','username','password','name','address','customerId', 'dso', 'roleId'] def validate(self, attrs): email = attrs.get('email', '') username = attrs.get('username', '') if not len(username) >= 4: raise serializers.ValidationError('Username must be morethan 4 letters or characters') return attrs def create(self, validated_data): return User.objects.create_user(**validated_data) Views.py: class RegisterView(generics.GenericAPIView): serializer_class= … -
Is there a way to capture permission change in Django Guardian?
I would like to receive a signal after permission is changed on the object level. Django Guardian allows us to set object-level permissions. Based on the permission change, I'd like to perform some actions. How to receive a signal on object level permission change?