Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Filtering items in generic.ListView
I'm creating a game website and i have these models for games: class Game(models.Model): accountant = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='games') title = models.CharField(max_length=50) bank_money = models.IntegerField() player_starting_money = models.IntegerField() golden_card_amount = models.PositiveIntegerField( validators=[ MinValueValidator(100), MaxValueValidator(1000) ] ) now i want every user to see their own games at dashbard: class DashboardView(mixins.LoginRequiredMixin, generic.ListView): template_name = 'games/dashboard.html' model = models.Game how can i do this (show every user their own games, not all games)? -
Displaying in PDF unique values and count of each unique values
I am having a hard time displaying in pdf all unique values of the category and subcategory versus count of each category under the three tight columns which are the severity. Severity has three options (in Bold). The PDF should have four columns: Accident Causation | Accident Causation Sub Category | Damage to Property | Fatal | Non-Fatal Views def fetch_resources(uri, rel): path = os.path.join(uri.replace(settings.STATIC_URL, "")) return path def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result, link_callback=fetch_resources) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None class GenerateInvoice(View): def get(self, request, *args, **kwargs): try: incident_general = IncidentGeneral.objects.filter(user_report__status = 2).distinct('accident_factor') #you can filter using order_id as well except: return HttpResponse("505 Not Found") data = { 'incident_general': incident_general, } pdf = render_to_pdf('pages/generate_report_pdf.html', data) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Accident Causation" #%(data['incident_general.id']) content = "inline; filename='%s'" %(filename) content = "attachment; filename=%s" %(filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") Models class AccidentCausation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) category = models.CharField(max_length=250) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.category class AccidentCausationSub(models.Model): accident_factor = models.ForeignKey(AccidentCausation, on_delete=models.CASCADE) sub_category = models.CharField(max_length=250, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.sub_category class IncidentGeneral(models.Model): … -
Prevent Url Form from clearing out
I am currently working on a Django project and wanted to create a form that includes the invitation link as the initial URL and a field for the maximum usage of that link. However, when I decide that I want to publish this link, the form is cleared, so the user is not able to publish the link afterwards. Any ideas on how to prevent this or is there another way to solve this problem. form in forms.py view in views.py functions in functions.py -
Scheduling libraries in Python [closed]
I have a requirement where I need to schedule a job in Django. I had gone through various libraries but one issue those libraries didn't resolve is multiple runs of job if the same instance of my app is running on multiple pods. Is there a library which resolves this issue or any other way to resolve this issue? Thanks -
Send filtered data using django via email
i want filter the student data by the skills in the vacancy and then send it to the company who posted the requirements in vacancy via email.does anyone have idea about this. ** The Model** class Student(models.Model): name = models.CharField(max_length=50) skills = models.ManyToManyField(Skill) passout = models.ManyToManyField(Passout) email = models.EmailField(max_length=254 ,null = True) resume = models.ImageField(upload_to='media/resume', height_field=None, width_field=None, max_length=None , null=True) create_date = models.DateTimeField('created date',auto_now_add=True) def __str__(self): return self.name class Company(models.Model): comp_name = models.CharField(max_length=50) loc = models.CharField(max_length=50) hr_name = models.CharField(max_length=50) hr_email = models.EmailField(max_length=254) def __str__(self): return self.comp_name class Vacanccy(models.Model): com_name = models.ForeignKey(Company, on_delete=models.CASCADE) skillreq = models.ManyToManyField(Skill) yearofpass = models.ManyToManyField(Passout) title = models.CharField(max_length=255) expiry_date = models.CharField(max_length=50) def __str__(self): return str(self.com_name) -
Paramiko exec_command, can't make code awaits for task to be completed
I am building a django app under docker. In the views I call a task where paramiko makes a ssh connection from a container to another to run a third party app. The problem is that during the call to the other container I zip the 'results' folder and move it to another place. This requires a bit. The code though goes back to the views and looks for the zip file before it appears where it should be. tasks.py @shared_task() def my_task(): command2 = f"""sudo cp /.../ibt1.msh /.../ibt1.msh && \n cd /... && \n sed -i 's/BUBB MASS.*LECT expl TERM/BUBB MASS {chargeMass} LECT expl TERM/g' ./ibt1.epx && \n sed -i 's/XC.*YC/XC {chargeLon} YC/g' ./ibt1.epx && \n sed -i 's/YC.*ZC/YC {chargeLat} ZC/g' ./ibt1.epx && \n sed -i 's/ZC.*R/ZC 0 R/g' ./ibt1.epx && \n sudo cp ./ibt1.epx ../castemData/ibt1.epx && \n pwd && \n ./europlexus ./ibt1.epx && \n sudo cp ./ibt1.msh ./output/ibt1.msh && \n sudo cp ./ibt1.epx ./output/ibt1.epx && \n sudo cp ./ibt1.listing ./output/ibt1.listing && \n until sudo zip -r result.zip ./output/; do sleep 5; done && \n until sudo mv result.zip /europlexusData/result.zip; do sleep 5; done && \n sudo rm -rf ./output """ host2 = "+" port = ++ username = … -
Django threads working differently with manage.py and gunicorn
I am working in a Django project with REST API that needs to work without a database, so the data is saved in a static dict. The app uses two different datasets that provide information about roads. One of the datasets provides some static data (it might be updated, at most once or twice a year), and the other one provides dynamic data (updated every 5 minutes). The dict will contain an element for each road, each element is created when the static dataset is read, and is updated with the dynamic data every 5 minutes when the dynamic dataset is read. Inside the APP, the static data is read by the main thread, and then is updated once a month by a second thread. The dynamic data is read by a third thread every 5 minutes. When a GET request is sent to the REST API, it should return the content of this dict. It works fine when the app is executed through the "manage.py runserver" command. However, after exporting the project to a docker image (that uses gunicorn), when the app is running, the GET request doesn't get the dynamic data on response, but only the static one … -
Django get queryset with column from another model
Hello this is my model related to default AUTH_USER_MODEL by OneToOneField: class Additional(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) vut_id = models.IntegerField() edit_right = models.BooleanField(default = False) add_access_right = models.BooleanField(default = False) and I need to get Queryset of data Additional model with username from model AUTH_USER_MODEL. If used select_related (Additional.objects.select_related('user').all() ) it returned only id of user: { "model": "authentication.additional", "pk": 13, "fields": { "user": 15, "vut_id": 123456, "edit_right": false, "add_access_right": false } } how i want it to looks like: { "model": "authentication.additional", "pk": 13, "fields": { "username": "user1", "vut_id": 123456, "edit_right": false, "add_access_right": false } } -
django next and previous button in detail page
I’m trying to create a next and previous button on a single(detail) page. I don’t understand how to make this happen. These are my codes views.py def playsong(request, id,slug, tag_slug=None): beat= Number_beat.objects.get(created_beats=id) album = Album.objects.get(album_id= id) albu = Album_beats.objects.filter(album_name= id) bea=Beats.objects.all() nextbeat = Number_beat.objects.filter(id__gt = beat.id).order_by(‘id’).first() #.values(‘id’)[:1] lastbeat = Number_beat.objects.filter(id__lt= beat.id).order_by(‘id’).last() tag= None if tag_slug: tag = get_object_or_404(Tag,slug=tag_slug) beat=beat.filter(tags__in=[tag]) context={ 'beat':beat, 'nextbeat':nextbeat, 'lastbeat':lastbeat, 'album':album, 'albu':albu, } return render(request, 'music/playsong.html', context) html {% if lastbeat %} <li class="page-item"> <a class="page-link" href="{% url 'playsong' lastbeat %}?{{ request.GET.urlencode }}" id="pred">{{ lastbeat }}</a> </li> {% else %} <li class="page-item"> <a class="page-link" href="{% url 'index' %}" id="pred">home</a> </li> {% endif %} {% if nextbeat %} <li class="page-item"> <a class="page-link" href="{% url 'playsong' %}?next={{ nextbeat|urlencode }}" id="predj">{{nextbeat}}</a> </li> {% else %} <li class="page-item"> <a class="page-link" href="{% url 'index' %}" id="pred">home</a> </li> {% endif %} please can anyone help on can I do -
Does race condition(lost update or write skew) happen in Django admin?
In Django views, we can use select_for_update() to prevent race condition(lost update or write skew) so race condition doesn't happen in Django views with select_for_update(). But, even though I googled, I couldn't find any information saying "in Django admin, race condition doesn't happen or select_for_update() is used to prevent race condition". So, in Django admin, does race condition happen? If so, are there any ways to prevent race condition in Django admin? If not, is select_for_update() or other way used to prevent race condition in Django admin? and can I see the code for me? -
Why user.has_perm() is always returning false even after adding permission to user object by first instantiating it?
python manage.py shell code and all the outputs >>> user1 = users[2] >>> print(user1.username) esther >>> print(exam_permissions[3]) core | exam | Can view exam >>> print(user1.has_perm(exam_permissions[3])) False >>> user1.user_permissions.add(exam_permissions[3]) >>> print(user1.has_perm(exam_permissions[3])) False >>> -
Why my django4 Static JavaScript is not working?
My html: {% load static %} <!doctype html> <html lang="en"> <head> <!-- Bootstrap CSS --> <link rel="stylesheet" type="text/css" href="{% static 'bootstrap/css/bootstrap-grid.min.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'bootstrap/css/bootstrap-reboot.min.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'bootstrap/css/bootstrap.min.css' %}" /> <!-- Own CSS --> <link rel="stylesheet" type="text/css" href="{% static 'news/css/base.css' %}" /> </head> <body> <div class="topnav" id="myTopnav"> <a href="#home" class="active">Home</a> <a href="#news">News</a> <a href="#contact">Contact</a> <div class="dropdown"> <button class="dropbtn">Dropdown <i class="fa fa-caret-down"></i> </button> <div class="dropdown-content"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> </div> </div> <a href="#about">About</a> <a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="myFunction()">&#9776;</a> </div> <div style="padding-left:16px"> <h2>Responsive Topnav with Dropdown</h2> <p>Resize the browser window to see how it works.</p> <p>Hover over the dropdown button to open the dropdown menu.</p> </div> <!--First own js, then other js--> <script type="text/javascript" src="{% static 'news/js/base.js' %}"></script> <script type="text/javascript" src="{% static 'bootstrap/js/bootstrap.bundle.min.js' %}"></script> <script type="text/javascript" src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script> </body> </html> My dir: blog --news --template --static ----bootstrap ------css ------js ----news ------css --------base.css ------js --------base.js --media Settings and urls: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ STATIC_DIR, ] urlpatterns += staticfiles_urlpatterns() if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) my base.js: function myFunction() { var … -
Dynamic updating & HTMX
I have this form setup This is what I want to happen; when the user selects an "Indoor Manufacturer" it then provides a list of "Indoor Models" that belongs to the "Indoor Manufacturer". The same thing for "Outdoor Manufacturer" & its Corresponding "Outdoor Models" I can get the above to work fine using HTMX using my code below However, the next step is to add to the HTMX the "Indoor/ Outdoor Same" checkbox, which will copy the data from "Indoor Manufacturer" to "Outdoor Manufacturer". I tried implementing the basics of what I know, but it's not quite doing what I want - in that it is copying over the data, but only once on the first load forms from django import forms from.models import Maintenance from . import models from units.models import System, Cooler, Make from installs.models import Install from bootstrap_datepicker_plus import DatePickerInput, DateTimePickerInput from dynamic_forms import DynamicField, DynamicFormMixin class CreateSystem(DynamicFormMixin, forms.ModelForm): def indoor_choices(form): owner = form['indoor_manufacturer'].value() return Cooler.objects.filter(manufacturer=owner, in_out="indoor") def indoor_initial(form): owner = form['indoor_manufacturer'].value() return Cooler.objects.filter(manufacturer=owner, in_out="indoor").first() def outdoor_choices(form): owner = form['outdoor_manufacturer'].value() return Cooler.objects.filter(manufacturer=owner, in_out="outdoor") def outdoor_initial(form): owner = form['outdoor_manufacturer'].value() #print (form['outdoor_manufacturer'].value()) return Cooler.objects.filter(manufacturer=owner, in_out="outdoor").first() def outdoor_manufacturer_choices(form): same_mamanufacturer = (form['manufacturer_boolean'].value()) condition = (form['indoor_manufacturer'].value()) if same_mamanufacturer is False: return Make.objects.all() … -
How to solve django.db.utils.OperationalError: (2005, "Unknown MySQL server host 'db' (8)")?
I am getting the error on Django after using python3 manage.py runserver on my computer. Error: django.db.utils.OperationalError: (2005, "Unknown MySQL server host 'db' (8)") Why is this error happening? -
ProgrammingError at /products/fetch/ relation"api_product" does not exist LINE 1: ...roduct"."price", "api_product"."description" FROM "api_produ
version: '2' services: products_web: build: ./products command: bash -c "python3 ./products/manage.py makemigrations && python3 ./products/manage.py migrate && python3 ./products/manage.py makemigrations api && python3 ./products/manage.py migrate api && python3 ./products/manage.py runserver 0.0.0.0:8001" volumes: - .:/code ports: - 8001:8001 restart: always depends_on: - db links: - db emails_web: build: ./emails command: bash -c "python3 ./emails/manage.py makemigrations && python3 ./emails/manage.py migrate && python3 ./products/manage.py makemigrations api && python3 ./products/manage.py migrate api && python3 ./emails/manage.py runserver 0.0.0.0:8002" volumes: - .:/code ports: - 8002:8002 restart: always depends_on: - db links: - db orders_web: build: ./orders command: bash -c "python3 ./orders/manage.py makemigrations && python3 ./orders/manage.py migrate && python3 ./products/manage.py makemigrations api && python3 ./products/manage.py migrate api && python3 ./orders/manage.py runserver 0.0.0.0:8003" volumes: - .:/code ports: - 8003:8003 restart: always depends_on: - db links: - db db: image: postgres:10.0-alpine restart: always # volumes: # - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=myuser - POSTGRES_PASSWORD=mypass - POSTGRES_DB=db ports: - 5432:5432 nginx: image: nginx:latest build: ./web ports: - "10080:80" - "10443:443" links: - products_web - orders_web - emails_web depends_on: - products_web - orders_web - emails_web migrate has not being done properly in docker -
Showing Field Data On Another View
Thank You, trying to show the created_date field to the front table but i get an error, if i don't filter and use the all() method i am able to populate all the field data, but i would like to populate created_date field of member.I Get KEY ERROR "list_id" class ListListView(ListView): model = HBTYList template_name = "accounts/modals/nomodal/index.html" paginate_by = 3 def get_queryset(self): qs = self.model.objects.all().order_by('-id') p_f = HbtyCustomerListFilter(self.request.GET, queryset=qs) return p_f.qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['dc'] = HBTYItem.objects.filter(hbty_cust_id=self.kwargs["list_id"]) #Fix this method to show created_data context['filter'] = HbtyCustomerListFilter(self.request.GET, queryset=self.get_queryset()) return context -
where to store 1TB media-file in Django project?
I have a Linux server and a Django project on it. My website opens files that can have enormous sizes. Like 100-500GB or even 1,2TB. Now I just drag and drop these files to "Staticfiles" folder inside my Django project. I use Filezilla for this. But is it a general practice to store such big files inside the Django file system? Or there is a way to store them somewhere outside? Because I think that there should be some "storage" independent from the Django project where I can store my big files. If you have experience with that It would be great if you share your opinion. -
Django Import-export imagefield in excel cell
I can't seem to find any answer to how can I import an excel file with a cell that represents an ImageField. -
Pulling data in the project I'm using SQlite
I am using Sqlite database in my project that I created with Django. While this project is running on the server, I see that the data entered in the system is not written to the sqlite database file, but it exists in the system, how can I access this data? -
Need to scrape all products using selenium and beautifulSoup in python
We need to scrape all products(5347 products, 50 pages) using selenium and beautifulsoup in python. The website is not working in our region and proxy(vpn) can't help us. Website link is https://www.target.com/c/makeup-beauty/-/N-5xu1e can someone provide the code to scrape, please? -
ImportError: cannot import name 'RightsMaster' from partially initialized module 'DATABASE.models' (most likely due to a circular import)
from DATABASE.models import ModuleMaster, PageMaster, RightsMaster ImportError: cannot import name 'RightsMaster' from partially initialized module 'DATABASE.models' (most likely due to a circular import) (C:\Users\ADMIN\Desktop\python server\DATABASE\models_init_.py) module_page.py from django.db import models class ModuleMaster(models.Model): active = models.BooleanField(default=True) id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=80) icon_class = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Meta: managed = False db_table = 'module_master' class PageMaster(models.Model): id = models.BigAutoField(primary_key=True) active = models.BooleanField(default=True) module = models.ForeignKey(ModuleMaster, models.DO_NOTHING) name = models.CharField(max_length=80) path = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Meta: managed = False db_table = 'page_master' rights_master.py from django.db import models class RightsMaster(models.Model): full_name = models.CharField(max_length=30, default='', blank=True, null=True) short_name = models.CharField(max_length=4, default='') description = models.CharField(max_length=80, default='', blank=True, null=True) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'rights_master' user_rights.py from django.db import models from DATABASE.models import ModuleMaster, PageMaster, RightsMaster class UserRights(models.Model): user = models.CharField(max_length=30) right = models.ForeignKey(RightsMaster, models.CASCADE) module = models.ForeignKey(ModuleMaster, models.CASCADE) page = models.ForeignKey(PageMaster, models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'user_rights' init.py from .profocus_py.module_page import ModuleMaster, PageMaster from .profocus_py.user_rights import UserRights from .profocus_py.rights_master import RightsMaster -
How to read CSV and EXL file using Django rest framework and store it into the model
I have gone through several blogs and youtube tutorials to understand how to read and store CSV and xls file data in a database and avoid duplication of the data, but I did not get a proper result, can someone please tell me how to achieve this using inbuilt CSV and openxls module. Thank You -
Docker can't pull postgres image: "no matching manifest for windows/amd64 10.0.22000 in the manifest list entries"
i'm creating a new django project and my DB is Postgresql. it was fine and everything was ok until one day when i tried to start docker i saw this: "Not enough memory to start docker". I found this and it worked and docker desktop started perfectly. but now when i'm trying to run docker-compose up i get this: [+] Running 0/1 - db Pulling 3.3s no matching manifest for windows/amd64 10.0.22000 in the manifest list entries this is docker-compose.yml db part: db: image: postgres:14 environment: - "POSTGRES_HOST_AUTH_METHOD=trust" I even tried docker pull postgres:14 but it's same: 14: Pulling from library/postgres no matching manifest for windows/amd64 10.0.22000 in the manifest list entries -
Show other contents besides a form in FormView?
I really dislike django CBS design which makes things without flexibility. I would like to have a page whose upper part showing the content of objects and lower part has a form to be posted. CBS formview class EditStudent(FormView): template_name = "editstudent.html" model = models.Student success_url = "/home" How can I retriev objects of studens and show them on the template. Thanks. -
i have a django data of time, i can't add it as time input field value
I have a django model with a field of time. also I created a custom form with an input field so user can edit. If I parse this time as text input valur it show, but if it is time input and given the value time in it, the value is not shown how to solve this?