Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix PostgreSQL encode
I am trying to migrate a database from a local computer(Windows, SQLite3) to a server(Ubuntu 20, PostgreSQL). I created a JSON dump from local SQLite3 base. python manage.py dumpdata > dump.json On the server, I enter into the shell and executed the commands from django.contrib.contenttypes.models import ContentType ContentType.objects.all().delete() quit() And when i'm try refill database python manage.py loaddata dump.json The console responds with this UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte I would be very grateful if you could explain to me how to fix the problem. -
scrollHeight yielding inconsistent results
I came with an idea to use top-bottom pagination. My plan was to use hidden class on the bottom paginator element if ListView fits into the user's viewport. Worked fine but accidentally I found out that once per +/- twenty times it just doesn't work. Using console log I noticed that scrollHeight is yielding inconsistent results, viewportHeight on the other hand works like a charm every time. Django template: <!doctype html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Ubuntu:wght@300;400;500;700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="{% static 'styles/elements.css' %}"/> <link rel="stylesheet" href="{% static 'styles/main.css' %}"/> <script defer src="https://unpkg.com/phosphor-icons"></script> <script defer src="{% static 'js/project-list.js' %}"></script> <title>Browse Projects</title> </head> JS file: 'use strict'; const tagFilterForm = document.getElementsByClassName('tag-filter-form')[0]; const paginatorLinks = document.getElementsByClassName('paginator-link'); const paginatorBottom = document.getElementsByClassName('paginator--bottom')[0]; // Prevent from wiping filters during page change: if (tagFilterForm) { for (let i = 0; i < paginatorLinks.length; i++) { paginatorLinks[i].addEventListener('click', function (e) { e.preventDefault() console.log('clicked') const pageNumber = this.dataset.page tagFilterForm.innerHTML += `<input value="${pageNumber}" name="page" hidden>` tagFilterForm.submit() }); } } // Add bottom paginator if doc height > viewport height: const documentHeight = document.documentElement.scrollHeight; const viewportHeight = window.innerHeight; console.log(documentHeight, … -
Django admin panel show ForeignKey data
I'm trying to display more information in a admin panel and can't I have two models with foreign Key I trying show streets list and add to street name City name class Street(models.Model): name = models.CharField(max_length=50, verbose_name='Street') code = models.IntegerField() city = models.ForeignKey('City', on_delete=models.PROTECT, null=True) class Meta: managed = True db_table = 'street' def __str__(self): return self.name + f'({self.city.name})' class City(models.Model): name = models.CharField(max_length=50, verbose_name='City') code = models.IntegerField() class Meta: managed = True db_table = 'city' def __str__(self): return self.name+ f' ({self.code})' -
django.db.utils.OperationalError: could not translate host name "db" to address: Name does not resolve. How to solve this issue?
Can some body help me solve this issue. Why am i getting this error? I have db in .env host and links, network in docker-compose file too. I am not being to figure out where the issue is being raised. Here is my docker-compose file. version: "3.9" volumes: dbdata: networks: django: driver: bridge services: web: build: context: . volumes: - .:/home/django ports: - "8000:8000" command: gunicorn Django.wsgi:application --bind 0.0.0.0:8000 container_name: django_web restart: always env_file: .env depends_on: - db links: - db:db networks: - django db: image: postgres volumes: - dbdata:/var/lib/postgresql environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} ports: - 5430:5432 networks: - django container_name: django_db here is my .env with database settings DB_USER=admin DB_NAME=test DB_PASSWORD=admin DB_HOST=db DB_PORT=5432 DB_SCHEMA=public CONN_MAX_AGE=60 -
AssertionError with assertIn; Django SafeString
I'm looking to understand why a string returned from a template's render_to_string method causes inconsistent testing when testing in a manner using self.assertIn() in the below TestCase. All the strings being checked for pass with the exception of "=question_id_1" and "id=question_id_1". There appears to be an issue adding question_id_1 after the equal sign. What explaination is there for this to fail? https://docs.djangoproject.com/en/3.2/topics/templates/#django.template.loader.render_to_string https://docs.djangoproject.com/en/4.0/ref/utils/#django.utils.safestring.SafeString class SafeString A str subclass that has been specifically marked as “safe” (requires no further escaping) for HTML output purposes. class TestUserQuestionProfileTemplate(TestCase): @classmethod def setUpTestData(cls): tag1 = Tag.objects.create(name="Tag1") tag2 = Tag.objects.create(name="Tag2") user = get_user_model().objects.create_user("ItsNotYou") profile = Profile.objects.create(user=user) cls.question = Question.objects.create( title="Test Question ZZZ", body="Post content detailing the problem about Test Question ZZZ", profile=profile ) cls.question.tags.add(*[tag1, tag2]) cls.template = render_to_string( "authors/questions.html", {"question": cls.question} ) def test_template_profile_questions_listing(self): self.assertIn("=", self.template) <<< pass self.assertIn("id", self.template) <<< pass self.assertIn("question_id_1", self.template) << pass self.assertIn("id=", self.template) <<< pass self.assertIn("=question_id_1", self.template) << fail self.assertIn("id=question_id_1", self.template) << fail The template authors/questions.html is written as: <div id="question_id_{{ question.id }}"> </div> The output of self.template in the test returns: <div id="question_id_1"> </div> As the test is ran, it returns the following assertion errors: self.assertIn("=question_id_1", self.template) AssertionError: '=question_id_1' not found in '\n<div id="question_id_1">\n\n</div>\n' self.assertIn("id=question_id_1", self.template) AssertionError: 'id=question_id_1' not found … -
Simulate CSRF attack in Django
I'm trying to get an understanding of how CSRF tokens work, currently my goal is to create a situation where the CSRF attack is possible. I'm hosting two Django apps locally on different ports. I access one by localhost:8000, the other by 127.0.0.1:5000 -- that ensures cookies are not shared between apps. There's an API view class ModifyDB(APIView): def post(self,request,format=None): if request.user.is_authenticated: return Response({'db modified'}) else: return Response({'you need to be authenticated'}) which shouldn't be accessed by unauthenticated users. The "malicious" site has a button that's supposed to trigger the attack when a user is logged on the target site: const Modify = () => { const onClick = async e => { e.preventDefault(); const instance = axios.create({ withCredentials: true, baseURL: 'http://localhost:8000', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', } }) const res = await instance.post('/api/modifydb'); return res.data } return ( <button class = 'btn' onClick = {onClick}> send request </button> ) } My authentication settings are as follows: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'my_proj.settings.CsrfExemptSessionAuthentication', ], } where CsrfExemptSessionAuthentication is a custom class that disables csrf protection for my educational purposes: class CsrfExemptSessionAuthentication(SessionAuthentication): def enforce_csrf(self, request): return django.middleware.csrf.CsrfViewMiddleware is also disabled. Both CORS_ALLOW_ALL_ORIGINS and CORS_ALLOW_CREDENTIALS are set to true. My first … -
Django prefetch_related nested models
I want to do a 3 lvl prefetch_related but I can't make it work. views.py: queryset = obj.answer.all().prefetch_related(Prefetch('question ', queryset=Question.objects.prefetch_related(Prefetch('orderedquestion', queryset=OrderedQuestion.objects.prefetch_related('select_set'))))) return AnswerSerializer(queryset, many=True).data And on my Serializers.py I call it like that: json['name'] = answer.question.orderedquestion.select_set.get(id=i).name I don't know if this metters but my OrderedQuestion class inherits from Question. How can I fetch select_set on the first query so my serializer stop doing N queries for each object? Thank you so much for the help. -
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?