Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
DRF unable to get request.data from vue
I am developing a system with vue and django. I have tested my djang URL successfully by input .../?admin_phone=XXX&admin_password=XXX. But however, when I send data from vue side, it failed and the print result code i wrote in django shows nothing, can anyone know what wrong with my code? this is my vue code: enter image description here enter image description here and here is my drf code: enter image description here this is the result: enter image description here thank you give me some suggestion -
Inspect db Issue
I am working on a Django project but when I perform the database inspection in the app and try to run the project it fails with the following error. OSError: [WinError 123] The filename, directory name or volume tag syntax is not correct: '' What is the best way to handle this? This is my database config DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': 'pos_service', 'USER': 'demoLogin', 'PASSWORD': 'demoLogin', 'HOST': 'LAPTOP-EQ88J4ES\SQLLOCAL', 'PORT': '1433', 'OPTIONS': { 'driver' : 'ODBC Driver 13 for SQL Server' } } } How is the correct way to inspect a database in Django and how would be the best way to import each of the classes? -
Is the level of protection in Next js too high? [closed]
Is the level of protection in Next js too high if they are used as a ForntEnd in terms of uploading and receiving files and opening sessions with django rest APIs ? Knowing that the program contains financial correspondence and important data, and high protection is very necessary! Is the framework weak with attacks the CSRF and another attacks? What do you advise me to use from a framework, taking into account high security and speed at the same time؟ Is react js work with it? And final Thanks in advance. -
Django Rest Framework - adding permissions for views based on groups?
TLDR: How do you permit specific Groups access to views using Django Rest Framework? I'm in the process of building a web service with the Django Rest Framework. Only a (proper) subset of the views are intended to be available to customers. So far, I've: set the default permission to rest_framework.permissions.IsAdminUser created a permission called is_customer (using the Django admin website) created a Group called customers and added all relevant users to this group (using the admin website) added the is_customer permission to customers (again using the admin website) All of my views are function-based. To provide the appropriate permission to the customers group, I've tried from rest_framework.decorators import api_view from django.contrib.auth.decorators import permission_required @api_view(["POST"]) @permission_required(["is_customer"]) def my_func(request): # calculations return Response(...) and from rest_framework.decorators permission_classes, api_view @api_view(["POST"]) @permission_classes(["is_customer"]) def my_func(request): # calculations return Response(...) and neither seems to be working. What is the proper way to go about this? Thanks in advance for any advice! -
ASGI channels django
Пытаюсь запустить сервер с django framework, чтоб использовались каналы, т.е. должно быть так: Starting ASGI/Channels version 4.0.0 development server at http://127.0.0.1:8000/ а получается стандартный запуск такой: Starting development server at http://127.0.0.1:8000/ Что я делаю не так? asgi.py # import os from channels.routing import ProtocolTypeRouter from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'SpareParts.settings') application = ProtocolTypeRouter({ 'http': get_asgi_application(), }) settings.py INSTALLED_APPS = [ 'channels', ASGI_APPLICATION = "SpareParts.asgi.application" Перепробовал кучу всего. Если как-то выразился не так, дайте понять - добавлю информации -
Is there "non-lazy mode" or "strict mode" for "querysets" in Django?
When I use select_for_update() and update() of a queryset together as shown below: # "store/views.py" from django.db import transaction from .models import Person from django.http import HttpResponse @transaction.atomic def test(request): # Here # Here print(Person.objects.select_for_update().filter(id=1).update(name="Tom")) return HttpResponse("Test") Only UPDATE query is run without SELECT FOR UPDATE query as shown below. *I use PostgreSQL and these logs below are the queries of PostgreSQL and you can check on PostgreSQL, how to log queries with transaction queries such as "BEGIN" and "COMMIT": But, when I use select_for_update() and update() of a queryset separately then put print(qs) between them as shown below: # "store/views.py" from django.db import transaction from .models import Person from django.http import HttpResponse @transaction.atomic def test(request): qs = Person.objects.select_for_update().filter(id=1) print(qs) # Here qs.update(name="Tom") return HttpResponse("Test") SELECT FOR UPDATE and UPDATE queries are run as shown below: Actually, this example above occurs because QuerySets are lazy according to the Django documentation below: QuerySets are lazy – the act of creating a QuerySet doesn’t involve any database activity. You can stack filters together all day long, and Django won’t actually run the query until the QuerySet is evaluated. But, this is not simple for me. I just want normal database behavior. Now, … -
Trying to connect from a docker container to docker host running Django in development mode gets connection refused
I'm running a django development server in my Debian GNU/Linux host machine with python manage.py runserver. After running a Debian docker container with $ docker run -it --add-host=host.docker.internal:host-gateway debian bash I expected I could make a curl in http://localhost:8000 with curl http://host.docker.internal:8000 but I get Failed to connect to host.docker.internal port 8000: Connection refused Is it something related to running Django with python manage.py runserver? -
Need help in Python Django for fetch the records from DB which will expire in 30 days
I wrote an application where there is a requirment to display only those records which will expire is next 30 day. models.py class SarnarLogs(models.Model): request_type_choice = ( ('NAR', 'NAR'), ) source = models.CharField(max_length=100) expiry_date = models.DateField() def __str__(self): return self.source Views.py @login_required(login_url=('/login')) def expiry_requests(request): Thirty_day = end_date = datetime.now().date() + timedelta(days=30) posts = SarnarLogs.expiry_date.filter(expiry_date = Thirty_day) context = {"console_data": posts, "user":request.user.full_name} return render(request, 'expiry_requests.html', context=context) -
how to select more options in "ManyToManyField()"?
i wanted to create a tag option for a a music model , well mainly musics accept more than one tag and there are amny kind of genres and tags ,so i wanted to make a ManyToManyField() that you can set more than 1 value ,also if you tag is not in add it in. to do that i thought maybe can make another CharField() then adding it to tag_name : #posts model name = models.CharField(max_length=200) band = models.CharField(max_length=200) release = models.DateTimeField() tag_add = models.CharField(max_length=100) tags = models.ManyToManyField(Tags) #cover = models.ImageField(upload_to='media/image') #file = models.FileField(upload_to='media/audio') class Meta(self): ordering = ['release'] def __str__(self): return self.name def get_absolute_url(self): return reverse('pages:music_detail',args=[str(self.id)]) class Tags(models.Model): tag_name = models.CharField(max_length=100) but i stuck here too ,i really dont know how to add a models field data to another models field ? i would appreciate if you guide me here -
I was running a test on my signal.py file and i am getting 'ValueError: seek of closed file' error
here is the signals.py file inside main app and here is the test_signals.py file enter image description here the full error is