Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not sure I understand dependancy between 2 django models
I am struggling to understand django models relationship. I have this arborescence: A train have cars, and those cars are divided into parts. Then those parts all contains different references. Like, for exemple, all the trains have the 6 cars, and the cars 6 parts. Each part have x reference to be associated. I would like to use all of them in a template later on, where the user can select the train, the car and the part he worked on, then generate a table from his selections with only the references associated to the parts he selected. It should update the train and the car (I'm trying to update a stock of elements for a company) I dont really understand which model field give to each of them. After checking the doc, Ive done something like this but i am not convinced: class Train(Car): train = models.CharField(max_length=200) id = models.CharField(primary_key='True', max_length=100) selected = models.BooleanField() class Meta: abstract = True class Car(Part): car = models.CharField(max_length=200) id = models.CharField(primary_key='True', max_length=100) selected = models.BooleanField() class Meta: abstract = True class Part(Reference): part = models.CharField(max_length=200) id = models.CharField(primary_key='True', max_length=100) selected = models.BooleanField() class Meta: abstract = True class Reference(models.Model): reference = models.CharField(max_length=200) id … -
Progress Bar Upload to S3 Django
I would like to show an upload progress bar for S3 uploads from a Django site. Currently without the progress bar being manipulated by JQuery, the uploads are working direct to S3. Once I try to implement the progress bar using JQuery, the upload form still functions as far accepting input and the file, but will not communicate the file to S3. Here is the upload view: from .forms import UploadForm def upload(request): if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('upload') else: form = UploadForm() context = { 'form': form } return render(request, 'content/upload.html', context) Here is the HTML: {% extends "about/base.html" %} {% load crispy_forms_tags %} {% block content %} {% block navbar %}{% endblock %} <div class="site-section mb-5"> <div class="container"> <div class="form-register"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <legend>Upload Content</legend> <div class="form-group"> {{ form | crispy }} </div> <button class="btn btn-outline-info" type="submit">Upload</button> </form> <div class="progress"> <div id="progressBar" class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"> 0% </div> </div> </div> </div> {% endblock %} Here is the JQuery: $(document).ready(function() { $('form').on('submit', function(event) { event.preventDefault(); var formData = new FormData($('form')[0]); $.ajax({ xhr : function() { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener('progress', function(e) { if (e.lengthComputable) { … -
How to install gdal package on django project with pip
I want to install GDAl package to django project in linux shared host i get the ssh access but i can't use apt command so i want to install GDAl with virtualenv and i get this error : [ERROR 2] No such file or directory: 'gdal-config': 'gdal-config' ERROR: Command errored out with exit status 1: python setup.py egg-info Check the logs for full command output. -
Does Django use built in variable names for Templates?
I'm learning Django and have done some tutorials. Does Django have built in variables that are accessible to any template in any app, or are these defined somewhere in code? For example, I have an app called users. In the models.py of users/models.py, I have this code: from django.contrib.auth.models import User In urls.py I have this: path('profile/', user_views.profile, name='profile') In users/views.py I do have a function called profile, but no where in that function am I passing a variable that allows for the use of obtaining a person's first name, however, in my template profile.html I can get the first person's name by using: {{ user.first_name }} Why is this? I was under the impression that we had to pass specific variables as dictionaries. -
Elasticsearch Indexing in Django Celery Task
I’m building a Django web application to store documents and their associated metadata. The bulk of the metadata will be stored in the underlying MySQL database, with the OCR’d document text indexed in Elasticsearch to enable full-text search. I’ve incorporated django-elasticsearch-dsl to connect and synchronize my data models, as I’m also indexing (and thus, double-storing) a few other fields found in my models. I had considered using Haystack, but it lacks support for the latest Elasticsearch versions. When a document is uploaded via the applications’s admin interface, a post_save signal automatically triggers a Celery asynchronous background task to perform the OCR and will ultimately index the extracted text into Elasticsearch. Seeing as how I don’t have a full-text field defined in my model (and hope to avoid doing so as I don’t want to store or search against CLOB’s in the database), I’m seeking the best practice for updating my Elasticsearch documents from my tasks.py file. There doesn’t seem to be a way to do so using django-elasticseach-dsl (but maybe I’m wrong?) and so I’m wondering if I should either: Try to interface with Elasticsearch via REST using the sister django-elasticsearch-dsl-drf package. More loosely integrate my application with Elasticsearch by … -
Unable to get 'get absolute url' to work (Python - Django)
Once a user had logged into my site he could write a post and update it. Then I was making progress in adding functionality which allowed people to make comments. I was at the stage where I could add comments from the back end and they would be accurately displayed on the front end. Now when I try and update posts I get an error message. I assume it is because there is a foreign key linking the comments class to the post class. I tried Googling the problem and looking on StackOverflow but I wasn't entirely convinced the material I was reading was remotely related to my problem. I am struggling to fix the issue because I barely even understand / know what the issue is. def save(self, *args, **kwargs): self.url= slugify(self.title) super().save(*args, **kwargs) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', kwargs={'slug': self.slug}) class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) def get_absolute_url(self): return reverse('article_detail', kwargs={'slug': self.slug}) -
How to apply python package localization file available in the package repository?
I've came across this issue a couple of times. I'm using a python package (e.g django-rest-framework-simplejwt) and it has the locale file I want in its Github repository. Now, even though I have LANGUAGE_CODE = "pt-BR" set in my django settings file, it won't load the right language. I've noticed that there's no locale folder inside my venv/lib/site-packages/rest_framework_simplejwt/. How do I install the available localization file from a repository in scenarios where installing the package skips the desired locales? -
Django POST query: Pass tuple or list in a param
I am trying to pass a tuple in a DJANGO POST query. But it is taking the value type as string. Like this: ('id','country_name') I found various links but none on how to pass a list/tuple in params. -
Django "Illegal mix of collations" for MySQL utf8mb4 table
I have reviewed other questions related to this topic, such as django python collation error However, the solutions say to encode the table using a utf8 charset. That is not a viable solution for our modern Django app running on a utf8mb4-encoded database. In my case, I need to enforce a charset or collation in the Django generated query, or in the DB itself, when utf-8 characters are being passed in (from a call to model.objects.get_or_create(), I believe with an emoji character being passed in one of the kwargs fields.) I'm getting this error: django.db.utils.OperationalError: (1267, "Illegal mix of collations (utf8mb4_unicode_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='") Any advice welcome. Thanks! -
Set the value of the Django 2 Admin Autocomplete widget using jQuery
I'm trying to add some custom logic with jQuery to a django admin view. I want to change the value of some select fields on my tabular inline fields when the value the "formula" Select Input Change. I've tried the following code, but the django admin autocomplete values does not change. rowNumber = 0 var ingredientInput = $('#id_formulaexplosioningredient_set-' + rowNumber + '-ingredient'); // console.log('aaa', ingredient, rowNumber, ingredientInput, ); console.log('select', ingredientInput.select2()); console.log('djangoAdminSelect2', ingredientInput.djangoAdminSelect2()); ingredientInput.djangoAdminSelect2().val(ingredient.ingredient.id.toString()).trigger('change'); ingredientInput.select2().val(ingredient.ingredient.id.toString()).trigger('change'); ingredientInput.val(ingredient.ingredient.id.toString()).trigger('change'); As you can see I tried 3 ways, with the val() of the element. The val() of the select2 plugin and the val() of the djangoAmindSelect2() plugin. Can anyone help me out and show me what I'm doing wrong? Thank you! -
Revoke-token error in oauth2 Django Oauth2
I have such a trouble I can't do revoke-token command in oauth2 django convert-token works good,and i don't understand why,they are quite similar I call each command with PostMan,but second don't want to work. Trace:{ "error": "invalid_request", "error_description": "URL query parameters are not allowed" } In addition,i am doing it with YouTube guide,step-by-step,but nothing help I was trying to call it from windows cmd,trying to search for different solutions online but nobody has the same. settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ''#i will hide it for my sec # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ba_app', 'users', 'bootstrap3', 'oauth2_provider', 'social_django', 'rest_framework_social_oauth2', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'be_aware_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] WSGI_APPLICATION = 'be_aware_project.wsgi.application' # … -
Python add multiple strings to one string with indexes same time
I have a long text, and some list of dict objects which points indexes of this long text. I want to add some strings to this indexes. If I set a loop, indexes change and I must calculate the indexes again. I think this way very confusing. Is there any way add different strings to different indexes in single time? My sample data like that: main_str = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.' my indexes list like that: indexes_list = [ { "type": "first_type", "endOffset": 0, "startOffset": 5, }, { "type": "second_type", "endOffset": 16, "startOffset": 22, } ] My main purpose: I want to add <span> attributes to given indexes with some color styles based on types. After that I render it on template, directly. Have you another suggestion? -
Save data into two table. Student with ID “None” doesn’t exist. Perhaps it was deleted?
I tried to save data to the standard User class and for my Student class. But I've got a problem. Student with ID “None” doesn’t exist. Perhaps it was deleted? models.py class Student(models.Model): studentIndex = models.IntegerField(unique=True) studentName = models.CharField(max_length=50) studentSurname = models.CharField(max_length=50, default='') studentPhoneNumber = models.CharField(max_length=12, default='+48') studentPesel = models.CharField(max_length=11, default='') studentStudyMode = models.CharField(max_length=12, default='') studentFaculty = models.CharField(max_length=30, default='') studentSemester = models.IntegerField(default='') studentAddress = models.CharField(max_length=255, default='') studentMotherName = models.CharField(max_length=100, default='') studentBirth = models.DateField(help_text='year-month-day') studentEmail = models.EmailField(max_length=255, default='') studentImage = models.ImageField(default='default.jpg', upload_to='profile_pics') studentPassword = models.CharField(max_length=100, default='12345678', help_text='Do not modify this field. Password will be generated automatically') studentDateJoined = models.DateTimeField(default=now) def save(self, *args, **kwargs): default_password = str(self.studentBirth)[0:4] + str(self.studentBirth)[5:7] + \ str(self.studentBirth)[8:10] +\ self.studentMotherName[0] +\ lower(self.studentName[0]) User.objects.create_user(username=self.studentIndex, email=self.studentEmail, password=default_password, first_name=self.studentName, last_name=self.studentSurname) def __str__(self): return f'{self.studentIndex} - {self.studentName} {self.studentSurname}' When I try this ... def save(self, *args, **kwargs): default_password = str(self.studentBirth)[0:4] + str(self.studentBirth)[5:7] + \ str(self.studentBirth)[8:10] +\ self.studentMotherName[0] +\ lower(self.studentName[0]) Student.objects.create() # <- this one User.objects.create_user(username=self.studentIndex, email=self.studentEmail, password=default_password, first_name=self.studentName, last_name=self.studentSurname) I've got string index out of range error (IndexError) or maximum recursion depth exceeded in comparison (RecursionError) I'm new in Django, so I'll be grateful if you'll help me Thanks a lot -
The model Group is already registered in app 'auth'
I switched my database to Postgresql and I'm having issues registering them to the admin interface. I'm having the error The model Group is already registered in app 'auth'. But, when I try to unregister the model (reference: Already Registered at /appname/: The model User is already registered), I get the error: django.contrib.admin.sites.NotRegistered: The model User is not registered It's really weird. Let me know if you need any piece of code. Thanks in advance! -
Django - Retrieving data from different spans
I am actually having a page which asks the user to build a team from a list of names and also to select some few other things later on the page.. I am a using Django and then I am a bit lost on the best way I could get this data from (the selected elements) Almost all my clickable elements are of type span. I also would like to get some data from two select elements. My questions are the following: Is it possible to get the data I want by using this page? or should I start over do a Django Form? (I have done this page way before I started Django and I spent hours on it, so I would like to avoid starting over...) If it is possible, then What would be the best way I could get all the data I want using Django? Here is a picture of my page for you to see what I am trying to achieve: select teammates select parts Here is an sample of my code: HTML <div class="card-body" id="team-list"> <p class="card-text">Select today's teammates:</p> <ul class="list-group list-group-flush"> <li class="list-group-item"> <span class="name">name 1</span> <span class="move" style="float: right;">Add to the team</span> … -
Deleting a very big folder in Google Cloud Storage
I have a very big folder in Google Cloud Storage and I am currently deleting the folder with the following django - python code while using Google App Engine within a 30 seconds default http timeout. def deleteStorageFolder(bucketName, folder): from google.cloud import storage cloudStorageClient = storage.Client() bucket = cloudStorageClient.bucket(bucketName) logging.info("Deleting : " + folder) try: bucket.delete_blobs(blobs=bucket.list_blobs(prefix=folder)) except Exception as e: logging.info(str(e.message)) It is really unbelievable that Google Cloud is expecting the application to request the information for the objects inside the folder one by one and then delete them one by one. Obviously, this fails due to the timeout. What would be the best strategy here ? -
ModelForm not processing upload
I have a ModelForm in django: class uploadform(forms.ModelForm): class Meta: model = upload fields = ['email', 'title', 'date', 'file'] From the model: class upload(models.Model): email = models.EmailField() title = models.CharField(max_length=100) date = models.DateField() file = models.FileField() Here is my view for processing the form: def upload(request): if request.method == 'POST': form = uploadform(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('upload') else: form = uploadform() context = { 'form': form } return render(request, 'content/upload.html', context) Here is my HTML: <div class="site-section mb-5"> <div class="container"> <div class="form-register"> <form method="POST"> {% csrf_token %} <legend>Upload Content</legend> <div class="form-group"> {{ form | crispy }} </div> <button class="btn btn-outline-info" type="submit">Upload</button> </form> Form populates well, form will allow me to attach, but whenever I press "Upload", I get redirected with the file actually going to S3. I know my S3 connection is correct because If I go to admin and create an upload, the file will appear in S3. What could be causing the file upload from the form.save() to not work? -
ProgrammingError at / relation "blog_post" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "blog_post"
Im getting this error when Im trying to deploy my django project to Heroku. Can anyone help -
Django error: Tcl_AsyncDelete: async handler deleted by the wrong thread
I am totally new in Django and I am having this error while I was trying to upload a CSV file through rest API. Basically, the back-end will receive sensor data as a CSV file. and the algorithm will run and proposed the sensor data and will return back a plotting script to the frontend. data_pre_process.py has a function called main def main (data): ld = LidarData(data) ld.apply_all_cleaning(verbose=False) angs,ss = compute_ransac_angles(ld.x, ld.y, n_win=80, n_trials=100, verbose= True) trans_slide = search_transition_regions(angs, verbose=True) wall_lines = compile_walls(trans_slide, ld.x, ld.y, verbose=True) sects = get_wall_corners(wall_lines) return ld here compute_ransac_angles takes around 20 sec to compute and process the data properly. overall the main takes 30 sec to return back the results after all the computation. here is my views.py from django.shortcuts import render from django.http import HttpResponse from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.exceptions import ParseError from rest_framework.parsers import FileUploadParser from lidar.create_plot import plotting, floorPlanPlotting from lidar.data_pre_process import * ########### # Create your views here. class lidarApi(APIView): def post(self, request): lidarData= request.data["data"] result = main(lidarData) plot = floorPlanPlotting(result) #check_request = request.data #plot = plotting(check_request) return Response(plot) for the very first case, it's working fine. but after few times later back end stop working … -
How Can I fix it?The app shows error in API key just like (KeyError: 'Api Key not found. ')
from django.shortcuts import render from django.contrib import messages from airtable import Airtable import os AT = Airtable(os.environ.get('AIRTABLE_MOVIESTABLE_BASE_ID'), 'Movies', api_key=os.environ.get('AIRTABLE_API_KEY')) Create your views here. def home_page(request): ##print(str(request.GET.get('query',''))) user_query=str(request.GET.get('query','')) return render(request,'movies/movies_stuff.html') -
adding percentage to graph
my code class BarChart(Drawing): def __init__(self, width=400, height=200, *args, **kw): Drawing.__init__(self, width, height, *args, **kw) self.add(String(200, 180, 'Hello World'), name='title') self.add(Pie(), name='pie') self.add(Legend(), name='leyenda') h=Donador.objects.filter(genero='M').count() m=Donador.objects.filter(genero='F').count() datos = [(colors.yellow, 'Hombres'), (colors.red, 'Mujeres')] self.title.fontName = 'Helvetica-Bold' self.title.fontSize = 12 self.pie.slices[0].fillColor=colors.yellow self.pie.slices[1].fillColor=colors.red self.pie.data = [h, m] self.pie.x = 50 self.pie.y = 0 self.pie.width = 150 self.pie.height = 150 self.leyenda.x= 300 self.leyenda.y=100 self.leyenda.colorNamePairs = datos This code generates a pdf file with a pie chart. What I want is that said chart show percentages thanks you -
How can I get the particular friend who like my post
I'm new in Django. I have friends in Manytomany field, how do I get my friends who liked my post. When my friend liked my post, I want to display is profile_pic at the side of my like count, but if a user who is not my friend is profile_pic will not display. I attached an image so that my question can be clearly understood. class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) profile_pic = models.ImageField() friends = models.ManyToManyFiels('Profile', related_name='my_friends') class Post(models.Model): poster_profile = models.ForeignKey(settings.AUTH_USER_MODEL) likes = models.ManyToManyField(User, related_name='image_likes) def home(request): user = request.user list_friends = user.profile.friends.all() -
Is it possible to pull 600,000 rows from a MySQL database and Display it as JSON data in postman?
I am trying to return a MySQL table with 600,000 rows and display it as a JSON object. My views.py contains the method below. def SettlementsStatements_1(request, query=""): if query =="All": namemap={'ID':'id','Comapny Name':'COMPANY_NAME'} ssr=SettlementsStatements.objects.raw('SELECT id,COMPANY_NAME FROM telco_amazon.settlements_statements;',translations=namemap) data = serializers.serialize('json', ssr) return JsonResponse(data,safe=False) I am calling this view in postman and it has yet to load after 40 minutes.I am wondering, is it even possible to extract and load this much data? -
Como posso mudar o estilo de uma form do Django
Estou fazendo um site de Quizzes e estou com problemas na edição de usuários usando a model form do Django. Porém, queria que ele ficasse dessa forma: https://i.imgur.com/P09UMkT.png só que não estou conseguindo fazer. Resumindo, queria que o formulário do Django ficasse da mesma forma da print acima, só que fazendo da forma que fiz ele não vai. Desde já agradeço. edit.html <body data-spy="scroll" data-target=".navbar" data-offset="50"> <div class="container py-2 mt-5"> <div class="row my-2"> <div class="col-lg-4"> <h2 class="text-center font-weight-light">User Profile</h2> </div> {% csrf_token %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> {{ error }} </div> {% endfor %} <div class="col-lg-8"> </div> {% for field in form %} <div class="col-lg-8 order-lg-1 personal-info"> <form role="form" method="post"> <div class="form-group row"> <label class="col-lg-3 col-form-label form-control-label">Nickname</label> <div class="col-lg-9"> <input class="form-control" type="text" value="{{user|title}}" /> </div> </div> <div class="form-group row"> <label class="col-lg-3 col-form-label form-control-label">{{field.name}}</label> <div class="col-lg-9"> <input class="form-control" type="email" value="" /> </div> </div> <div class="form-group row"> <label class="col-lg-3 col-form-label form-control-label">{{field.name}}</label> <div class="col-lg-9"> <input class="form-control" type="password" value="11111122333" /> </div> </div> <div class="form-group row"> <label class="col-lg-3 col-form-label form-control-label">{{field.name}}</label> <div class="col-lg-9"> <input class="form-control" type="password" value="11111122333" /> </div> </div> <div class="form-group row"> <div class="col-lg-9 ml-auto text-right"> <a href="/"><input type="reset" class="btn btn-outline-secondary" value="Cancel" /></a> <a href="{% url 'accounts:edit' %}"><input type="button" class="btn … -
Is there a way to prevent keyboard focus from being lost when reloading a pdb target?
If I'm debugging a django view with runserver and I change python source without exiting the debugger, the python process will notice the change and reload. This reload will kill the current context, and now keystrokes won't be sent to the terminal. To close the process I have to kill the terminal entirely. Is there a way to get the reloading django process to cleanly kill the open debugging process and ensure I can still control-c out of the runserver?