Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to improve the structure of my django project?
Oops good night, recently I started studying django and I came across the problem of structuring the project. Using the codes as an example (suppose you have 1 billion business rules there), I rewrote the user model (user, works perfectly), created a custom manager custom queryset, views (which already comes in startapp) and created a service (another name for "put the business rule"). And my doubts are: 1 ° - Is this basic structure correct? 2 ° - What could I change to further improve the structure of the project? 3 - What is the best way to call my services? static method, instance or class method? 4 - Is it better to put the services of each application in class or to separate everything into functions? 5 ° - If I have a function call from a service view and this function calls another internal function, is it better to instantiate a class to be able to call the functions with the self or to position the function above the other to be able to call? models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db.models import Q from .manager import UserManager class User(AbstractBaseUser): REQUIRED_FIELDS = ['name', … -
Can I use a custom Django manager on a given set of objects?
I have some queryset logic that I would be happy to have in a Manager. I already have the objects in an existing queryset, and I would just like to reorder them. I am thinking of doing something like this: class WorkdayManager(Manager): def ordered_by_time_available(self, object_set): results = object_set.annotate( remaining=F('duration') - F(Coalesce((Sum('record__minutes_planned'), 0)))) return results.order_by(['-remaining']) And I would like to use it like this: object_set.ordered_by_time_available() Would this work? Or should I be using something different? -
django JSONField doesn't accept value
I add a JSONField for one of my models. I want to create an instance of that model in admin panel but that JSONField returns a validation error (Enter a valid JSON.) how I can fix this?? model: class Product(models.Model): category = models.ManyToManyField(Category, related_name='products') name = models.CharField(max_length=500) slug = models.SlugField(max_length=500, allow_unicode=True, unique=True) image_1 = models.ImageField(upload_to='products_pic/%Y/%m/%d/', null=True, blank=True) description = models.TextField(null=True, blank=True) attribute = models.JSONField(default={}) price = models.PositiveIntegerField() discount = models.PositiveIntegerField(null=True, blank=True) available = models.BooleanField(default=True) popular = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) comments = GenericRelation(Comment) class Meta: ordering = ('-created',) def __str__(self): return self.name I add products in admin panel this is the error: -
Django annotate field in different model for union
I'm trying to do a union for two tables: from django.db import models class Base(models.Model): id = models.BigAutoField() created = models.DateTimeField(auto_now_add=True) class Meta: abstract = True class A(Base): ... class B(models.Model): id = models.BigAutoField() title = models.CharField(max_length=255) class C(Base): parent = models.ForeignKey(B, on_delete=CASCADE) And I want to do a union on models A and C while grabbing the attributes of model B: _values = ["id", "parent_id", "parent__title"] A.objects.annotate(parent_id=models.Value(-1, output_field=models.BigIntegerField()), models.Value("", output_field=models.CharField()) ).values(*_values).union(B.objects.values(*_values)).order_by("-created")[:5] But in Postgres 12, Python 3.8, Django 3.1.3, I'm getting this error: django.db.utils.ProgrammingError: UNION types character varying and bigint cannot be matched If you'd like me to get the SQL statement for this, I'd be happy to use Django's SQL compiler to do so. The above was just a demonstration. -
How to create a rating user django
this is the question. I have a mini blog and user profiles. On the user profiles page, I display information: Comments count of this user; Posts count of this user; I display the number of comments in the template userprofile like this: {{comments.count}} I would like to make a small rating system, for example: If a user has left 10 comments and 10 posts - he is a cat. If 20 is a dog. 30 - elephant, etc. For this I would like to have a separate table in the database, so that I can then make a selection by users rating. How can I implement this? Help me pls -
Cannot connect to local database in SQL Server with django 3.1.4
I'm trying to connect to local database with django and I've got this error: django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') My connection string is: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'HOST': '127.0.0.1\MSSQLSERVER', 'NAME': 'RTLLTR', 'USER': '', 'PASSWORD': '', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, }, -
Django ORM Select Column From Two Model or More
I want select column with django orm from two model or more. SELECT nim, k.kode, s.nama, sks, nilai, th_ajaran FROM mahasiswa_khs k, mata_kuliah_si s WHERE k.kode = s.kode AND nim = %s This is my code khs = Khs.objects.filter(nim=nim).values_list('kode').union(SI.objects.all().values_list('kode')) But, went I call in template it's didn't show -
HOST_NAME is 127.0.0.1 (gunicorn via Apache)
I managed to get gunicorn running behind Apache: <Location /foo/> ProxyPass unix:/run/gunicorn-foo.sock|http://127.0.0.1/ ProxyPassReverse unix:/run/gunicorn-foo.sock|http://127.0.0.1/ </Location> Everything works, except ALLOWED_HOSTS checking. The HTTP_HOST is always 127.0.0.1 How to pass the HTTP_HOST to gunicorn? Apache/2.4.46 (Debian) BTW: I would prefer Nginx, but that's not possible in this case. -
Django qyery to join data from two models without primary or forign key
I'm lerning Django, so farso good, however i stuck with get_query(self) function. I have two models in django no forign in tables: class Airport(models.Model): ID = models.AutoField() Name = models.CharField() City = models.CharField() ICAO = models.CharField() class Airport_Frequency(models.Model): ICAO = models.CharField()) ATC_Type = models.CharField() Frequency_MHz = models.DecimalField() Now I want to create a listview but i want to join tables field Airport.name and Airport_Frequency.ICAO to show in frequency list - sql statement: SELECT DISTINCT a.ICAO, b.ICAO, b.Name FROM airport as b, airport_frequency as a WHERE a.ICAO = b.ICAO View: class Airport_FrequencyListView(ListView): model = Airport_Frequency How to refer in the Airport_FrequencyListViewview above to another model? -
<ul class="errorlist"><li>eauthor<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
I am building a CRUD app on Django. I can create, read, and delete just fine, but the update function does not work. I have edited the views.py file (it was a template) to print the error. Here are the relevant pieces of my code: #models.py from django.db import models class Item(models.Model): id = models.AutoField(primary_key=True) etype = models.CharField(max_length=100) etitle = models.CharField(max_length=100) eauthor = models.CharField(max_length=100) estatus = models.CharField(max_length=20) class Meta: db_table = "Item" #views.py ... def edit(request, id): item = Item.objects.get(id=id) return render(request,'edit.html', {'item':item}) def update(request, id): item = Item.objects.get(id=id) form = ItemForm(request.POST, instance = item) print(form.errors) if form.is_valid(): try: form.save() except Exception as e: print(e) return redirect("/items/show") return render(request, 'edit.html', {'item': item}) ... I guess the problem has to be in edit.html file, but I cannot figure it out. #edit.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Index</title> {% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}"/> </head> <body> <form method="POST" class="post-form" action="http://127.0.0.1:8000/items/update/{{item.id}}"> {% csrf_token %} <div class="container"> <br> <div class="form-group row"> <label class="col-sm-1 col-form-label"></label> <div class="col-sm-4"> <h3>Update Details</h3> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Type:</label> <div class="col-sm-4"> <input type="text" name="etype" id="id_etype" required maxlength="100" value="{{ item.etype }}" /> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Title:</label> <div class="col-sm-4"> … -
adding a django format to messages
i am trying to add to my messages.success the username so when he login the message go up and have the username views.py: def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username and password: user = authenticate(username=username, password=password) if user is not None: l_login(request, user) success_url = '/home' messages.success(request, 'You logged in to ') return redirect('home') else: messages.error(request, 'Username or Password is Incorrect') else: messages.error(request, 'Fill out all the Fields Please') return render(request, 'register/login.html',{}) -
grunt-contrib-uglify@0.2.7 requires a peer of grunt@~0.4.0 but none is installed. You must install peer dependencies yourself
Hello everyone I am getting the below error. Does anyone know how to fix it npm WARN grunt-contrib-uglify@0.2.7 requires a peer of grunt@~0.4.0 but none is installed. You must install peer dependencies yourself. When I did Npm INstall I got the below error added 1608 packages from 1128 contributors and audited 1615 packages in 75.474s 61 packages are looking for funding run `npm fund` for details found 3 vulnerabilities (1 low, 1 moderate, 1 high) run `npm audit fix` to fix them, or `npm audit` for details So I did npm audit fix 62 packages are looking for funding run `npm fund` for details fixed 0 of 3 vulnerabilities in 1674 scanned packages 3 vulnerabilities required manual review and could not be updated In the npm WARN. I get the below errors npm WARN grunt-contrib-uglify@0.2.7 requires a peer of grunt@~0.4.0 but none is installed. You must install peer dependencies yourself. Cab Anyone help me fix this. please advise -
'RequestSite' object has no attribute 'root_page'
I have an issue where trying to set up wagtail with nginx and gunicorn. Running the django server on a gunicorn socket fails and get a 502 error at 'website.com/'. but when I execute manage.py runserver on localhost I get 'RequestSite' object has no attribute 'root_page' at 'website.com/local' My settings are below. What am I doing wrong? NGINX upstream app_server { server unix:/etc/systemd/system/gunicorn.sock fail_timeout=0; } server { listen 80; server_name mywebsite.com; keepalive_timeout 5; location /static/ { alias /home/user/static/; } location /media/ { alias /home/user/media/; } location /local/ { include proxy_params; proxy_pass http://localhost:8000; } location / { include proxy_params; proxy_pass http://app_server; } } GUNICORN [Unit] Description=gunicorn Requires=gunicorn.socket After=network.target [Service] Type=simple PIDFile=/run/gunicorn.pid User=user Group=user EnvironmentFile={{etcdir}}/gunicorn.env WorkingDirectory={{projdir}}/ ExecStart={{projdir}}/venv/bin/gunicorn --config {{etcdir}}/gunicorn.conf.py --chdir /home/user/project project.wsgi:application ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s TERM $MAINPID [Install] WantedBy=multi-user.target gunicorn.conf.py workers = 2 pythonpath = '/home/user/venv/bin/python3' syslog = True bind = ['unix:/etc/systemd/system/gunicorn.sock','127.0.0.1:8000',] umask = 0 loglevel = "info" user = "user" group = "user" PRODUCTION.PY DEBUG = False ALLOWED_HOSTS = ['*',] SITE_ID = 1 SECRET_KEY = os.environ['SECRET_KEY'] MEDIA_ROOT = "/home/user/media" STATIC_ROOT = '/home/user/static' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['DB_NAME'], 'USER': os.environ['DB_USER'], 'PASSWORD': os.environ['DB_PASS'], 'HOST': '127.0.0.1', 'PORT': '5432', } } -
Headstart to python Django for freshers
I am a fresher graduated in 2016 from affiliated anna university college. I have basic knowledge on web development including javascript, html, css. I am learning python and python django at the moment. Need suggestion on how to start with Python Django. -
ModuleNotFoundError: No module named 'learning_logs/urls'
I'm learning python, I'm reading a book called python crash course and I'm stuck somewhere, it gives this error: ModuleNotFoundError: No module named 'learning_logs/urls' this is my main url file and in the learning_log/url I have the following: I saw many people complaining about the problem but I couldn't find a solution! -
create validator with objects in django
i want to create a validator in a model and get every same name in that model. my try: def unique_value(objects): def innerfn(value): for title in objects.all(): if title == value: raise ValidationError("This title already exists") return innerfn my model: class Tag(models.Model): name = models.CharField(max_length=100, verbose_name="tag name:", validators=[unique_value(objects)]) the error (on the makemigrations): NameError: name 'objects' is not defined I can not use unique = True because it mixes with my other models and raise error with other model -
Reuse the django form request
I have a page that displays a report according to the informed criteria, within that same page I would like to create a "send by email" button, how could I do to take advantage of the same request? -
Django lookup_expr for arrayfield not matching exact string
I have a djago array field, names = ArrayField( CICharField(max_length=255), blank=True, null=True, help_text="Additional names of the person.", ) It has names, "names": [ "Adam Bender", "April Watkins", "Daniel Brooks", "George Booker" ] When I do, names = django_filters.CharFilter(lookup_expr="icontains") and search for "Adam Bender" it matches the record. But when I search for "Adam Bend" then also it is matching. I don't want that to happened. It should match exact name. I tried iexact but it did not work. Please advise. -
Custom HTML renderer returning empty page
I have this custom HTML renderer using Django Rest Framework: from rest_framework.renderers import TemplateHTMLRenderer class CustomHTMLRenderer(TemplateHTMLRenderer): def renderer_context = renderer_context or {} view = renderer_context['view'] request = renderer_context['request'] response = renderer_context['response'] if response.exception: template = self.get_exception_template(response) else: template_names = self.get_template_names(response, view) template = self.resolve_template(template_names) context = self.get_template_context({'content': data}, renderer_context) return template.render(context) And this is my view for a search carried out on my Solr server: import os from django.conf import settings from rest_framework.generics import GenericAPIView from rest_framework.response import Response from rest_framework.renderers import JSONRenderer from rest_framework.pagination import LimitOffsetPagination import collections from collections import OrderedDict from rest_framework.settings import api_settings import scorched from scorched.strings import DismaxString from bassculture.renderers.custom_html_renderer import CustomHTMLRenderer class SearchResultsPagination(LimitOffsetPagination): def get_paginated_response(self, data): self.solr_response = data['solr_response'] self.offset = self.solr_response.result.start self.limit = len(data['records']) self.count = self.solr_response.result.numFound self.request = data['request'] resp = Response(OrderedDict([ ('count', self.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data['records']), ('facets', self.solr_response.facet_counts.facet_fields), ('params', self.solr_response.params), ('highlighting', self.solr_response.highlighting), ('limit', self.limit), ])) return resp class SearchViewHTMLRenderer(CustomHTMLRenderer): template_name = "search/search.html" class SearchView(GenericAPIView): renderer_classes = [JSONRenderer, SearchViewHTMLRenderer] pagination_class = SearchResultsPagination def get(self, request, *args, **kwargs): querydict = request.GET offset = querydict.get('offset', 0) fcq = {} for f in settings.SEARCH_FACETS: if querydict.get(f, None): fcq[f] = querydict.get(f) fq = {} if querydict.get('fq'): fq = querydict.get('fq') else: fq = '*' … -
Django loops infinitly after startapp method call
I'm doing the CS50Web course, and there is a Django project in which I want to create a new app called "wikipedia". The problem is that after I run this command in Windows PowerShell: python manage.py runserver this loop happens: loop print I don't know what I did wrong for that to happen. After running python manage.py startapp wikipedia , I: went to my Django project and added 'wikipedia' in the installeds apps in settings.py went to urls.py and added a path like this: path("wiki/", include("wikipedia.urls)) And then I tried running the server. What did I do wrong? -
How can I get pdf2image working on Heroku?
I have added multiple buildpacks: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku-community/apt.tgz https://github.com/survantjames/heroku-buildpack-poppler.git https://github.com/amitree/heroku-buildpack-poppler I even tried the xpdfrc buildpack but I still can't get it to work. This is the error: pdfinfo: error while loading shared libraries: libpng12.so.0: cannot open shared object file: No such file or directory -
How to make multiple updates with different values
Please, how do i create a form that returns a list for all name attributes in the form. I have a form that has multiple of the same inputs. How do i make it POST data so that in my views i can do something like... name = request.POST.getlist('name') I need this help. -
Query with annotated aggregation over the same model
I have the following models: class P(models.Model): name = models.CharField(max_length=30, blank=False) class pr(models.Model): p = models.ForeignKey(P, on_delete=models.CASCADE, related_name='cs') r = models.CharField(max_length=1) c = models.ForeignKey(P, on_delete=models.CASCADE, related_name='ps') rc = models.PositiveSmallIntegerField() class Meta: unique_together = (('p', 'c'),) and the data: "id","name" 69,"Hunter" 104,"Savannah" 198,"Adrian" 205,"Andrew" 213,"Matthew" 214,"Aiden" 218,"Madison" 219,"Harper" --- "id","r","rc","c_id","p_id" 7556,"F",1,219,213 7557,"M",1,219,218 7559,"H",3,218,213 7572,"F",1,214,213 7573,"M",1,214,218 7604,"F",1,198,213 7605,"M",1,198,218 7788,"H",3,104,205 7789,"F",1,104,213 7790,"M",1,104,218 7866,"M",1,69,104 7867,"F",1,69,205 For a pr model instance I need to find in how many rows the associated p_id exists. These queries generate the intended result: ro = pr.objects.get(pk=7604) cntp = pr.objects.filter(Q(p = ro.p) | Q(c = ro.p)).count() The above queries will hit the database 2 times, I want to hit the database one time so I wrote this query: ro = pr.objects.filter(pk=7604).annotate(cntp=Subquery(pr.objects.filter(Q(p = OuterRef('p')) | Q(c = OuterRef('parent'))).count())) That query generates error "This queryset contains a reference to an outer query and may only be used in a subquery." so used the method mentioned in Simple Subquery with OuterRef: ro = pr.objects.filter(pk=7604).annotate(cntp=Subquery(pr.objects.filter(Q(p = OuterRef('p')) | Q(c = OuterRef('c'))).annotate(count=Count('pk')))) Again this query generates another error "subquery must return only one column"! Can Django ORM be used to generate the intended results? Environment:Django Version: 3.0.4 Python version: 3.7.3 Database:PostgreSQL 11.9 (Debian 11.9-0+deb10u1) on … -
How could I ,,split'' a set of values from html button?
Let's suppose i'm sending a set of values in html (with value="{{ q }}") and i want to open this set in django view and then save them into another model? How could I do this? (those commented out lines are what I thought would work) <form action="." method="post"> {% for q in questions_data %} <ul> <li>{{ q.question }}</li> </ul> {% csrf_token %} <button type="submit" name="answerButton" value="{{ q }}">{{ q.answer1 }}</button> <button type="submit" name="answerButton" value="{{ q }}">{{ q.answer2 }}</button> {% endfor %} </form> views if request.method == 'POST': #question_id = interest = request.POST.get('answerButton') answered = UserInterest() #answered.selectedInterest = interest['selectedInterest'] #answered.q_id = interest['q_id'] answered.save() return render(request, 'account/dashboard.html', {'section': 'dashboard'}) -
How to retrieve index number from a 'for' loop of a dict in Django Views
I am trying to get the index number of {% for p in mydict_1 %} so that I can use that index on another dict to get the value. How to do this within Django Views? Data from both dicts corresponds to the index in a series. mydict_1 = [{'itemCode': 'AZ001', 'price': 15.52}, {'itemCode': 'AB01', 'price': 31.2}, {'itemCode': 'AP01', 'price': 1.2}] #list of dict mydict_2 = [{'prop': 'val000'}, {'prop': 'val008'}, {'prop': 'val009'}] #list of dict {% for p in mydict_1 %} <tr> <td><a>{{p.itemCode}}</a></td> <td><a>{{p.price}}</a></td> #Want to use p's index number to get value of that index from mydict_2 <td><a>{{mydict_2.[p].prop}}</a></td> #How to do this correctly? Expecting val000 for index 0 </tr> {% endfor %}