Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: User() got an unexpected keyword argument 'is_staff'
I'm newbie with django. I want to create an login, signup API so I find a solution on Internet. But it's not user my own User model, it use django.contrib.auth.models import AbstractUser. I don't need some field of AbtractUser so I give it =none. Here is my models code: from django.db import models from django.contrib.postgres.fields import ArrayField from django.contrib.postgres.fields import JSONField from django.contrib.auth.models import AbstractUser # Create your models here. # class User(models.Model): # name = models.CharField(null=False,blank=False, max_length=512) # username = models.CharField(null=False,blank=False, max_length=512, unique=True) # email = models.EmailField(null=False,blank=False, max_length=512, unique=True) # password = models.CharField(null=False,blank=False, max_length=512) # status = models.CharField(null=True,blank=True, max_length=512) # role = models.IntegerField(null=False, blank=False, default=1) # USERNAME_FIELD = 'username' # REQUIRED_FIELDS = [] # def __str__(self): # return self.username class User(AbstractUser): last_login = None is_staff = None is_superuser = None first_name = None last_name = None name = models.CharField(null=False,blank=False, max_length=512) username = models.CharField(null=False,blank=False, max_length=512, unique=True) email = models.EmailField(null=False,blank=False, max_length=512, unique=True) status = models.CharField(null=True,blank=True, max_length=512) role = models.IntegerField(null=False, blank=False, default=1) USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] def __str__(self): return self.username class Category(models.Model): title = models.TextField(null=False, blank=False) description = models.TextField(null=False, blank=False) class Question(models.Model): title = models.TextField(null=False, blank=False) description = models.TextField(null=False, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) choices = models.JSONField(null=False, blank=False) answer = … -
Javascript - Uncaught ReferenceError: $ is not defined
I trying to use date range picker in JavaScript in Django where I have a date field from the django model. i want to override using the daterange picker but I'm getting a error.Though i have added the jquery cdn as well. error jquery-3.6.0.min.js:2 jQuery.Deferred exception: $(...).daterangepicker is not a function TypeError: $(...).daterangepicker is not a function at HTMLDocument.<anonymous> (http://localhost:1700/:646:34) at e (https://code.jquery.com/jquery-3.6.0.min.js:2:30038) at t (https://code.jquery.com/jquery-3.6.0.min.js:2:30340) undefined S.Deferred.exceptionHook @ jquery-3.6.0.min.js:2 t @ jquery-3.6.0.min.js:2 setTimeout (async) (anonymous) @ jquery-3.6.0.min.js:2 c @ jquery-3.6.0.min.js:2 fireWith @ jquery-3.6.0.min.js:2 fire @ jquery-3.6.0.min.js:2 c @ jquery-3.6.0.min.js:2 fireWith @ jquery-3.6.0.min.js:2 ready @ jquery-3.6.0.min.js:2 B @ jquery-3.6.0.min.js:2 jquery-3.6.0.min.js:2 Uncaught TypeError: $(...).daterangepicker is not a function at HTMLDocument.<anonymous> ((index):646) at e (jquery-3.6.0.min.js:2) at t (jquery-3.6.0.min.js:2) html <div> Due Date</div> <div class="row" id='id_row' name="daterange"> <!-- From: <input type="date" name='fromdate'> To: <input type="date" name='todate'> --> {{ form.due_Date}} </div> <p></p> <script> $(function() { $('input[name="daterange"]').daterangepicker({ opens: 'left' }, function(start, end, label) { console.log("A new date selection was made: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD')); }); }); </script> -
How to authenticate user by the Microsoft Active Directory (AD) in Django app
according to this article: django-auth-ldap installation not working I want to ask you, how to transform this code for Microsoft Active Directory auth. It's for OpenLDAP. I want to only authenticate user by username and password from AD with django-python3-ldap modul without anymore mapping. Thanks!!! -
"Invalid Date format. It must be YYYY-MM-DD" -- Django Rest Framework
I am trying to redefine Django's Restframework default Date input type from YYYY-MM-DD to DD-MM-YYYY, while any post request is sent from frontend. I tried with postman to test the scenarios but Django is only accepting it without YYYY-MM-DD format I followed the doc tried to set settings.py with with configs like 1. REST_FRAMEWORK = { "DATE_INPUT_FORMATS": ["%d-%m-%Y"], } REST_FRAMEWORK = { "DATE_INPUT_FORMATS": [("%d-%m-%Y")], } But nothing seems to work. Please someone help, its like Iam stuck here. -
Django queryset with left join?
Suppose I have from django.db import models class Obj(models.Model): obj_text = models.CharField(max_length=100) class ObjAnnot(models.Model): obj = models.ForeignKey(Obj, on_delete=models.CASCADE) annot_text = models.CharField(max_length=100) I want to efficiently get all Obj objects with zero associated ObjAnnot instances. I could iterate over all Obj instances and query how many associated ObjAnnot instances there are, but that seems quite inefficient. In SQL, I would do a left outer join, and pick the rows with objannot.id null. How can I do that with the Django ORM? EDIT: Possible duplicate question. -
REST Django - filter with multiple variables
I know you can do something like : if Test.objects.filter(id = 2).exists(): #do something But with my attempt of using two variables, it does not work properly. I have a table with two Foreign keys to a User and a Project. I want to see if a specific combination exists. This attempt is what I tried but does not work. if Test.objects.filter(user = User, project = Project).exists(): #do something Maybe I just implemented it wrong ? my whole line is this. I get username and projectid by POST in the request.data if Userproject.objects.filter(user= User.objects.get(username = request.data.get('username',0), project = Project.objects.get(id = request.data.get('projectid',0)).exists(): -
Why is unmanaged model not calculating id in Django?
I have an unmanaged model in Django: class Person(models.Person): name = models.CharField(max_length=200) class Meta: managed = False db_table = '"public"."person"' Somewhere in my tests, I try to create a Person entry in the DB: person = Person(name="Ariel") person.save() But then I get an error: django.db.utils.IntegrityError: null value in column "id" of relation "person" violates not-null constraint DETAIL: Failing row contains (null, Ariel). Outside tests, everything works fine. In the tests, I initialize the DB with the tables referenced by the unmanaged by loading a schema dump. The Django docs states that "no database table creation, modification, or deletion operations will be performed for this model", and that "all other aspects of model handling are exactly the same as normal", including "adding an automatic primary key field to the model if you don’t declare it". But doesn't that mean this code should work? How come Django and Postgres are not taking care of the id? Am I doing something wrong? How can I fix it? -
Prefetching model with GenericForeignKey
I have a data structure in which a Document has many Blocks which have exactly one Paragraph or Header. A simplified implementation: class Document(models.Model): title = models.CharField() class Block(models.Model): document = models.ForeignKey(to=Document) content_block_type = models.ForeignKey(to=ContentType) content_block_id = models.CharField() content_block = GenericForeignKey( ct_field="content_block_type", fk_field="content_block_id", ) class Paragraph(models.Model): text = models.TextField() class Header(models.Model): text = models.TextField() level = models.SmallPositiveIntegerField() (Note that there is an actual need for having Paragraph and Header in separate models unlike in the implementation above.) I use jinja2 to template a Latex file for the document. Templating is slow though as jinja performs a new database query for every Block and Paragraph or Header. template = get_template(template_name="latex_templates/document.tex", using="tex") return template.render(context={'script': self.script}) Hence I would like to prefetch script.blocks and blocks.content_block. I understand that there are two methods for prefetching in Django: select_related() performs a JOIN query but only works on ForeignKeys. It would work for script.blocks but not for blocks.content_block. prefetch_related() works with GenericForeignKeys as well, but if I understand the docs correctly, it can only fetch one ContentType at a time while I have two. Is there any way to perform the necessary prefetching here? Thank you for your help. -
Django Table forward fill missing values
I have a table like this: A B a row row row row b row row row c row ... .... How can I fill in missing values like forward fill in Pandas data frame using Django ORM query? -
How to add the previous/next value of a filter_gt or filter_lt?
I have an array with several values including a date_time. With the django-url-filters module, I filter by this date_time. I can for example put in the url: https://URL/myws/?date_time__lte=2021-10-21T16:00:00&date_time__gte=2021-10-20T16:00:00 My problem is that I need a minimum and maximum value. For example, if in my database, I have 5 objects: [ { date_time: 2021-10-01T00:00:00, id: 1 ... }, { date_time: 2021-10-02T00:00:00, id: 2 ... }, { date_time: 2021-10-06T00:00:00, id: 3 ... }, { date_time: 2021-10-10T00:00:00, id: 4 ... }, { date_time: 2021-10-20T00:00:00, id: 5 ... } ] If I pass in my request the following parameters: date_time__lte=2021-10-08T00:00:00&date_time__gte=2021-10-03T00:00:00 The result is : [ { date_time: 2021-10-06T00:00:00, id: 3 ... } ] But I would like to have the previous value at date_time__gte and the next value at date_time__lte. The goal is to be sure to have a value for the whole period chosen in parameter. So I have to get: [ { date_time: 2021-10-02T00:00:00, id: 2 ... }, { date_time: 2021-10-06T00:00:00, id: 3 ... }, { date_time: 2021-10-10T00:00:00, id: 4 ... } ] Of course, I can't change the date of my previous value by the day - 1 because I don't know in advance the period between 2 values. My function: … -
Weird errors installing django-heroku for python
Although I'm not sure it is important, I will prefix by saying that I started working on a Heroku app on my old computer and am continuing on my new one. After a lot of struggling I finally managed to get the app to build on Heroku, although it didn't run. Perhaps the reason was because Heroku doesn't host static files so I set up an Azure account to do that and made some changes to settings.py and created a custom_azure.py file. After running "git push heroku main" it failed to build because it said that django-heroku was not found. Running "pip install django-heroku" resulted in a many errors. Then "pip freeze" shows that "django-heroku 0.0.0" is installed. Running "pip install --upgrade django-heroku" resulted in the same errors. It is so long I can't post it here so here's a link to a google doc: https://docs.google.com/document/d/17eQUC3Zd4YKq1vt4jObSV9s7MzoHjBy7jbfCerMlzT0/edit?usp=sharing I can't make sense of it. -
Django automatic file-upload: [WinError 123] The filename, directory name, or volume label syntax is incorrect C:\\path\to\folder\C:
I'm pretty new to Django and I'm working on a project in which I have to automate PDF file uploads from a given folder to a model in Django and these files will undergo a text extraction process. I wrote a script to monitor the folder and upload new files to database. The django model looks like this: class Version(models.Model): id = models.AutoField(primary_key = True) file = models.FileField(upload_to = history_directory_path, db_column = 'file', max_length = 500) filename = models.CharField(default = '', max_length = 100, db_column = 'filename') date = models.DateTimeField(auto_now_add = True, db_column = 'date) version_num = models.IntegerField(null = True, blank = True) history_directory_path is a function which creates the folder using the filename and its version number. A piece of my automatic upload script (in this example only for 1 file, I will put it in a loop when it starts working) is the following: from django.core.files import File from myapp.models import Version import os import glob BASE_PATH = r'C:\path\to\folder_to_be_monitored' files = [os.path.basename(x) for x in glob.glob(BASE_PATH + '/*.pdf')] filename = files[0] f = open(os.path.join(BASE_PATH, filename), 'rb') my_file = File(f) version = Version(file = my_file, filename = filename, version_num = 1) version.save() executing the last command I get OSError: … -
How to save matplotlib animations as BytesIO and embed them in a Django website?
I want to save my Matplotlib animation (gif file) as BytesIO. I want to then call the gif onto my HTML webpage in my Django project. For static images (static Matplotlib graphs), what I do is bytesio = io.BytesIO() fig.savefig(bytesio,format='png') bytesio.seek(0) string = base64.b64encode(string) uri = urllib.parse.quote(string) I shall have in my views.py return render(request, 'index.html',{data:uri}) and in my HTML page I have <imag src = "data:image/png;base64,{{data}}"> But I don't know how to implement a similar strategy for animations (gif files). My animations are generated using Matplotlib FuncAnimation. Thanks in advance for any/all responses! -
passing querystring in DRF action
I am trying to fetch some data from a url that (optionally)contains a query string. Here's a snippet of my code: class MyViewSet(ModelViewSet): queryset = models.Me.objects ... ... @action(detail=False, methods=['get'], url_path='someurl(?:/(?P<colour>[^/]+))?')) def some_url(self, request, id): colour = request.GET.get('colour') obj = self.get_object() url = settings.MY_URL if colour: url = url + f'?{colour}' result = requests.get(url) return Response(status=result.status_code) This throws an error that the serializer can not understand colour as a field. Ofcourse, it's not supposed to be a field, it's a query string. How do I handle it correctly to use it for the url request only? Finally, the get url should look something like "www.abc.com/?colour=blue" -
How to use django inlineformset_factory to allow users to create course in a function base view
Okay am really having a hard time figuring out how to use django inlineformset_factory as a form in a function base view to allow users to create their own course, I keep coming against this error (ModelForm has no model class specified) when i try to create a course, is there any better practice to use an inlnineformset in a function base view? or is it only possible with class base view? below is my form for creating course and module. from django.forms.models import inlineformset_factory from .models import Course, Module class CreateCourse(forms.ModelForm): ModuleFormSet = inlineformset_factory(Course, Module, fields=['title', 'description'], extra=2, can_delete=True) Here is my function base view for creating a course def course_create(request): if request.method == "POST": form = CreateCourse(request.POST,request.FILES) if form.is_valid(): form.save() return redirect('courses:main') else: form = CreateCourse(request.POST,request.FILES) context={'form':form} return render(request,'manage/module/formset.html',context) -
Django boundfields auto naming: changing the form part
I can't seem to find if/how this is possible. But say I have a form: class Detform(ModelForm): class Meta: model = Ap_detcmd fields = ["foo"] Formset = inlineformset_factory(ParentModel, ChildModel, form=Detform, can_delete=False, extra=0) Then in the template this gets renders, for instance in the management form (or any field): <input type="hidden" name="ap_detcmd-TOTAL_FORMS" value="0" id="id_ap_detcmd-TOTAL_FORMS"> Since the model of the form is "Ap_detcmd", then I get #id_ap_detcmd-.... as a prefix for all fields. Is there a way to specify that prefix? -
Django template's include not sharing static files
I have a large Django project with multiple templates which are merged later on to construct pages dynamically, I am facing a weird issue as follows: I have a base.html which includes all the needed imports, including JS and CSS. I have sub-folders for both CSS/JS in the assets, which are usually imported at the end of base.html. Now, as my project got bigger, I decided I'd rather have the scripts imports, e.g: <script type="text/javascript" src="{% static "js/base.js" %}"></script> <script type="text/javascript" src="{% static "js/menus/projects.js" %}"></script> <script type="text/javascript" src="{% static "js/menus/sensors.js" %}"></script> included in each individual HTML file, instead of all being in the base.html, I expected to have no issues, since as far as I know include statements should also transfer context, for reference sake, those are the include statements of interest: in base.html: {% include "applications/Devices/deviceDashboard.html" %} in deviceDashboard.html: {% include "applications/Devices/deviceDashboard/listCard.html" %} {% include "applications/Devices/deviceDashboard/editCard.html" %} {% include "applications/Devices/deviceDashboard/graphCard.html" %} In all of those, if I try to run it as-is I get the following: TemplateSyntaxError at / Invalid block tag on line 25: 'static'. Did you forget to register or load this tag? When I try to use the same script import tags as before, and this … -
How to provide voice synthesis on my website?
I have a python program which can take as an input a text file and some parameters, and give as output a file mp3. I would like to let people try the system on my website, for small sentences. I thought I could put the python program on a cloud server and create a API with Flask-Restful, and then call this API with my website which is made with Django Framework. I can't afford a GPU server, so it will take a few seconds/minutes to generate the mp3 file. I can't make a POST request that long, can I? The thing is, I don't know if this is an appropriate method, is there an easier way to do this ? I just want to install my tts system on a web server, and be able to call it from my website. I didn't found any documentation or tutorial that helped me... Tell me if my problem is not clear enough, Thank you for your help -
get and dispaly and open image from s3 bucket to django admin template
I have a folder on amazon s3 bucket which contains multiple images. I want to display those images on django admin panel also the images should be clickable. I am able to display image on admin template but when I have created its href to open image it gives me blank. my current code looks like this: admin.py class ImagesAdmin(admin.ModelAdmin): def image_from_S3(self, obj): image_obj = client.get_object(Bucket=bucketName, Key='folder_name/'+str(obj.image_name) ) body = image_obj['Body'].read() return format_html('<a target="_blank" href="data: image/png; base64,'+b64encode(body).decode('utf8')+'"><img src = "data: image/png; base64, {}" width="100" height="100"></a>'.format( b64encode(body).decode('utf8') )) using this code I have successfully displayed image on django admin template but when trying to hit image then image is unable to load . -
React and Django website not loading on Heroku
Homepage doesn't load properly I have successfully build and deployed my code in Heroku. It works fine locally but react doesn't render the index.html The backend API works properly here but the homepage here doesn't load - using ReactJS. My all GitHub codes are here inside the develop branch. -
How to change File type from CSV to XLSX
My current code prints my file data to a CSV perfectly, however, I need this data to be in an XLSX format instead. Does anyone know how I could do this without changing my code too much, here is what I have currently got : Views.py # Starting CSV response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="' + complexName + '"Age Analysis.csv"' writer = csv.writer(response) writer.writerow(['Prepared By : Atout(PTY) ltd']) writer.writerow(['Customer Age Analysis for Monthly Customers as at 31/10/21']) writer.writerow( ['Account', ' ', ' ', '120+ Days', '90 Days', '60 Days', '30 days', 'Current', 'Total', '', 'Name', 'E-mail']) for x in ageSelect: writer.writerow([ x["Account"], '*', ' ', '0', '0 ', '0', '0', x["Balance"], x["Balance"], '', x["Name"], x["E-mail"] ]) for x in XtotalCurent: writer.writerow(['Totals:', ' ', ' ', '120 Days', '90 Days', '60 Days', '30 days', x, x]) writer.writerow(['PERCENTAGE :', ' ', ' ', '120 Days', '90 Days', '60 Days', '30 days', 'Current', '100%']) writer.writerow(['GRAND TOTAL :', ' ', ' ', '', '', '', '', '', x]) return response -
Django Filter Duplicated Obj in Queryset
I have Product and ProductPrices Model. class ProductPrice(BaseModel): product = models.ForeignKey( to="Product", related_name="prices", on_delete=models.CASCADE, verbose_name=_("prices"), null=True, blank=True ) When ı try order by price model field some objects duplicated. What ı doing? if order_by in [order_choices[HIGH_TO_LOW_PRICE], order_choices[LOW_TO_HIGH_PRICE]]: outer_price = ProductPrice.objects.filter(end_user__isnull=False, product_id=OuterRef("pk")) qs = qs.annotate(has_price=Exists(outer_price)).order_by("-has_price", order_by).distinct() return qs -
Are there any existing universal Python post code validation packages?
I know how to make post codes (zip codes) validations for specific countries. I know how to check to see the number of characters the user has entered and whether he has included numbers, letters or both. But is there a package I can install that already has post code (zip code) validations for every country. I want the form to apply different validations based on the country the user selects. For example I only want the user to be able to enter letters in the post code if they have chosen one of these countries - Argentina, Brunei, Canada, Eswatini, Ireland, Kazakhstan, Malta, Netherlands, Peru, Somalia or United Kingdom. -
How to setup Django + RabbitMQ + Celery with Docker?
I'm trying to setup my Django app to have push notification functionality. For scheduling notifications I'm trying to use Celery, for the message broker I chose RabbitMQ. My app is running in Docker containers and I'm struggling to get the RabbitMQ to work. I get an error message Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. when running docker-compose up. Here are my celery and rabbitmq3 services from my docker-compose.yml: celery: restart: always build: context: . command: celery -A test_celery worker -l info volumes: - .:/test_celery env_file: - ./.env depends_on: - app - rabbitmq3 rabbitmq3: container_name: "rabbitmq" image: rabbitmq:3-management-alpine ports: - 5672:5672 - 15672:15672 In my test_celery -app I have a file called celery.py which contains the following: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_celery.settings') app = Celery('test_celery') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() And finally, in my settings.py I have this: CELERY_BROKER_URL = 'amqp://localhost'. Should I define the CELERY_BROKER_URL somehow different? Is there something wrong with my docker-compose file? Would appreciate any help with this, what is wrong with my setup? -
Unable to connect to Sql Server from Docker Django
i'm trying to connect my Django to en existing legacy MS SQL database. When im trying to run a sql on the database works fine: sql = 'SELECT * FROM ' + db_name + '.INFORMATION_SCHEMA.TABLES' connection_string = "driver=FreeTDS;server={};PORT={} database={};UID={};PWD={};TDS_Version=8.0;".format(db_host, db_port, db_name, db_user, db_password) conn = pyodbc.connect(connection_string, autocommit=True) for row in cursor.fetchall(): print(row) And i can see all the tables but when try to generate model from database running this command: python manage.py inspectdb --database pirineos > pirineos_models.py I get the error: django.db.utils.Error: ('08001', '[08001] [FreeTDS][SQL Server]Unable to connect to data source (0) (SQLDriverConnect)') This are my project files. Dockerfile: FROM python:3.8-slim-buster ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apt-get update -y && apt-get install -y unixodbc unixodbc-dev tdsodbc freetds-common freetds-bin freetds-dev && apt-get clean && rm -rf /var/lib/apt/lists/* RUN mkdir /djangonoguero COPY ./project /djangonoguero/ COPY ./requirements.txt /djangonoguero/ ADD odbcinst.ini /etc/ WORKDIR /djangonoguero RUN pip install --no-cache-dir -r requirements.txt EXPOSE 8000 requirements.txt: pyodbc==3.0.10 django-mssql-backend==2.8.1 settings.py: DATABASES = { 'pirineos': { 'ENGINE': 'sql_server.pyodbc', 'NAME': DB_PIRINEOS_NAME, 'USER': DB_PIRINEOS_USER, 'PASSWORD': DB_PIRINEOS_PASSWORD, 'HOST': DB_PIRINEOS_HOST, 'PORT': DB_PIRINEOS_PORT, 'OPTIONS': { 'driver': 'FreeTDS', 'unicode_results': True, 'driver_supports_utf8' : True, 'extra_params': 'tds_version=8.0;', }, }, } odbcinst.ini: [FreeTDS] Description=FreeTDS Driver for Linux & MSSQL on Win32 Driver=/usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so Setup=/usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so UsageCount=1