Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pass a .zip file to a Docker container using python
I am using the Docker SDK to try and push a file from a Django web request method of POST to a Docker container. In my use case, the .zip file cannot touch the local machines file directory or load into memory. The file must go straight to the Docker container. This is the code I have so far but I cannot seem to find a way to get a file to passthrough to the container and get back command output from the commands I am running. Any help would be greatly appreciated. import docker client = docker.from_env() # start the container container = client.containers.run( image='myimage:latest', command='mkdir /tmp/upload', remove=True, detach=True, network_mode='none', ) try: # write the uploaded file to the container's file system container_id = container.id container_exec_command = f'cat > /tmp/upload/{zipfile.name}' _, stream = container.exec_run(cmd=container_exec_command, stream=True) with zipfile as f: for chunk in f.chunks(): stream.write(chunk) # perform the rest of the processing inside the container container_exec_command = f""" cd /tmp/upload # unzip the file echo y | unzip -P {filePassword} {zipfile.name} # get the filename of the other file in the directory filename=$(find . -maxdepth 1 -type f ! -name '*.zip' -printf "%f\n") # run sha256 sum against it, then … -
Pass an argument to a url with hx-get
I'm using HTMX to render different partial templates in a 'group-detail' page. The get requests are triggered by click event, and rendered in a tag. However, I'm trying to pass the group information so I can render the correct information in the partial template, but the data isn't being rendered. <li><a hx-trigger="click" hx-get="{% url 'groups:info' group.slug %}" hx-target="#group-content" class="btn btn-outline btn-rounded btn-tertiary btn-with-arrow mb-2">Info<span><i class="fas fa-chevron-right"></i></span></a></li> Here I'm passing the slug argument so it can know which group data render. This is the partial view: def group_info(request, slug): group = Group.objects.filter(slug=slug) context = { 'group' : group } return render(request, 'groups/partials/info.html', context) And I'm trying to render {{group.name}} in the info.html template for example, but nothing gets shown (the correct slug is being passed, the correct template is being rendered, but not the {{}} tags). Not getting any error neither. Am I missing something on passing URL arguments with htmx? -
Creating an event driven architecture using Django
I would like to create an event driven architecture in Django. Every time a database record is created, updated or deleted, i would like to create and event, posting it to a queue ( like kafka, sqs, or something similiar). I know that Django has a post_save method, that I could use to capture the record and post it in a queue, but I suppose that I could suffer for a dual write problem, i.e., update the database, but fails to post message in the queue. Does Django have any different mecanism? Does Django retry the post_save method? Should I use a outbox pattern or process database bin log instead? -
Why is timezone.now showing a future date when being applied as a default value to DateField in django
Here are the relevant settings in my project: settings.py TIME_ZONE = "US/Mountain" USE_TZ = True models.py (using timezone.now) class Submission(models.Model): date_created = models.DateField( default=timezone.now, blank=True, ) datetime_created = models.DateTimeField( default=timezone.now, ) If I create a Submission at 5PM MST on 03/01/2023 these are the values I get: date_created: "2023-03-02" datetime_created: "2023-03-01 17:00:00-07:00" Why would date_created be using the date of the following date? -
Using Django DecimalField with Select Widget
I'm not sure if there is something special I should be doing but I have a model and form similar to the following; # models.py from django.db import models class ObjectModel(models.Model): object = models.DecimalField(max_digits=10, decimal_places=2) # my_settings.py from decimal import Decimal object_choices = [ (Decimal('1'),'1'), (Decimal('1.5'),'1.5'), (Decimal('2'),'2'), (Decimal('2.5'),'2.5'), (Decimal('3'),'2.5'), ] # forms.py from django import forms from my_settings import object_choices from models import ObjectModel class ObjectForm(forms.ModelForm): object = forms.ChoiceField(choices = object_choices) class Meta: model = ObjectModel fields = ['object'] The form renders fine, and saves the object without any problem. I can see in the Django Admin that the value I select on the form gets saved to the model, and all the other fields (not shown above) render and work fine. When I load a form to edit the model rather than create a new one, e.g views.py from forms import ObjectForm ... form = ObjectForm(instance = obj) ... The select widget which renders doesn't have an initial value. If I delete the definition for 'object' in the form definition and let it render with the default text input, everything works as expected and I can see the correct value, the same as I can see in the Django … -
Remote desktop as a website host (VPN access only)
Networking is not a strong skill of mine and I'm currently working on making an internal website for my company and I don't want to make this website available publicly. Basically, we have a remote desktop that we can solely access via VPN and I wonder if it's possible to make that remote desktop as the website host so that no one can access the website except for the ones who are in the VPN? I'll be building the site via Django and python and any guidance would be much appreciated. -
stylesheet only rending for my 'core' app, and not for the rest of my apps in the same directory
For some reason, my stylesheet isn't loading for my other apps. . When I GET http://127.0.0.1:8000/static/style.css, it returns .container { width: 50vw; margin: 50px auto; padding: 25px 10px; background-color: #ffffff; border-radius: 3px; text-align: center; box-shadow: 0 19px 38px rgba(0,0,0,0.30), 0 15px 12px rgba(0, 0, 0, 0.22); } I loaded this for all my templates: {% load static %} <link rel="stylesheet" href="{% static 'style.css' %}"> This loads fine for all my templates in website (this was the first app i created, not sure if that changes anything) When I try to do this for my other apps (chat/friend/accounts) it doesn't apply at all. Does anyone know why this is happening? I don't get any console error for the stylesheet on my other pages.. settings.py: # static STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) -
Referencing more than one field on a Django Model
I am trying to reference 2 fields from a particular django model but it keeps giving me error. The models are displayed below, i want to reference 'building_type' and 'location' from property table to client table class Property(models.Model): location = models.CharField(choices=Property_Location, max_length=120) building_type= models.CharField(choices=Property_Type, max_length=120) initial_quantity= models.IntegerField(null= False, blank= False) quantity_in_stock= models.IntegerField( null= False, blank= False) quantity_sold = models.IntegerField( null= False, blank= False) def __str__(self): return self.location class Client(models.Model): first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) phone = models.IntegerField() email = models.EmailField(max_length=130) building_type= models.ForeignKey(Property,null= False, blank= False, on_delete=models.CASCADE) location= models.ForeignKey(Property, null= False, blank= False, on_delete=models.CASCADE) def __str__(self): return self.first_name + ' '+ self.last_name -
virtual env in django
While I was trying to execute the mkvirtualenv command on the command prompt, I was getting this error: 'mkvirtualenv' is not recognized as an internal or external command, operable program or batch file python 3.10 windows 11 Expecting to create a virtual env -
(fields.E300) Field defines a relation with mode which is either not installed, or is abstract. many to many Model
I have the error message "recipes.Recipe.categories: (fields.E300) Field defines a relation with model 'Catego ry', which is either not installed or is abstract. "I am at a complete loss, even though in my eyes I did everything by the book. Nor am I really any the wiser after analysing my code. The Model Recipe from backend.apps.categories.models import Category class Recipe(models.Model): title = models.CharField( db_index=True, max_length=256, unique=False, null=False, verbose_name=_("Titel") ) lang = models.ForeignKey(Language, on_delete=models.RESTRICT, verbose_name=_("Sprache")) categories = models.ManyToManyField(Category, default=None) settings.py - INSTALLED_APPS "backend.apps.categories", "backend.apps.cookbooks", "backend.apps.cookparty", "backend.apps.customer", "backend.apps.dashboard", "backend.apps.hints", "backend.apps.home", "backend.apps.lexicon", "backend.apps.masterdata", "backend.apps.seo", "backend.apps.service", "backend.apps.user", "backend.apps.recipes", "backend.apps.importer", The Model Category class Category(models.Model): name = models.CharField(max_length=50, unique=True) parent = models.ForeignKey( to="Category", on_delete=models.SET_NULL, default=None, null=True, blank=True ) is_active = models.BooleanField(default=False) slug = models.SlugField(default=None, blank=True, unique=True) In the debug, all apps are listed under 'INSTALLED_APPS'. For me, the error is completely irrational. Does anyone have a tip for me as to which screw I need to turn? -
Django - No such column: rowid when migrating Spatialite database
I am trying to create a database using GeoDjango, but when I try to migrate the database I get "error in trigger ISO_metadata_reference_row_id_value_insert: no such column: rowid". I have added the right database engine and included 'django.contrib.gis', in settings.py. Any ide what the problem might be? from django.contrib.gis.db import models # Create your models here. class Bus(models.Model): busID = models.IntegerField(primary_key=True) route = models.CharField(max_length=20) operator = models.SmallIntegerField() latitude = models.DecimalField( max_digits=8, decimal_places=6) longitude = models.DecimalField( max_digits=8, decimal_places=6) location = models.PointField(srid=4326, blank=True, null=True) updated = models.DateTimeField(blank=True, null=True) lastStop = models.IntegerField(blank=True, null=True) def __str__(self): return self.busID settings.py: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': BASE_DIR / 'db.sqlite3', } } Error: python3 ./manage.py migrate Operations to perform: Apply all migrations: admin, api, auth, contenttypes, sessions Running migrations: Applying admin.0002_logentry_remove_auto_add...Traceback (most recent call last): File "/opt/homebrew/lib/python3.11/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/homebrew/lib/python3.11/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute return Database.Cursor.execute(self, query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ sqlite3.OperationalError: error in trigger ISO_metadata_reference_row_id_value_insert: no such column: rowid The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/vvv/Documents/Prosjekter/mqtt/./manage.py", line 22, in <module> main() File "/Users/vvv/Documents/Prosjekter/mqtt/./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/opt/homebrew/lib/python3.11/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/opt/homebrew/lib/python3.11/site-packages/django/core/management/__init__.py", line … -
Display Username when request is set declined
class PendingRequest(models.Model): book_request = models.ForeignKey(Borrow, on_delete=models.CASCADE, null=True) member = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True) book = models.ForeignKey(Books, on_delete=models.CASCADE, default=None, null=True) approved = models.BooleanField(default=False, verbose_name="Approved") declined = models.BooleanField(default=False, verbose_name="Declined") request_date = models.DateTimeField(auto_now_add=True) approval_date = models.DateTimeField(auto_now=True, null=True) I have a view function that loop through this above model and displays the status of every request in database and renders it out in a table in template. Whenever the request is approved, it displays True and whenever it is declined, it display False. The problem i am facing is that whenever all the request for a user is set to False, it doesn't display the username of the user in member datacell of the table Here is the template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <table border="1"> <thead> <tr> <th>Member</th> <th>Book</th> <th>Request Date</th> <th>Approval Date</th> <th>Status</th> </tr> </thead> <tbody> {% for username, requests in user_requests.items %} {% with num_requests_approved=requests.approved_requests|length num_requests_declined=requests.declined_requests|length %} {% for request in requests.approved_requests %} <tr> {% if forloop.first %} <td rowspan="{{ num_requests_approved|add:num_requests_declined }}"> {{ username }} </td> {% endif %} <td><a href="{{request.book.book.url}}">{{ request.book }}</a></td> <td>{{ request.request_date }}</td> <td>{{ request.approval_date }}</td> <td>{{ request.approved }}</td> </tr> {% endfor %} … -
ResourceWarning: unclosed file <_io.BufferedReader name=
I have used with open but no luck but I still get this error : ResourceWarning: unclosed file <_io.BufferedReader name='/home/idris/Documents/workspace/captiq/captiq/static/docs/CAPTIQ Datenschutzhinweise.pdf'> attachment=customer_profile.get_attachments(), ResourceWarning: Enable tracemalloc to get the object allocation traceback below is my function which the error points to : def get_attachments(self): files = None cp = ( self.cooperation_partner.get_cooperation_partner() if self.cooperation_partner else None) # TODO: improve implementation: too many conditions if cp and cp.custom_attachments.exists(): files = [f.attachment for f in cp.custom_attachments.all()] elif cp and cp.pool.default_b2b_attachments.exists(): files = [ f.attachment for f in cp.pool.default_b2b_attachments.all()] else: files = self.get_default_attachments() if not files: path_one = finders.find( 'docs/file_1.pdf') path_two = finders.find('docs/file_2.pdf') with open(path_one, 'rb') as f1, open(path_two, 'rb') as f2: files = [f1, f2] attachments = [ { 'filename': os.path.basename(attachment.name), 'content': attachment.read(), 'mimetype': mimetypes.guess_type(attachment.name)[0] } for attachment in files] return attachments attachments = [ { 'filename': os.path.basename(attachment.name), 'content': attachment.read(), 'mimetype': mimetypes.guess_type(attachment.name)[0] } for attachment in files] return attachments So the issue is here with this section : with open(path_one, 'rb') as f1, open(path_two, 'rb') as f2: files = [f1, f2] attachments = [ { 'filename': os.path.basename(attachment.name), 'content': attachment.read(), 'mimetype': mimetypes.guess_type(attachment.name)[0] } for attachment in files] return attachments -
pipenv install fails in Django project
i have a django project and when i tried to run python manage.py migrate i git this error django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. and i knew i had to run pipenv install so here is my pipfile and below the error ocures when i try to run pipenv install Note : I tried to open pipenv shell first then install and it didnt work pipfile-> [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django-admin = "*" django = "*" djangorestframework = "*" djangorestframework-simplejwt = "*" drf-yasg = "*" django-cors-headers = "*" django-multiupload = "*" twilio = "*" django-redis = "*" psycopg2-binary = "*" python-dotenv = "*" dj-database-url = "*" django-storages = "*" boto3 = "*" gunicorn = "*" pillow = "*" django-filter = "*" ipdata = "*" pip = "*" install = "*" [dev-packages] black = "*" [requires] python_version = "3.11"` and here is the error I get when i run pipenv install `Loading .env environment variables... Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 … -
Migrate Custom Field Renderer from Django 1.8 to Django 3.2
I am trying to migrate a custom field renderer in a Django 1.8 form to Django 3.2. The form looks like this: class SomeEditForm(forms.ModelForm): job_uuid=forms.CharField(widget=forms.HiddenInput()) class Meta: model=Job fields=('status',) widgets={'status': forms.RadioSelect(renderer=BSRadioFieldRenderer)} So as it seems there is no Rendermixin anymore which accepts a renderer in its def init(). I have read the new source code and see that RadioSelect is now a subclass of ChoiceWidget. I cant get my head around to inject my old renderer into the new structure. Can someone please point me into the right direction? Thanks for your help! :) -
How to auth users with JWT in django microservice-like project?
I already have JWT from external auth service and want to use it in my django (DRF actually) project, I also want to populate user model basing on this jwt. How can I implement this? most of libs are about django as auth service, not just client -
Django Rest Framework api: bulk_create assigning a str to the primary key and a number to my str field
I'm creating a basic Pokemon API for practise purposes, where my models include: Card, Expansion and Type (fire, water, bug, ice, etc.) I'm trying to run a script to populate the "Type" database table but I get weird results, where the type name field actually seems to contain the primary key value and the ID field contains the actual name, when it should be the other way around. When I use Type.objects.all() to print the table contents (I set __repr__ to print the primary key (ID) and the name only) I can see this: <QuerySet [Type( ID: Normal; NAME: 1), Type( ID: Fighting; NAME: 2), Type( ID: Flying; NAME: 3), Type( ID: Poison; NAME: 4), Type( ID: Ground; NAME: 5), Type( ID: Rock; NAME: 6), Type( ID: Bug; NAME: 7), Type( ID: Ghost; NAME: 8), Type( ID: Steel; NAME: 9), Type( ID: Fire; NAME: 10), Type( ID: Water; NAME: 11), Type( ID: Grass; NAME: 12), Type( ID: Electric; NAME: 13), Type( ID: Psychic; NAME: 14), Type( ID: Ice; NAME: 15), Type( ID: Dragon; NAME: 16), Type( ID: Dark; NAME: 17), Type( ID: Fairy; NAME: 18)]> Also, when trying to run Type.objects.all().delete() to clear the table records, I get "ValueError: Field … -
Submit form with only two clicks on Submit Django
I created a page with questions to the phone, I need that when, when a person clicks on the submit form, he must submit the form with one click, and change the same form with one click too. But for now, it can be done with just two mouse clicks. my models.py: class Items_buy(models.Model): class Meta: db_table = 'items_buy' verbose_name = 'Телефон который покупаем' verbose_name_plural = 'Телефоны которые покупаем' image_phone = ResizedImageField(size=[100,100], upload_to='for_sell/',verbose_name='Фотография модели телефона') model_produkt = models.TextField(max_length=80, verbose_name='Модель продукта ') text = models.TextField(max_length=500, verbose_name='Текст') max_prise = models.FloatField(verbose_name='Максимальная цена telefoha') image_phone_for_buy_bord = ResizedImageField(size=[100,100],upload_to='for_sell/',verbose_name='Фотография модели телефона ha prodazy') def __str__(self): return self.model_produkt class Question(models.Model): class Meta: db_table = 'question' verbose_name = 'Вопрос к телефону' verbose_name_plural = 'Вопросы к телефону' items_buy = models.ForeignKey(Items_buy, on_delete=models.RESTRICT) titles= models.CharField(max_length=150,verbose_name='Заголовок вопросa') question_text =models.TextField(max_length=100, verbose_name='Заголовок вопросa text') #max_prise_qustion = models.FloatField(verbose_name='Максимальная цена') def __str__(self): return self.titles class Choice(models.Model): class Meta: db_table = 'choice' verbose_name = 'Выбор ответа' verbose_name_plural = 'Выбор ответов' question = models.ForeignKey(Question, on_delete=models.RESTRICT,related_name="options") title = models.CharField(max_length=1000, verbose_name='Заголовок выбора') price_question = models.FloatField(verbose_name='Цена ответа') #lock_other = models.BooleanField(default=False, verbose_name='Смотреть другой вариант ответа') def __str__(self): return str(self.price_question) class Answer(models.Model): class Meta: db_table = 'answer' verbose_name = 'Ответ на вопрос' verbose_name_plural = 'Ответы на вопросы' items_buy = models.ForeignKey(Items_buy, on_delete=models.RESTRICT) question = … -
HTML - How to auto refresh the messages of a Chat-App
I'm working on a Chat-App with Django in Python. I tried some changes to auto refresh the messages of a chat but I had some problems: First time I tried: I used a javascript reloader for the div of the chat (but doing this, the send-message text input clears every time the auto refresher plays.) Second problem: the chat reset the height of the scroll every time the auto refresher plays. So I'm looking for a solution to refresh only the chat and keeping the scroll, without affecting other elements such as the text input. Here's the "chats.html" file: <div class="container-fluid h-100" style="posistion:absolute; margin-left:60;"> <div class="row justify-content-center h-100"> <div class="col-md-4 col-xl-3 chat"> <div class="card mb-sm-3 mb-md-0 contacts_card" style="max-height:700;min-height:700"> <div class="card-header"> <div class="input-group"> <input type="text" placeholder="Search..." name="" class="form-control search"> <div class="input-group-prepend"> <span class="input-group-text search_btn"><i class="fas fa-search"></i></span> </div> </div> </div> <div class="card-body contacts_body"> <ui class="contacts"> {% for group in groups %} <a href="/chats/{{ group.event_name }}/" style="text-decoration: none;"> {% if group.event_name == current_group.event_name %} <li class="active"> <div class="d-flex bd-highlight" > <div class="img_cont"> <img src="{{ group.event_img.url }}" class="rounded-circle user_img"> <span class="online_icon"></span> </div> <div class="user_info"> <span>{{ group.event_name }}</span> <p>Kalid is online</p> </div> </div> </li> {% else %} <li class=""> <div class="d-flex bd-highlight"> <div class="img_cont"> <img … -
Execute Celery task after Django model timestamp has passed
I am trying to build a Django app that reacts to certain events, and then after X amount of time, executes a celery task. Users with permissions are given the option of either vetoing the action, or expediting the action. I am using Django 4.1 and Python 3.10. Veto does not need to take effect immediately, as the celery task will just check for it once it runs. Expedite does need to take effect immediately, but must require more than a single user to vote on it. Votes may have their "expiry time" changed by an admin, and the celery task should change the eta accordingly (or the task revoked and a new one put in the queue, with the updated eta). The work must be done in near-real-time, so no having a daily task that checks for expired votes. An example might make it a lot more clear: Bob has quit his job, and therefore his user accounts and access need to be revoked. A celery task that does just that, is put into the celery queue, with an eta of 2 days into the future (the timestamp is also logged in a Django model). HR is notified that … -
Make a pie chart using chart.js in Django error
I am building a budget tracker application and in dashboard page, I'd like to list different graphs. The pie chart is for expense structure showing how much expense is spent in certain categories. I'm facing two problems mainly. First one is the data of model in view doesn't pass through the template which results graph not showing. Second one is that I'm trying to show proportion of certain categories of expense, not a proportion of every expense(sum of accumulation of expense has to be calculated if they're in same category.) If I can get help, I'd be so much appreciated. models.py class Transaction(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) TRANSACTION_CHOICES = [ ('Expense','Expense'), ('Income','Income'), ] transaction_type = models.CharField(max_length=10, blank=False, choices=TRANSACTION_CHOICES, default="Expense",null=True) title = models.CharField(blank = False, max_length=30) description = models.CharField(blank = True, max_length=200) amount = models.DecimalField(blank=False, max_digits=10, decimal_places=2) date_paid = models.DateField(auto_now_add=False, blank=True, null=True) time_paid = models.TimeField(auto_now_add=False, blank=True, null=True) CATEGORY_CHOICES = [ ('Groceries', 'Groceries'), ('Salary', 'Salary'), ('Bills', 'Bills'), ('Rent', 'Rent'), ('Gym', 'Gym'), ('Restaurant', 'Restaurant'), ('Vacation', 'Vacation'), ('Travel', 'Travel'), ('Gift', 'Gift'), ('Investments', 'Investments'), ('Savings', 'Savings'), ('Entertainment', 'Entertainment'), ('Internet', 'Internet'), ('Healthcare', 'Healthcare'), ('Lifestyle', 'Lifestyle'), ('Insurance', 'Insurance'), ('Other', 'Other'), ] category = models.CharField(max_length=50, blank=False, choices=CATEGORY_CHOICES) receipt = models.ImageField(upload_to='receipt_images', blank = True) def __str__(self): return self.title def … -
TypeError: unsupported operand type(s) for *: 'NoneType' and 'decimal.Decimal'
File "F:\Coding Related\Karmachari-BackEnd\Karmachari_App\mainapp\models.py", line 97, in calculate_net_salary gross_pay = self.hours_worked * self.basic_pay_rate ~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~ TypeError: unsupported operand type(s) for *: 'NoneType' and 'decimal.Decimal' These are the lasted error message in terminal. in my model.py i have class Payroll(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) basic_pay_rate = models.DecimalField(max_digits=8, default=10000, decimal_places=2) overtime = models.DecimalField(max_digits=8,null=True, decimal_places=2) hours_worked = models.FloatField(null=True, blank=True) deductions = models.DecimalField(max_digits=8,null=True, decimal_places=2) net_pay = models.DecimalField(max_digits=8,null=True, blank=True, decimal_places=2) def calculate_net_salary(self): gross_pay = self.hours_worked * self.basic_pay_rate net_pay = gross_pay + self.overtime - self.deductions self.net_pay.save() # def save(self, *args, **kwargs): # self.net_salary = self.calculate_net_salary() # super(Payroll, self).save(*args, **kwargs) def __str__(self): return self.user.username in my views.py i have def payroll(request): payrolls = Payroll.objects.all() for payroll in payrolls: payroll.calculate_net_salary() user_object = User.objects.get(username=request.user.username) profile = Profile.objects.get(user=user_object) context={ 'profile':profile, 'navbar':'salary', 'payroll': payroll, } return render(request,'Salary_Sheet.html',context) I want to access payroll of each employee and calculate net salary and provide them in pdf. This is my first project so I dont know the concept clearly and want a beginner friendly explanation or solution. -
How to add a favorite function?
First time asking here so be patient with me, also trying to learn django. I have the following codes : class Favorite(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) apartment = models.ForeignKey(Apartment, on_delete=models.CASCADE) class Meta: unique_together = ('user', 'apartment') and {% extends 'base.html' %} {% load static %} <head> <title>Browse Rooms</title> <link rel="stylesheet" type="text/css" href="{% static 'css/browse_rooms.css' %}"> </head> {% block content %} <div class="container mt-5"> <h2 class="mb-4"><i class="fas fa-search"></i> Browse Rooms</h2> <div class="row"> {% for apartment in apartments %} <div class="col-md-4 mb-4"> <div class="card"> {% if apartment.image %} <img class="card-img-top" src="{{ apartment.image.url }}" alt="Profile Image"> {% endif %} <div class="card-body"> <h5 class="card-title">{{ apartment.address }}, {{ apartment.city }}, {{ apartment.state }} {{ apartment.zipcode }}</h5> <p class="card-text">Price: ${{ apartment.price }}</p> <p class="card-text">Bedrooms: {{ apartment.bedrooms }}</p> <p class="card-text">Bathrooms: {{ apartment.bathrooms }}</p> <p class="card-text">Move-in Date: {{ apartment.move_in_date|date:"F j, Y" }}</p> <a href="{% url 'apartment_detail' apartment.id %}" class="btn btn-primary"><i class="fas fa-info-circle"></i> View Details</a> <a href="#" class="btn btn-outline-secondary" onclick="addToFavorites({{ apartment.id }})"><i class="fas fa-heart"></i> Add to Favorites</a> </div> </div> </div> {% empty %} <p>No apartments found.</p> {% endfor %} </div> </div> {% endblock %} I tried to search on web how to implement this function but there are many methods and i don't understand the logic behind cause they … -
Can I override Django rendering checkbox inputs inside a label?
I'm trying to render a form which allows for multiple selections via checkboxes. I've tried with django-multiselectfield (which I was already using) and the native CheckboxSelectMultiple widget. If I have a simple form like so: FAVORITE_COLORS_CHOICES = [ ('blue', 'Blue'), ('green', 'Green'), ('black', 'Black'), ] class SimpleForm(forms.Form): favorite_colors = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=FAVORITE_COLORS_CHOICES, ) And if I render with widget tweaks like so: {% render_field form.favorite_colors %} <div id="id_favorite_colors"> <div> <label for="id_favorite_colors_0"> <input class="form-control" id="id_favorite_colors_0" name="favorite_colors" placeholder="Your Name" type="checkbox" value="blue" /> Blue</label> </div> <div> <label for="id_favorite_colors_1"> <input class="form-control" id="id_favorite_colors_1" name="favorite_colors" placeholder="Your Name" type="checkbox" value="green" /> Green</label> </div> <div> <label for="id_favorite_colors_2"> <input class="form-control" id="id_favorite_colors_2" name="favorite_colors" placeholder="Your Name" type="checkbox" value="black" /> Black</label> </div> </div> This is causing problems for the way I want to render my form. Is there any way I can force Django to output the input and then the label, so the html would be like so: <div id="id_favorite_colors"> <div> <input class="form-control" id="id_favorite_colors_0" name="favorite_colors" placeholder="Your Name" type="checkbox" value="blue" /> <label for="id_favorite_colors_0">Blue</label> </div> <div> <input class="form-control" id="id_favorite_colors_1" name="favorite_colors" placeholder="Your Name" type="checkbox" value="green" /> <label for="id_favorite_colors_1">Green</label> </div> <div> <input class="form-control" id="id_favorite_colors_2" name="favorite_colors" placeholder="Your Name" type="checkbox" value="black" /> <label for="id_favorite_colors_2">Black</label> </div> </div> I haven't found an easy answer to this and most … -
request Timeout Error when creating pdf export for many users - django
I want to export from my users in site. but when I want to export from many users, I see this error: request Timeout I made a thread to solve this problem. But when downloading the file, the file is not downloaded, but the error is not shown on the site. Please guide def pdf(request, users): # ceating pdf code ... with open('media/pdf-export/exports/export.zip', 'rb') as fh: response = FileResponse(fh) response['Content-Disposition'] = 'inline; filename=' + os.path.basename('media/pdf-export/exports/export.zip') return response @admin.register(User) class UserAdmin(admin.ModelAdmin): list_display = ['id', 'time', 'first_name', 'last_name', 'phone_number', 'contract_number'] sortable_by = ['time'] list_filter = ['accept', 'final_submit'] search_fields = ['first_name', 'last_name', 'phone_number'] actions = ['export_to_excel', 'export_to_pdf'] .... def export_to_pdf(self, request, users): pdf_ = threading.Thread(target=pdf, args=[request, users, ], daemon=True) pdf_.start() I used thrading for control timeout error