Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create a list view with group by field name and link to details - django admin
So I have the following the following table: class IncomeStatementQuarterly(models.Model): date = models.DateField() statement = models.CharField(max_length=1000, blank=True, null=True) ticker = models.CharField(max_length=1000, blank=True, null=True) security = models.ForeignKey(SecuritiesTable, models.DO_NOTHING) line_item = models.CharField(max_length=1000, blank=True, null=True) amount = models.DecimalField(max_digits=65535, decimal_places=4, blank=True, null=True) class Meta: ordering=('ticker',) verbose_name = "Income statement / Quarterly" verbose_name_plural = "Income statements / Quarterly" managed = False db_table = 'income_statement_quarterly' unique_together = (('date', 'ticker', 'line_item'),) and the following in my admin.py class: @admin.register(IncomeStatementQuarterly) class IncomeStatementQuarterlyAdmin(admin.ModelAdmin): date_hierarchy = 'date' list_filter = ('line_item',) list_display = ("ticker", "date", "statement", "line_item", 'amount') search_fields = ['ticker'] list_display_links = ('ticker',) def has_add_permission(self, request, obj=None): return False def has_delete_permission(self, request, obj=None): return False def has_change_permission(self, request, obj=None) -> bool: return False My goal is to create a view grouped by the 'ticker' and 'date' field. As of right now, my admin view is displaying each rows of my model like so: I want to regroup everything by ticker and date so that I'll have a link that if clicked on, I'll have all the rows based on the given combination of date and ticker. Is this possible? I've been looking everywhere for the past 5 days and I was getting ready to start a new model called statements_list … -
django.db.utils.IntegrityError: UNIQUE constraint failed:
I am making review api with django, but I have a problem. models.py from django.db import models import uuid # Create your models here. from django.utils.text import slugify class buildingData(models.Model): building_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(unique=True, default=uuid.uuid1) building_loc = models.CharField(max_length=50) building_call = models.CharField(max_length=20) building_time = models.CharField(max_length=50) def save(self, *args, **kwargs): self.slug = slugify(self.building_name) return super().save(*args, **kwargs) class reviewData(models.Model): building = models.ForeignKey(buildingData, related_name='reviews', on_delete=models.CASCADE, null=False, blank=False) review_content = models.TextField() star_num = models.FloatField() urls.py from django.contrib import admin from django.urls import path from crawling_data.views import ReviewListAPI from crawling_data.views import BuildingInfoAPI urlpatterns = [ path('admin/', admin.site.urls), path('api/buildingdata/', BuildingInfoAPI.as_view()), path('api/buildingdata/<slug:slug>/', ReviewListAPI.as_view()) ] I am collecting data with crawling, but... django.db.utils.IntegrityError: UNIQUE constraint failed: crawling_data_buildingdata.slug This error occurs. I've tried deleting migrate file and migration again, but still doesn't work. Is there any problem on my code or is there other way to solve this? -
How to handle dynamic byte-struct unpacking and comprehension
During my current project, I have been receiving data from a set of long-range sensors, which are sending data as a series of bytes. Generally, due to having multiple types of sensors, the bytes structures and data contained are different, hence the need to make the functionality more dynamic as to avoid having to hard-code every single setup in the future (which is not practical). The server will be using Django, which I believe is irrelevant to the issue at hand but I have mentioned just in case it might have something that can be used. The bytes data I am receiving looks like this: b'B\x10Vu\x87%\x00x\r\x0f\x04\x01\x00\x00\x00\x00\x1e\x00\x00\x00\x00ad;l' And my current process looks like this: Take the first bytes to get the deviceID (deviceID = val[0:6].hex()) Look up the format to be used in the struct.unpack() (here: >BBHBBhBHhHL after removing the first bytes for the id. Now, the issue is the next step. Many of the datas I have have different forms of pre-processing that needs to be done. F.e. some values need to be ran with a join statement (e.g. ".".join(str(values[2]) ) while others need some simple mathematical changes (-113 + 2 * values[4]) and finally, others needs a simple logic … -
Serve media file on pythonanywhere
I have a web app made with Django. It consists of upload, file processing and download. The download part works with the FileResponse() class, wich takes a binary . I want to run this app on Pythonanywhere. The problem is that, as Django is not meant to serve static/media files, I have to use the Pythonanywhere capabilities, wich provides a Dashboard to serve the files (it maps the file path to a URL). I can see how it is used to serve static files (css or js), wich is the most common case. In their docs they make a very clear example, in wich the URL replaces the file path inside the or tags of the HTML. But in the case of my app, we are talking about a media file wrapped with open() class inside the view function of the view.py file. Do I have to use the URL as the file path passed to open()? Am I scoping this wrong. Please, help me. -
Django total iteration number for nested for loops
Example: django doc cities = [ {'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'}, {'name': 'New York', 'population': '20,000,000', 'country': 'USA'}, {'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'}, {'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'}, {'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'}, ] {% regroup cities by country as country_list %} <ul> {% for country, local_cities in country_list %} <li>{{ country }} <ul> {% for city in local_cities %} <li>{{ city.name }}: {{ city.population }}</li> {% endfor %} </ul> </li> {% endfor %} </ul> How do I get the total iteration number of both inner and outer for loop. forloop.counter and forloop.counter0 return only inner index -
Django - remove items from select while maintaining the original query
I'm wondering if Django has the functionality to remove particular items from a select once they've been added. For example, lets say I have a query that looks like: FooBar.objects.annotate( field_1=field_1, field_2=field_1, field_3=field_1 ).filter( some_filter_set ) would produce SQL like so: select field_1, field_2, field_3 from foo_bar where some_filter_set After the initial query has been made, I'd like to keep this query, and create another copy that is the exact same but distilled down to just field_1 in the select. Does Django give the functionality to directly edit the select? The reason for this is that I have a very large dynamically generated query that needs to be used in a subquery. I'd like to take the final version of the query, copy it, change the select, and use that as the subquery. Thanks! -
How to resolve: NOT NULL constraint failed: bloggo_ipaddress.user_id by trying to store user's ip
i'm trying to use the django framework and to practice i tried to create a blog. What I have programmed seems to work quite well. The only thing I'm trying to do and I can't is adding the ip field to the user (which I created with the standard django mode). For now I'm trying to see if by logging (log in works) the ip is saved in the field that I created but it doesn't work (IntegrityError at /login/... NOT NULL constraint failed: bloggo_ipaddress.user_id), then I would like to make sure that if a user enters with a different ip a message is shown. But in the meantime I would like to understand how to correctly store the ip. This is my forms.py with Log in and Registration forms from django import forms from django.forms import ModelForm, TextInput from django.shortcuts import render, redirect from django.contrib.auth import (authenticate, get_user_model, login, logout,) from django.contrib.auth.models import User from bloggo.models import Post from django.contrib.auth.forms import UserCreationForm, AuthenticationForm User = get_user_model() class AuthenticationForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError('Wrong username or … -
Pyhton package to convert html to image and pdf
I need python package to convert html to image and pdf without depending on wkhtmltopdf/wkhtmltoimage packages. -
Is a Javascript search less secure than using a search client like Sphinx or Elasticsearch?
I have a concept/security question... Looking at the search options for Django, most recommend search databases or docker apps such as sphinx or elasticsearch. However, in my particular case I was able to create a Javascript real time search that functions just as smoothly as the sphinx one on my site and is simply using my already made django postgres models. My questions are: What are the upsides of using a separate app or database over a javascript search? Are there size limitations to Javascript searches? Are there security risks with either option? Thank you! -
Django on virtualenv but failed to run project and import using git-bash
I already installed django using virtualenv on git bash, but always gives me this error. ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Already add PYTHONPATH to environment variable as well. I tried to import django on python idle but it seems didn't work too. Any idea what I am missing? -
'max_number' is not defined using annotation with django
I have that code from django.db.models import Max User.objects.annotate(max_number=Max('number')).filter(number=max_number) # Filter all users by the highest number. And when I execute it I got that error : 'max_number' is not defined Could you help me please ? Thank you very much ! -
PostgreSQL not available: instance=None:None, timeout=30s
I am trying to run the old code of Django 1.x in my local machine, some how this project is used as microservice and make many dependencies on other project, But I want to run it locally on my machine. I set up the virtual environment, errors removed when I start the server this comes always (env) C:\Users\mahad\projects\Hermes\app>python manage.py runserver PostgreSQL not available: instance=None:None, timeout=30s here is my code, where I am connecting database: 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': environ.get('PGHOST'), 'NAME': environ.get('PGDATABASE', 'app'), 'USER': environ.get('PGUSER'), 'PASSWORD': environ.get('PGPASSWORD'), 'PORT': int(environ.get('PGPORT', 5432)), } What will be the error or what I am missing? Kindly ask if any point you want to know about project settings. -
Querying Multiple foreign key relationships in DRF
I am completely new to django and python kindly help me with below query: I have 3 models , with multiple foreign key relations with given sample data now I need 3 outputs via django ORM or Serializers 1.for a given student id ,display the Student details and marks in each subjects 2.list all the students with their total marks (sum of three subjects in this case) 3.Average marks scored by all the students for each subject for ex as per the given sample marks in English are 65 , 95 and average is 80 { Subject :"English", average : " 80" } class Student(models.Model): student_id = ShortUUIDField(primary_key=True, editable=False) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) class Subjects(models.Model): subject_code = ShortUUIDField(primary_key=True, editable=False) subject_name = models.CharField(max_length=100) class Reports(models.Model): student = models.ForeignKey(Student,on_delete=models.CASCADE,related_name='student_report') subject = models.ForeignKey(Subjects,on_delete=models.CASCADE,related_name='subject',default=None) marks = models.IntegerField(max_length='3') class Meta: unique_together = ("student", "subject") sample data Student data student_id first_name last_name 1 abc x 2 def y Subjects data subject_code subject_name 1 English 2 Science 3 Math Reports data student_id subject_id marks 1 1 65 1 2 75 1 3 92 2 1 95 2 2 85 2 3 62 -
how to send two different post request from react to Django rest framework
I am trying to send different types of data via two different POST requests from react using Axios. When I used to work on the normal Django with the template I would do this: html page with jinja2 <form action="." method="POST"> {% csrf_token %} <p><input class="btn btn-info" type="submit" name="join-group" value="Join Group"></p> <p><input class="btn btn-danger" type="submit" name="leave-group" value="Leave Group"> </p> </form> I am able to grab name, which is either join-group or leave-group above and would allow me to get a different type of post request on the same page normal Django views.py def foo(request, id): ... if 'join-group' in request.POST: # do custom action 1 elif 'leave-group' in request.POST: # do custom action 2 ... How can I achieve the result above using react with Axios and Django rest framework backend? Please note that I know how to send just a regular POST request from react to `Django rest, but sending different types on the same page is what I am looking for. -
How to filter in Django and use a method of the class as the condition?
I want to get a queryset that only contains tutors who fulfill minimum requirements. The tutor class has a method "satisfies_min_requirements(self, student) -> bool". It basically figures out whether a tutor is fitting for the student. I have an approach that works, but I think there must be a better way to do it. This is what I have: tutors = Tutor.objects.all() tutors = list(filter(lambda tutor : tutor.satisfies_min_requirements(student), tutors)) Thank you a lot! -
Is generating CSRF token on the front-end a bad idea?
In Django world, CSRF token is generated in a way that doesn't involve any information known only to the server. It's perfectly possible to generate a valid CSRF token in javascript - Django will happily accept it. In particular, we could have a piece of javascript that generates valid CSRF token and setting its value as a cookie. Are there any security related drawbacks of doing that? The only thing I can think of is that such cookie cannot have the http-only flag set (for obvious reasons). -
How to provide translations for django standalone app inside app?
I would want to provide translation texts (makemessages and write translation strings) inside django-standalone app, to make app support multiple languages. How it can be done? Currently, I use from django.utils.translation import gettext to define translation strings. I would not want to run manage.py makemessages command in the parent project and repeat writing translation strings for each parent project. -
Function to restrict access to the page by time
I have a logic: import datetime now = datetime.datetime.now() hour_now = now.hour if 23 < hour_now < 6: *...views logic...* else: *...closed.html...* But I need this logic make in separate function in utils.py def time_close(): But I don't understand how it's do... Help, please. -
Django JSONField complex query ... practical example of querying complex nested data structure
I have inherited the following JSONField data structure: [ { "name": "Firstname", "show": { "value": true }, "type": "text", "uuid": "55668e45-07d1-404e-bf65-f6a3cacfaa97", "label": { "for": "Firstname", "display": "First name" }, "value": "Michael", "options": [], "required": true, "component": "Input", "placeholder": "Input text here", "validationErrors": [] }, { "name": "Surname", "show": { "value": true }, "type": "text", "uuid": "ce91fefa-66e3-4b08-8f1a-64d95771aa49", "label": { "for": "Surname", "display": "Surname" }, "value": "Roberts", "options": [], "required": true, "component": "Input", "placeholder": "Input text here", "validationErrors": [] }, { "name": "EmailAddress", "show": { "value": true }, "type": "email", "uuid": "6012a805-da62-4cee-8656-b7565b5f8756", "label": { "for": "Email", "display": "Email" }, "value": "michael@hiyield.co.uk", "options": [], "required": true, "component": "Input", "placeholder": "Input text here", "validationErrors": [] }, { "name": "University", "show": { "value": true }, "type": "text", "uuid": "434e3781-ab8a-4f09-9c68-5ec35188f3c7", "label": { "for": "University", "display": "University/College" }, "value": "University College London", "options": [], "required": true, "component": "Input", "placeholder": "Input text here", "validationErrors": [] }, { "name": "Subscribe", "show": { "value": true }, "type": "checkbox", "uuid": "79bdc29e-6357-4175-bf65-07be60776a29", "label": { "for": "Subscribe", "display": "Subscribe to the KEVRI mailing list" }, "value": true, "options": [], "required": true, "component": "Checkbox", "description": "KEVRI is committed to respecting and protecting your privacy. The data collected here will create your personalised report which … -
Two Django websites on Windows Apache
I am trying to host two Django websites on Windows (so no WSGIdaemonprocess). When I did host only one of them it worked perfectly. Now it still works (main path "/" named magazyn). But the second one (path "/awizacje" named awizacje) throws an Internal Server Error. Full error message in Apache logs looks like this: C:\A\34\s\Modules\_decimal\libmpdec\context.c:57: warning: mpd_setminalloc: ignoring request to set MPD_MINALLOC a second time [Mon Oct 11 14:57:35.251409 2021] [wsgi:error] [pid 6268:tid 992] [client 192.168.2.54:25532] mod_wsgi (pid=6268): Failed to exec Python script file 'C:/var/www2/awizacje/rootkat/awizacje/wsgi.py'. [Mon Oct 11 14:57:35.251409 2021] [wsgi:error] [pid 6268:tid 992] [client 192.168.2.54:25532] mod_wsgi (pid=6268): Exception occurred processing WSGI script 'C:/var/www2/awizacje/rootkat/awizacje/wsgi.py'. [Mon Oct 11 14:57:35.251409 2021] [wsgi:error] [pid 6268:tid 992] [client 192.168.2.54:25532] Traceback (most recent call last):\r [Mon Oct 11 14:57:35.251409 2021] [wsgi:error] [pid 6268:tid 992] [client 192.168.2.54:25532] File "C:/var/www2/awizacje/rootkat/awizacje/wsgi.py", line 19, in <module>\r [Mon Oct 11 14:57:35.251409 2021] [wsgi:error] [pid 6268:tid 992] [client 192.168.2.54:25532] application = get_wsgi_application()\r [Mon Oct 11 14:57:35.251409 2021] [wsgi:error] [pid 6268:tid 992] [client 192.168.2.54:25532] File "C:\\var\\www\\magazyn\\env39\\Lib\\site-packages\\django\\core\\wsgi.py", line 12, in get_wsgi_application\r [Mon Oct 11 14:57:35.251409 2021] [wsgi:error] [pid 6268:tid 992] [client 192.168.2.54:25532] django.setup(set_prefix=False)\r [Mon Oct 11 14:57:35.251409 2021] [wsgi:error] [pid 6268:tid 992] [client 192.168.2.54:25532] File "C:\\var\\www\\magazyn\\env39\\Lib\\site-packages\\django\\__init__.py", line 19, in setup\r [Mon Oct … -
how to pass input to api from angular forms without formControlName?
I am passing some data from angular to django rest api, Which is as follows first what django need in for api: notice { description: something, classname : in which class notice is provided, students : from dropdown } what I am passing from angular description by formController students by formcontroller now my issue is that I am not taking classname as input because It doesn't make sense here so is there any other way by which I directly pass classname to api as input without showing on UI my angular code: this.announceForm = this._formBuilder.group({ students : [selectedStudents, Validators.required], description: ['', Validators.required] }); here is django's input fields -
Different RAW query results from django.db.connection and cx_Oracle
I executed the following query from my Django project. from django.db import connection balance_query = " SELECT HAOU.ORGANIZATION_ID ORG_ID, CASE WHEN HAOU.ORGANIZATION_ID = 1 THEN 'F' WHEN HAOU.ORGANIZATION_ID = 9 THEN 'R' ELSE HAOU.NAME END COMPANY, BLNCE (HCA.CUST_ACCOUNT_ID, HCASA.ORG_ID, 0) CCL FROM hca, hp, hcasa, hcsua, HAOU WHERE hca.party_id = hp.party_id AND hca.cust_account_id = hcasa.cust_account_id AND hcasa.bill_to_flag = 'K' AND hcasa.cust_acct_site_id = hcsua.cust_acct_site_id AND hcsua.site_use_code = 'AM' AND HCASA.ORG_ID IN (1, 9) AND HAOU.ORGANIZATION_ID = HCASA.ORG_ID AND HCASA.CUST_ACCOUNT_ID = 11211123 ORDER BY 1" with connection.cursor() as cur: cur.execute(balance_query) balance_data = cur.fetchall() print(balance_date) Then I get result after print as (1, 'F', 77259668) (9, 'R', '24153') The bold value is wrong But When I execute same query with following query import cx_Oracle dsn_tns = cx_Oracle.makedsn('host', 'post', service_name='name') conn = cx_Oracle.connect(user=r'user', password='pwd', dsn=dsn_tns) c = conn.cursor() c.execute( " SELECT HAOU.ORGANIZATION_ID ORG_ID, CASE WHEN HAOU.ORGANIZATION_ID = 1 THEN 'F' WHEN HAOU.ORGANIZATION_ID = 9 THEN 'R' ELSE HAOU.NAME END COMPANY, BLNCE (HCA.CUST_ACCOUNT_ID, HCASA.ORG_ID, 0) CCL FROM hca, hp, hcasa, hcsua, HAOU WHERE hca.party_id = hp.party_id AND hca.cust_account_id = hcasa.cust_account_id AND hcasa.bill_to_flag = 'K' AND hcasa.cust_acct_site_id = hcsua.cust_acct_site_id AND hcsua.site_use_code = 'AM' AND HCASA.ORG_ID IN (1, 9) AND HAOU.ORGANIZATION_ID = HCASA.ORG_ID AND HCASA.CUST_ACCOUNT_ID = 11211123 … -
How do I integrate live video processing in Django?
So the issue I am facing is, I am creating an application where students would join a room and stream their live video to the server (It is not necessary for each student to see each other) these live frames are then fed into the AI model which accepts frames and produces an output. How do I tackle this am I suppose to create a whole thread from the room and each thread for the student? How do I tackle live streaming to the server and processing the data? -
Django DRF api does not return any value
I am trying to create my first api using Django rest framework DRF. Here is my code: in views.py : class PostViewSet(viewsets.ModelViewSet): # permission_classes = [IsAuthenticated] @action(detail=True, methods=['GET']) def queryset(self, request, pk=None): try: queryset = Post.objects.get(post_id=pk) except Analysis.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = PostSerializer(queryset) return Response(serializer.data) and in urls.py: router = DefaultRouter() router.register(r'api/post/<int:pk>/post_analysis/', PostViewSet, basename='app_name') urlpatterns = router.urls However this raises an error that The current path, api/post/698/post_analysis/, didn't match any of these. or Not Found: /api/post/698/post_analysis/ But when I change url as follows, it returns none: PostView = PostViewSet.as_view({ 'get': 'retrieve' }) urlpatterns = format_suffix_patterns([ path('api/post/698/post_analysis/', PostView, name='app_name') ]) result is this: { "detail": "Not found." } -
how to make dynamic email template and store in database table in django?
i am working in a project where we need to have html and text email which needed to stored in database. so that we can dynamically change the values in email and send mail to the users. if any one could please suggest me how to do this all, it will be of great help. i am new to django Framework - django, for mail client - AWS ses, boto3