Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
"from captcha.fields import RecatchaFields" Is not recognized by Pylance
making a Django project and wanted to use Google's Recaptcha API in order to fight off bots. I've followed several installation KBs, watched tutorials, and I'm using these two as my installation guide: https://pypi.org/project/django-recaptcha/ https://django-simple-captcha.readthedocs.io/en/latest/usage.html Despite following their instructions, none of them seem to be importing correctly, Pylance doesn't recognize 'captcha' when importing in a form.py file. I'm even copying and pasting from their website just for this post's sake. from captcha.fields import CaptchaField These seem to be what I need in order to properly set up the API - I've even placed in the correct secret keys. The problem seems to be when I attempt to use it on a form/model .py file. Yes, I have installed in in installed apps - it's simple: INSTALLED_APPS = [ ... "captcha", ] I have even tried: INSTALLED_APPS = [ ... 'captcha', ] Not sure if load order has anything to do with the issue, and most tutorials seem to have the widget working right after this step. I have also made sure to set the urls.py files up according to the KB: urlpatterns += [ ..., path('captcha/', include('captcha.urls')), ..., ] I've uninstalled and reinstalled the plugin several times now, that isn't … -
Django: Multiple inputs with foreign key
I wanted to add more users for a shift. But it's a foreign key. How to do I make it? It does add, but if I choose more than one user, it shows this. Field 'id' expected a number but got ['1', '2'] Should I convert it to string? I don't know how to do it. Below is my code. models.py class User(models.Model): user_name = models.CharField(max_length=32, unique=True) pass_word = models.CharField(max_length=150,) email = models.EmailField(blank=True, unique=True) phone = models.CharField(max_length=32, unique=True) is_active = models.BooleanField(default=True,) class Attendance(models.Model): RosteringUserDate = models.ForeignKey(RosteringUserDate, on_delete=models.CASCADE, null=True) date = models.DateField() user = models.ForeignKey(User, on_delete=models.CASCADE) begin_time = models.TimeField(default="") end_time = models.TimeField(default="") work_time = models.CharField(max_length=64, default='') views.py def shift_add(request): queryset = User.objects.all() if request.method == 'GET': return render(request, 'attendance/shift_add.html', {'queryset': queryset}) if request.method == "POST": Attendance.objects.create( user_id = request.POST.getlist('user_name',[]), date = request.POST.get('date'), RosteringUserDate_id = request.POST.get('RosteringUserDate_id'), begin_time = request.POST.get('begin_time'), end_time = request.POST.get('end_time'), work_time = request.POST.get('work_time'), ) return redirect('/user/attendance/') forms.py <form method="post" action="/user/attendance_administrators/shift/add/"> <div class="form-group"> <input type="text" name="name" class="form-control" required> </div> <div class="form-group"> <input type="date" name="date" class="form-control" required> </div> <div class="form-group"> <input type="text" name="RosteringUserDate_id" class="form-control" required> </div> <div class="form-group"> <input type="time" name="begin_time" class="form-control" required> </div> <div class="form-group"> <input type="time" name="end_time" class="form-control" required> </div> <div class="form-group"> <input type="text" name="work_time" class="form-control" required> </div> <div class="form-group"> … -
Unit Testing Python Google Sheet
How would I unit test this part of my code?: creds = Credentials.from_service_account_info( json.loads(json.loads(creds_service_account)), scopes=scope ) class GoogleSheet: def __init__( self ): self.authenticate() def authenticate(self): scope = [ "https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive", ] # b64 decode, then utf decode, then jsonload. Super straightforward decoded = base64.b64decode(settings.PAYMENT_GOOGLE_SHEET_CREDS) creds_service_account = decoded.decode("utf8") creds = Credentials.from_service_account_info( json.loads(json.loads(creds_service_account)), scopes=scope ) client = gspread.authorize(creds) # self.sheet = client.open(GOOGLE_SHEET_TITLE).sheet1 self.sheet = client.open(GOOGLE_SHEET_TITLE).worksheet( GOOGLE_SHEET_WORKSHEET_NAME ) I tried this, but I might be off track here as it's not working, it still wants the proper json.loads(json.loads(creds_service_account)), scopes=scope: with patch('google.oauth2.service_account.Credentials.from_service_account_info', new=Mock(return_value=True)): -
'CourseTake' object has no attribute 'points'
class SimpleCourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ['title','credit_hours'] class CourseTakeSerializer(serializers.ModelSerializer): course = SimpleCourseSerializer() points = serializers.SerializerMethodField() grade_points = serializers.SerializerMethodField() class Meta: model = CourseTake fields = ['id','course', 'grade', 'points', 'grade_points'] def get_points(self, coursetake: CourseTake): if coursetake.grade >= 90: return '4' elif coursetake.grade >= 70: return '3' elif coursetake.grade >= 50: return '2' return '1' #TRY AND ERROR #Terminal: 'CourseTake' object has no attribute 'points' def get_grade_points(self, coursetake: CourseTake): return coursetake.course.credit_hours * coursetake.points I want to calculate grade points, which will be used later to calculate each student's GPA score. So the get_grade_point() will return the credit_hours * points. My problem is that the points field is not part of the model or serializer. I created a function to calculate the points for each course. Because I defined the points, Django keeps saying it's not an attribute anytime I try to access the point values. Is there a way to access the points value inside the get_grade_function? Image for better view -
Django annotate multiple aggregators over grouped values
Due to the structure of my project, I need to have multiple aggregations over three interlocked tables. With structure looking somewhat like this: class ItemMeta(models.Model): item = models.ForeignKey( Item, on_delete=models.SET_NULL, null=True ) class = models.CharField(max_length=2048, null=True, blank=True) department = models.CharField(max_length=2048, null=True, blank=True) class Item(models.Model): amount = models.DecimalField(max_digits=18, decimal_places=2) status = models.CharField(max_length=2048, null=True, blank=True, choices=ItemStatus.choices) class CartItem(models.Model): author = models.ForeignKey(to=UserModel, on_delete=model.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) class ItemStatus(models.TextChoices): UNDER_CONSIDERATION = 'UNDER_CONSIDERATION', 'Under consideration' IMPOSED = 'IMPOSED', 'Imposed' PAID = 'PAID', 'Paid' And I need to have item grouping by class, department and status both in cart and outside of it. I also need to have aggregations of prices of items in different statuses, as well as amount of different items in cart and existing. So the structure of the response has to always contain 5 values: sum of paid, imposed and considered items, and count of items existing and in cart of the calling user. I inherited from last poor sod this piece of code to do these: def _sum(self, status): return Coalesce(Sum('amount', filter=Q(status=status)), 0.0, output_field=FloatField()) def annotate_kwargs(self): return { 'under_consideration_amount': self._sum(ItemStatus.UNDER_CONSIDERATION), 'imposed_amount': self._sum(ItemStatus.IMPOSED), 'paid_amount': self._sum(ItemStatus.PAID), 'count': Count('pk', distinct=True), 'in_cart': Count('pk', distinct=True, filter=Q(cartitem__author=self.user)), } def get(self): return self.queryset \ .values(*self.group_by) \ .annotate(**self.annotate_kwargs()) … -
How to get rid of dict_keys() in my django template?
I am trying to print comma separated key values after drilling into a dictionary. But I am unable to get rid of dict_keys() that shows in my output. Here is my template: metrics.html <h1>Accessing values</h1> <p>{{ final_metrics.values }} </p> <p>{{final_metrics.data.0.13.browser.Chrome}}</p> <h1>{{ final_metrics.month }} Clicks Statistics</h1> <p>Short Url: {{final_metrics.short_url }}</p> <p>Date Accessed: {{ final_metrics.data.0.keys }}</p> <p>Browser: {{final_metrics.data.0.13.browser.keys}}</p> <p>Platform: {{final_metrics.data.0.13.platform.keys}}</p> and on the output screen it shows as follows Is there a way to get rid of the dict_keys() and have those values in a comma separated format? I have tried the solutions from https://stackoverflow.com/a/8000091 and https://stackoverflow.com/a/34542858 but does not seem to work for me.