Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Install gdal geodjango on elastic beanstalk
what are the correct steps to install geodjango on elastic beanstalk? got eb instance, installed env and made it two instances now I want to use geodjango on it, I'm already using it on a separate ec2 instance for testing that's my django.config file and it fails option_settings: aws:elasticbeanstalk:container:python: WSGIPath: hike.project.wsgi:application commands: 01_gdal: command: "wget http://download.osgeo.org/gdal/2.1.3/gdal-2.1.3.tar.gz && tar -xzf gdal-2.1.3.tar.gz && cd gdal-2.1.3 && ./configure && make && make install" then tried this instead and also failed from 100% cpu and time limit option_settings: aws:elasticbeanstalk:container:python: WSGIPath: hike.project.wsgi:application commands: 01_install_gdal: test: "[ ! -d /usr/local/gdal ]" command: "/tmp/gdal_install.sh" files: "/tmp/gdal_install.sh": mode: "000755" owner: root group: root content: | #!/usr/bin/env bash sudo yum-config-manager --enable epel sudo yum -y install make automake gcc gcc-c++ libcurl-devel proj-devel geos-devel # Geos cd / sudo mkdir -p /usr/local/geos cd usr/local/geos/geos-3.7.2 sudo wget geos-3.7.2.tar.bz2 http://download.osgeo.org/geos/geos-3.7.2.tar.bz2 sudo tar -xvf geos-3.7.2.tar.bz2 cd geos-3.7.2 sudo ./configure sudo make sudo make install sudo ldconfig # Proj4 cd / sudo mkdir -p /usr/local/proj cd usr/local/proj sudo wget -O proj-5.2.0.tar.gz http://download.osgeo.org/proj/proj-5.2.0.tar.gz sudo wget -O proj-datumgrid-1.8.tar.gz http://download.osgeo.org/proj/proj-datumgrid-1.8.tar.gz sudo tar xvf proj-5.2.0.tar.gz sudo tar xvf proj-datumgrid-1.8.tar.gz cd proj-5.2.0 sudo ./configure sudo make sudo make install sudo ldconfig # GDAL cd / sudo mkdir -p /usr/local/gdal … -
unsupported operand type in django project
I am working on a django project where i am going to create a tranfer money process. but when im doing this, i am getting following error unsupported operand type(s) for -=: 'int' and 'str' views here. from django.shortcuts import render,redirect from .models import * # Create your views here. def Moneytransfer(request): if request.method == 'POST': try: user= request.POST.get('user') user_two= request.POST.get('user_two') balance= request.POST.get('balance') #print(phone) user_obj= TransferMoney.objects.get(user=user) user_obj.balance -= balance user_obj.save() user_two_obj= TransferMoney.objects.get(user=user_two) user_two_obj.balance += balance user_obj.save() except Exception as e: print(e) return redirect('/') return render(request, 'transaction/transfermoney.html') models.py class TransferMoney(models.Model): user= models.CharField(max_length=50) phone= models.CharField(max_length=20, unique=True,default=None) balance= models.IntegerField(default=0) def __str__(self) -> str: return self.user -
How to make Model.clean work before saving?
I'm a beginner in Django and I'm trying to make a quiz app. I need to have a validation for admin panel so at least one answer was correct and at least one answer was wrong. I override a clean() method, it works incorrectly. For example - I make all answers incorrect - saving is okay, than I want to change it back - it raises an error 'There should be at least one correct answer'). My models: from django.core.exceptions import ValidationError from django.db import models class Quiz(models.Model): name = models.CharField(max_length=100) image = models.ImageField(blank=True, null=True, upload_to='images/quiz/') class Meta: verbose_name_plural = 'Quizzes' def __str__(self): return self.name class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='questions') question = models.CharField(max_length=255) def __str__(self): return self.question def clean(self): correct_answers = Answer.objects.filter(question=self).filter(is_correct=True).count() if correct_answers == 0: raise ValidationError('There should be at least one correct answer') elif self.answers.count() == correct_answers: raise ValidationError('There should be at least one wrong answer') class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') answer = models.CharField(max_length=255) is_correct = models.BooleanField() def __str__(self): return self.answer It seems like the clean method works before save method with the original data and doesn't check new data which I'm trying to save. I tried to override the save() method with self.clean() … -
serve django staticfiles with nginx
i have django back-end and reactjs front-end. i want to load static files of django back-end with nginx but he can't find anything . gunicorn can find django pages but can't load staticfiles so i want nginx to serve django page and staticfiles. this is my settings.py : STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, '/static') docker-compose : version: "3.9" services: backend: build: context: ./backend ports: - "8000:8000" entrypoint: ./entrypoint.sh # command: gunicorn server.wsgi:application --bind 0.0.0.0:8000 volumes: - static:/static nginx: build: context: . dockerfile: ./webserver/Dockerfile restart: always ports: - "80:80" volumes: - static:/static depends_on: - backend volumes: static: and this is my default.conf : upstream api { server backend:8000; } server { listen 80; server_name myapp.loc; root /usr/share/nginx/html/frontend1; location / { try_files $uri /index.html; } location /admin/ { proxy_pass http://api; } location /static/ { alias /static/; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } } server { listen 80; server_name newapp.loc; root /usr/share/nginx/html/frontend2; location / { try_files $uri /index.html; } location /admin/ { proxy_pass http://api; } location /static/ { alias /static/; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } } -
Django forms: MultipleChoiceField set active options on init
I'm building a custom form using ul and li items for selecting options and I have a problem that is based on a logic I have in my forms. So I have some models in which I create my product attributes and a separate model which has those attributes values. So this is how I create my form class PropertyAttributeForm(FormSpamDetect, forms.Form): adg = HoneypotField() def __init__(self, *args, **kwargs): super(PropertyAttributeForm, self).__init__(*args, **kwargs) # TODO add cache # Get custom attribute fields for attribute in PropertyAttribute.objects.filter(is_active=True): # TODO: add more types if attribute.type == PropertyAttribute.STRING: if choices := attribute.value_choices.all(): choices_tuple = ((choice.value_slugified, choice.value) for choice in choices) self.fields[attribute.slugified_name] = forms.MultipleChoiceField() self.fields[attribute.slugified_name].choices = choices_tuple self.fields[attribute.slugified_name].required = False self.fields[attribute.slugified_name].widget.attrs.update({"class": "hidden"}) def save(self, commit=True): if self.is_valid(): try: property = Property.objects.last() # TODO pass pk from session property.attrs = json.dumps(self.cleaned_data) property.save() except Property.DoesNotExist: return And this is my form in template: <form id="property-ajax-form" class="grid gap-12 mt-10 grid-flow-row grid-cols-1"> {{ form.adg }} {% for field in form.attribute_fields %} <div class="text-lg text-center"> <span class="text-left text-2xl font-medium text-primary">{{ attr_name_by_slugified_name[field]|safe }}</span> {{ form[field] }} <ul id="{{ field }}-options" class="grid grid-flow-row grid-cols-4 mt-5 gap-5 w-3/5 mx-auto"> {% for attribute in form[field] %} <li data-type="{{ attribute.data.value }}" class="flex flex-col m-auto items-center justify-center … -
Apex chart not changing colors when using candlestick chart
I am using apex charts to develop charts for the stock market and in the backend I use Django. I have a problem with changing the colors of candlesticks. I have multiple stocks with years of data and on some stocks, chart colors are correctly displayed but on most of them, they are displayed incorrectly. I have no idea what is causing this and how to fix this. Any idea? Chart code: <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script> <div id="chart"> </div> <script> var options = { series: [{ name: 'OHLC', type: 'candlestick', data: [ {% for stock in stocks %} { x: "{{stock.date}}", y: ["{{stock.open|floatformat}}", "{{stock.high|floatformat}}", "{{stock.low|floatformat}}", "{{stock.price|floatformat}}"], }, {% endfor %} ] }, ], chart: { id: 'chart_1', group: 'social', type: 'candlestick', height: 900 }, title: { text: '{{ticker}} Stock ', align: 'center' }, yaxis: { tooltip: { enabled: true } } }; var chart = new ApexCharts(document.querySelector("#chart"), options); chart.render(); </script> With this part of django template: {% for stock in stocks %} { x: "{{stock.date}}", y: ["{{stock.open|floatformat}}", "{{stock.high|floatformat}}", "{{stock.low|floatformat}}", "{{stock.price|floatformat}}"], }, {% endfor %} I am looping through a list of data that I have in the backend filtered from the database. This is how chart looks like with incorrect colors: Data … -
How do I integrate my Django Project with an existing Vue3 template that I purchased?
I recently purchased a template from themeforest and they are using vue3 , I want to use the existing code and the design elements in my production ready Django project but I don't have any idea on how to do so. I want to add the templates in my existing project and use those elements. After reading this article , I am just able to load all of the code to the the django local host , but I am not able to specifically use only some parts of the html. I have set up static files. -
I want to migrate spring security sha256 (80byte) to Django
I want to migrate spring security sha256 (80byte) to django. import org.springframework.security.crypto.password.PasswordEncoder; passwordEncoder.encode("Mypassword"); **Security config** encoders.put("sha256", new org.springframework.security.crypto.password.StandardPasswordEncoder()); I did a hash of sha256 password through spring security. However, it is 80 bytes, not 64 bytes. **Result value: {sha256}80byte** I think it's made by adding a random salt value. But if it's a random salt value, how can I compare the values? **It should be implemented the same way in Python Django.** I don't know how to implement it. The method of adding a random salt value or **I'm going to show you how to do it in Python Django Please give it to me!** First of all, I don't understand the salt value. The password entered by the user and the password stored in the database should be compared, but how can it be processed if it is a random salt value? -
Can I remove a set of ManyToMany objects using SafeDeleteModel?
Soft_delete_cascade was applied to the entire model using the django-safedelete library. However, if you remove the corresponding many to many object as in the code below, it is not deleted from the set of objects. What should I do? # models.py from django.db import models from safedelete import SOFT_DELETE_CASCADE, HARD_DELETE from safedelete.models import SafeDeleteModel class Post(SafeDeleteModel): _safedelete_policy: int = SOFT_DELETE_CASCADE category = models.CharField("카테고리", max_length=100, null=True, blank=True) title = models.CharField("제목", max_length=300, null=True, blank=True) created_at = models.DateTimeField("생성일시", auto_now_add=True) updated_at = models.DateTimeField("수정시간", auto_now=True) tags = models.ManyToManyField("Tag", through="TagPostAssociation", related_name="posts") def __str__(self): return f"글(ID:{self.id}/제목:{self.title})" class Tag(SafeDeleteModel): _safedelete_policy: int = SOFT_DELETE_CASCADE value = models.CharField("태그 값", max_length=100) created_at = models.DateTimeField("생성일시", auto_now_add=True) updated_at = models.DateTimeField("수정시간", auto_now=True) class Meta: verbose_name = verbose_name_plural = "태그" def __str__(self): return f"태그(ID:{self.id}/값:{self.value})" class TagPostAssociation(SafeDeleteModel): _safedelete_policy: int = HARD_DELETE tag = models.ForeignKey(to=Tag, verbose_name="태그", on_delete=models.CASCADE) post = models.ForeignKey(to=Post, verbose_name="글", on_delete=models.CASCADE) created_at = models.DateTimeField("생성일시", auto_now_add=True) updated_at = models.DateTimeField("수정시간", auto_now=True) class Meta: verbose_name = verbose_name_plural = "글-태그" def __str__(self): return f"글{self.post.id})-태그({self.tag.id})" >>> post = Post.objects.get(id=2) >>> tag = Tag.objects.get(id=2) >>> post.tags.all() <SafeDeleteQueryset [<Tag: 태그(ID:2/값:hair)>, <Tag: 태그(ID:1/값:test)>]> >>> post.tags.remove(tag) >>> post.tags.all() <SafeDeleteQueryset [<Tag: 태그(ID:2/값:hair)>, <Tag: 태그(ID:1/값:test)>]> I tried to delete the many to many object using the m2m_changed signal, but it didn't work. -
How to load image from backend directly by using Django?
I am trying to make a blogging website. I know django provides argument templates like {% include images.html with value=sense %} The above code directly works in HTML and hence everything works. When I try the above code directly in the backend it doesn't work because I think once something is rendered then it doesn't rerender by django HTML I wish to paste some form of links in the django story backend. such that when it renders in HTML automatically the page should show pics in the appropriate place. If anyone has any idea how to do this kindly let me know. <p>{{object.story_title}}</p> <p>{{MEDIA_ROOT}}</p> <p>{{object.story}}</p> {% include "blogdescription/image.html" with value=sense %} Thank you for your time. with regards -
error in importing Rating model from star_rating.models
I am trying to use django_ratings but when i try to import it and i fail. I tried to just include {% ratings object %} in templates after configuring settings but i got an error 'str' object has no attribute '_meta'. Here is the settings #star rating settings STAR_RATINGS_RERATE_SAME_DELETE = True STAR_RATINGS_RERATE = True STAR_RATINGS_ANONYMOUS = True STAR_RATINGS_OBJECT_ID_PATTERN = '[a-z0-9]{32}' Templates context processor 'django.template.context_processors.request' Any help will be much appreciated Error! -
Django Stock Trading Based Web Application
I’ve developed a stock trading python script which gives stock price continuously using an API call. Now I want to display those price data into some HTML page using Django 4 in table format. Those prices should automatically updated/ reflected without reloading the page. And also, if I select some time interval (such as 1 minute or 2 minute etc) inside that HTML page then it should update price information at that interval without reloading the page. What is the best way to achieve this using Python 3 & Django 4. It would be very helpful if somebody has answer for this. Thanks, P. Roy. -
unsupported operand type(s) for +=: 'int' and 'Decimal128'
Im trying to add the numbers from Mongodb database. #code meal_data = Data.objects.filter(year= se_year, month= se_month, category = 'Meal') meal_amt = 0 for i in meal_data: id = i.id m_amount_data = Data.objects.get(id = id) meal_amt += m_amount_data.amount #error TypeError: unsupported operand type(s) for +=: 'int' and 'Decimal128' the error is showing in this line meal_amt += m_amount_data.amount I need to add those numbers and store it to a variable "meal_amt". -
how to read an excel file on django using pandas?
I am working on a website that takes your city and area and the food that you want to eat as input. Then, it shows you a list of all the restraunts in your area that are offering the food that you desire. My website gets the list of all the restraunts (from admin) through a Excel file. The problem that i'm facing right now is, that i'm unable to read the Excel file through pandas. My views.py file is as follows: class Addcity(View): def post(self, request, *args, **kwargs): file_name= request.POST.get('FileName') #some extra lines of code df = pd.read_excel(file_name,names=["name","rating","distance"]) print(df) return render(request, 'appmanager/addcity.html') Currently, whenever I upload a file, it displays an error(no such file exists), i even tried to keep my file in the same directory as my views.py file, but still didnt work. My addcity.html file is as follows: {% extends 'appmanager/base.html' %} {% block content %} <div class="container mb-5"> <div class="row justify-content-center mt-1"> <div class="card col-md-5 col-sm-12 p-4 text-center"> <form method="POST" action = "{% url 'welcome' %}" > {% csrf_token %} <div class="form-group"> <label for="FileName" class="form-label">Upload a file</label> <input class="form-control" type="file" name="FileName" /> </div> <button type="submit" class="btn btn-primary mb-2">Enter</button> </form> </div> </div> </div> {% endblock content %} … -
How to solve a problem of IntegrityError?
I need your help to solve this problem. I am creating a django application that manages absences and notes for an establishment. I wanted to create a list form with which the teacher can record absences. But I encountered an error in saving the view form. Here is my model and the view. ----Table: class Absence(models.Model): matricule = models.ForeignKey("Etudiant", on_delete=models.CASCADE) date = models.ForeignKey("Cours", on_delete=models.CASCADE) nombre_heure= models.IntegerField(null=True, default="0") ----Views: def listeappel(request): matricule=request.POST.get('matricule') date=request.POST.get('date') nombre_heure=request.POST.get('nombre_heure') newAbsence=Absence.objects.create(matricule=matricule, date=date, nombre_heure=nombre_heure) newAbsence.save() return render(request, 'mesabsences/listeappel.html') ---error : File "C:\Users\ISSA\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\ISSA\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 84, in _execute with self.db.wrap_database_errors: File "C:\Users\ISSA\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\ISSA\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\Users\ISSA\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 477, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: note_absence.date_id [25/Dec/2022 09:24:41] "GET /note/listeappel HTTP/1.1" 500 148241 I tried to delete the migration file and the database and then redo the migration, but it didn't work. -
How to set form values to user's values in a `FormView`?
Given a FormView subclass which updates user settings class SettingsView(FormView): template_name = 'settings.html' form_class = SettingsForm def get(self, request, *args, **kwargs): if request.user.is_authenticated: return super().get(request, *args, **kwargs) return redirect('signin') which has a SettingsForm containing user's first name and last name class SettingsForm(Form): first_name = forms.CharField( widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'First name'} ), ) last_name = forms.CharField( widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Last name'} ), ) Is there a way to populate the fields and set first and last name fields to user's first and last names? I think one way to do it is to define a get_form_class and nest a class definition there with the values set to request.user's. Is this the simplest way to do it? -
Django HttpRequest object not getting the json parameter
I have been trying to parse the request object to get the json parameters but that json is not passing into the request object this is my client side, where I am requesting with json. enter image description here and this is my view enter image description here the output is enter image description here I am expecting to get this data into my view function "query":"hi, this is what you are lookig for!" -
How i get the value (content) of a form in html
I wanna get the value of {{q.op1}} in html. How can i fix this? <div class="form-check"> <input class="form-check-input" type="radio" name="answer" id="gridRadios1" value="option1" checked> <label class="form-check-label" for="gridRadios1"> {{q.op1}} # here </label> </div> if i use in views.py request.POST.get(q.op1) i get None but i wann the value of the choice. -
How to add a Django custom signal to worked out request
I have a Django project and some foreign API's inside it. So, I have a script, that changes product stocks in my store via marketplace's API. And in my views.py I have a CreateAPIView class, that addresses to marketplace's API method, that allows to get product stocks, and writes it to MYSQL DB. Now I have to add a signal to start CreateAPIView class (to get and add changed stocks data) immediately after marketplace's change stocks method worked out. I know how to add a Django signal with pre_save and post_save, but I don't know how to add a singal on request. I found some like this: from django.core.signals import request_finished from django.dispatch import receiver @receiver(request_finished) def my_callback(sender, **kwargs): print("Request finished!") But it is not that I'm looking for. I need a signal to start an CreateAPIView class after another api class finished its request. I will be very thankfull for any advise how to solve this problem. -
can access django admin through nginx port 80 but not port 81
I can access Django admin by redirecting traffic from nginx port 80 to django port 8000. However, when I change nginx listen port to 81 I received, after signing in Django admin Forbidden (403) CSRF verification failed. Request aborted. nginx.conf server { listen 81; server_name localhost; location = /favicon.ico {access_log off;log_not_found off;} location /static/ { include /etc/nginx/mime.types; alias /static/; } location / { proxy_pass http://backend:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } docker-compose file version: '3.9' services: backend: image: thequy/resume_builder_django:2.0 build: context: ./backend dockerfile: ./docker/django/Dockerfile env_file: - .env command: gunicorn resume_builder.wsgi -w ${GUNICORN_WORKER_COUNT} -b 0.0.0.0:${DJANGO_PORT} networks: - resume_builder_network backend_nginx: image: thequy/resume_builder_django_nginx:1.0 build: ./backend/docker/nginx ports: - "${BACKEND_DJANGO_PORT}:${BACKEND_DJANGO_PORT}" depends_on: - backend networks: - resume_builder_network networks: resume_builder_network: I tried adding CORS_ALLOW_ALL_ORIGINS=True and CSRF_TRUSTED_ORIGINS="http://backend_nginx:81" but it doesn't help -
how to pass a django variable of an object fetched from the database in css
I want a background image to be an image uploaded by a user the following is what I am trying to do <div class="slider-image" style="background-image: url({{latestArticle.image.url}});"></div> -
Set dynamic values from a dictionary for select values inside a Django template using Javascript or other method
I have three consecutive select options that their values change according to the previous select. The purpose is to categorize products using these select options. First option is to either categorize products with their usage or model value. If usage is selected as the first select option, then the second select that is populated with usages list which is all objects of the Usage model, is shown, and if model is selected, then the select populated with all objects of MainModel model is shown and the other select tag gets hidden with visually-hidden class. To this point, my codes are as below: views.py: def get_common_queryset(): usage_queryset = Usage.objects.all() main_model_queryset = MainModel.objects.all() sub_usage_queryset = SubUsage.objects.all() pump_type_queryset = PumpType.objects.all() queryset_dictionary = { "usage_queryset": usage_queryset, "main_model_queryset": main_model_queryset, "sub_usage_queryset": sub_usage_queryset, "pump_type_queryset": pump_type_queryset, } return queryset_dictionary def solution_main(request): context = get_common_queryset() return render(request, "solutions/solution_main.html", context) my template: <div class="col-md-3 mx-md-5"> <h2 class="h5 nm-text-color fw-bold mb-4">Choose usage or model:</h2> <select required aria-label="Select usage or model" id="usage_model_select" class="form-select" onchange="set_usage_or_model_dic()"> <option>----</option> <option value="usage">Usage</option> <option value="model">Model</option> </select> </div> {# usage or model select div #} <div class="col-md-3 mx-md-5"> {# usage select div #} <div class="usage visually-hidden" id="usage_div"> <h2 class="h5 nm-text-color fw-bold mb-4">Select usage:</h2> <select required aria-label="Select usage" class="form-select" name="usage_select" … -
Reuse test_func for UserPassesTestMixin in Django
Suppose I have 2 view classes class View1(LoginRequiredMixin, UserPassesTestMixin, View): def get(self, request, *args, **kwargs): #Do something and render a page def test_func(self): #Validation logic class View2(LoginRequiredMixin, UserPassesTestMixin, View): def get(self, request, *args, **kwargs): #Do something and response with JsonResponse def test_func(self): #The exact same validation logics as the test_func for View1 How can I in my Django code don't repeat the same test_func twice? -
No module named chess.svg
I am getting the error No module named chess.svg even though I did what the tutorial tell me. views.py: ` from django.shortcuts import render import chess import chess.svg # Create your views here. def index(request): board = chess.svg.board() return render(request, "mychess/index.html", { 'code':board }) I search the internet for the error and expected to find the way to fix but nothing happend. -
APScheduler doesn't work after some time (django)
i used backgroundScheduler for doing a task every 5 minutes and after i deployed it , it worked properly but after about 2 weeks it did the task after 6 hours next time after 4 hours . i didn't change anything at all