Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
in python how can I display the registered soccer teams in a chart?
below is my code and excel file i generated with this, now i need to display the teams in figure as a knockout tournament, from django.shortcuts import render from .models import Team, TieSheet from openpyxl.utils import get_column_letter from openpyxl.styles import Font from openpyxl import Workbook from django.http import HttpResponse import pandas as pd from openpyxl.styles import Font, PatternFill, Alignment, borders from django.http import HttpResponse from openpyxl import load_workbook from django.core.files import File from django.core.files.base import ContentFile def tie_sheet(request): # Load the Excel template workbook = load_workbook(filename='static/excel/Tie-sheet.xlsx') # Get the active worksheet worksheet = workbook.active # Create merged cell for POLL1 and POLL2 columns and set heading worksheet.merge_cells(start_row=1, start_column=2, end_row=1, end_column=3) worksheet.cell(row=1, column=2, value='POLL1') worksheet.cell(row=1, column=4, value='POLL2') # Get the teams from the database teams = Team.objects.all().order_by('?') # Fill the data into the worksheet row_num = 2 count = 1 col = 2 for team in teams: cell = worksheet.cell(row=row_num, column=col, value=team.title) cell.border = borders.Border(left=borders.Side(style='thin'), right=borders.Side(style='thin'), top=borders.Side(style='thin'), bottom=borders.Side(style='thin')) if col == 2: col = 4 row_num = row_num elif col == 4: col = 2 row_num += 2 count = count+2 # Add spacing between rows and columns for row in worksheet.iter_rows(min_row=1, max_row=1): for cell in row: cell.font = Font(size=12, bold=True) … -
One-To-Many relation with a specific order in Django
I want to have a kind of array in my model to save instances of another model in a specific order, but I found out that you can't use an ArrayField of ForeignKeys. There is the Questionary model, that contains multiple questions that have to be in a certain order. And this questions have to be able to reorder or be deleted. Something like: class Questionary(models.Model): name = models.CharField(max_length=300, null=False, blank=False) ... class Question(models.Model): text = models.CharField(max_length=300, null=False, blank=False) ... questionary = models.ForeignKey(Questionary, on_delete=models.CASCADE) I don't know how to make the Question model have a specific order in the questionary and let this order be edited. I thought maybe add a field in the Question called 'index' and edit that when the Questions are reordered, but that seems a little bit inefficient. -
How to Make Map That Would Show Data From Models Like AirBnb's Map?
I' want to make a map like Airbnb's that would show the houses on the map and when you click on them ity would move you to the house detail page, but I didn't find any tutorials on google or youtube. Can you send some link that would help me do that or send code how to do that. -
Alternative command of gunicorn for waitress
So basically I'm trying to use gunicorn on Windows using the command gunicorn core.wsgi:application -w 4 I know that gunicorn does not work on Windows bc the package 'fcntl' does not exist in Windows. The alternative to gunicorn on Windows is waitress, is there a waitress command that can achieve the same result as the gunicorn command above? Thank you in advance. -
Query a secondary relation django
I have an Test model and an Application model like so: class Test(models.Model): #some fields here pass class TestApplication(models.Model): STATUS = [ ('P', 'Pending'), ('A', 'Approved'), ('R', 'Rejected'), ] user = models.ForeignKey(CustomUser, on_delete = models.CASCADE) test = models.ForeignKey(Test, on_delete = models.CASCADE) status = models.CharField(max_length = 1, choices = STATUS) A user submits an Application for a test therefore a test may have many Applications from different users. A privileged user approves or rejects the applications. The problem I have is detemining if the currently logged in user has applied for a particular test on the template, which seems so trivial. I am displaying a list of Tests and I particularly want to display a link for someone who wants to register for a Test on the template side. Test are only linked to users via applications. I tried iterating but that leads to a situation where I should skip/continue the loop which is impossible in django apparently. {% for appl in test.testapplication_set.all %} {% if appl.user == user %} <!---dont display link----> I want to do something like this: {% if user not in test.testapplication_set %} I'm sure I'm missing something on the docs that can be used to achieve … -
Add trailing slash to all URLs by default for Django App deployed on Heroku
I have a Django App deployed on Heroku. When running the app locally, all the URLs are automatically appended with trailing slash. However, on deploying the app to heroku, the URLs do not add the trailing slash and this causes 404 error. In the settings.py file for the Django project, 'HTTP_X_FORWARDED_PROTO' is set. Is there a way to ensure that all URLs automatically add "/" even on heroku? -
Interactive html template with Python
Using the work of Sajid Lhessani as reference (https://levelup.gitconnected.com/googlenews-python-api-gain-30-minutes-a-day-with-this-robot-newsreader-48ae6c593ef0) I wrote some Python code that receives an input from the user (Keywords, date from, date to), and returns a dataframe with news fetched from GoogleNews that apply to said input. Now, I want to make it into something I can easily share with my collegues, so that they can use the program themselves. I tried to create a HTML template using Django, Flask and PyScript (please note I have no knowledge of JavaScript) but absolutely failed at it. I would appreciate any help regarding how to complete said task. -
How can i make the value of one serializer field be dependent on the value of another within the same serializer class
I have this serializer class. I need to make the value of quantity be menuitem.quanity and price be quantity multiplied by menuitem.price. As can be gleaned, menuitem is a foreign field menuitem = MenuItemSerializer(read_only=True) menuitem_id = serializers.IntegerField(write_only=True) quantity = serializers.IntegerField() unit_price = serializers.DecimalField(max_digits=6, decimal_places=2) price = serializers.DecimalField(max_digits=6, decimal_places=2) class Meta: model = Cart fields = ['user', 'menuitem', 'menuitem_id', 'quantity', 'unit_price', 'price'] depth = 1 def get_unit_price(self, obj): return obj.menuitem.price def get_total_price(self, obj): return obj.unit_price * obj.quantity using the methods defined in the class i had returned @property from model class class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) menuitem = models.ForeignKey(MenuItem, on_delete=models.CASCADE) quantity = models.SmallIntegerField(default=0) unit_price = models.DecimalField(max_digits=6, decimal_places=2) price = models.DecimalField(max_digits=6, decimal_places=2) class Meta: unique_together = ('menuitem', 'user') def __str__(self): return f'{self.user}, {self.menuitem}, {self.quantity}, {self.price}' @property def total(self): return self.quantity * self.menuitem.price @property def _unit_price(self): return self.menuitem.price But this implementation doesn't save to database although it serialized -
How to use oauth2client.tools.run_flow with exceptions in python?
When I try to run the below code, from oauth2client import tools creds = tools.run_flow(flow, store, flags) When I close the web browser without logging into it, Following is the screen that appears and freeze like this way on terminal and the page keeps loading and show nothing in my django web page. Is their anyway I can use exception for this ? like if the user doesn't login then it won't start the process.? -
Application labels aren't unique, even though INSTALLED_APPS apps are unique
I am aware of some other questions that relate to this, however none of the other solutions seem to work. I am getting this error django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: userprofile even though my INSTALLED_APPS array in my django settings are unique. This is my installed_apps portion INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'drf_yasg', 'userauth', 'userprofile' ] Noting that this error did not surface at all before, when I started adding new apps it showed up, and even when I removed the new app I added it is still there. Would appreciate any guidance concerning it. -
Celery throwing a cx_oracle error while starting workers (django, celery, redis, oracle configuration)
I am attempting to integrate celery with my running django-oracle project. Redis is configured to be the message broker and the database backend. celery settings are in the prod.py in project/settings. When I start the workers, I get an error: [2023-04-26 20:35:44,049: ERROR/ForkPoolWorker-2] Signal handler <bound method DjangoWorkerFixup.on_worker_process_init of <celery.fixups.django.DjangoWorkerFixup object at 0x7fc016265f60>> raised: OperationalError(<cx_Oracle._Error object at 0x7fc009593ed8>,) Traceback (most recent call last): File "/home/raxak/.virtualenvs/raxak/lib/python3.6/site->packages/django/db/backends/base/base.py", line 252, in _close return self.connection.close() cx_Oracle.OperationalError: ORA-03113: end-of-file on communication channel Process ID: 0 The worker runs fine, though. I can't tell where this error is generated and why. The celery.py file looks like this: import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "raxakprotect.settings.prod") app = Celery("raxakprotect") app.config_from_object("django.conf:settings", namespace="CELERY") and the CELERY_ settings in prod.py are: ### # Celery related ### CELERY_BROKER_URL = "redis://localhost:6379" CELERY_RESULT_BACKEND = "redis://localhost:6379" CELERY_WORKER_SEND_TASK_EVENTS = True CELERY_TASK_SEND_SENT_EVENT = True --prasanna -
Get count for date between start date and start date + days left
I have a model: class Banner(models.Model): date_start=models.DateField() days_left=models.IntegerField() ... I need to create a function, that will return count of models, where input date is between model's date_start and date_start + days_left. For example: model1 and model2 date_start field is 26.04.2023 model1 days_left is 3 and model2 days_left is 8 For date 27.04.2023 function should return 2, but if date is 01.05.2023 it should return 1 (cause model1.date_start + datetime.timedelta(days=model1.days_left)) will be 29.04.2023, and date is not in that range) Which is the best way to do that? I think it should be some kind of Django ORM function, but i can't figure that. -
Is there a way to add a new field in django models that is calculated on the basis of other 2 fields in the same model
class Issue(models.Model): date = models.DateTimeField(auto_now_add = True) customer = models.ForeignKey(Customer, on_delete = models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE ) quantity = models.PositiveIntegerField() kt = models.IntegerField() rate = models.FloatField() I have this model, now I want to add a field to this model that is calculated with this formula: kt_21 = kt/21*quantity so I want a new field (kt_21) that is calculated by dividing the 2 already existing fields I could not find any solution to this online. -
Django saving media file outside of MEDIA_ROOT when in Docker Container
I have a Dockerized website which uses nginx to serve a react.js frontend, a postgreql, and a django backend. It is set to create a summary image (.PNG) which gets saved to an imageField and this is then attached to an email and sent to users. When I run it in in the Django development environment (./manage.py runserver) it works perfectly. However, when I run it using docker-compose, it saves the images into BASE_DIR and not MEDIA_ROOT. Of note, the static files work. settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/django_static/' # original one STATIC_ROOT = os.path.join(BASE_DIR, 'django_static') MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class SummaryEmail(models.Model): """Model to represent a new learner/attending combination to only send 1 morning email""" learner = models.ForeignKey("learners.Fellow", on_delete=models.SET_NULL, null=True) attending = models.ForeignKey("attendings.Supervisor", on_delete=models.SET_NULL, null=True, blank=True) surgery_type = models.CharField(max_length=50, null=True, blank=True) # surgery_type = models.ForeignKey("track.Surgery", on_delete=models.SET_NULL, null=True, blank=True) #Need to make foreign key date_surgery = models.DateField() email_sent = models.BooleanField(verbose_name="summary email has been sent", null=False, default=False) email_body = models.TextField(null=True, blank=True) date_email_sent = models.DateTimeField(null=True, blank=True) gears_image = models.ImageField(upload_to="email_images/%Y/%m/%d", blank=True) steps_image = models.ImageField(upload_to="email_images/%Y/%m/%d", blank=True) def __str__(self): return f"{self.learner} & {self.attending} ({self.surgery_type}, {self.date_surgery})" nginx default.conf server { listen … -
Django Multi Tenant Admin Page Users
I am working on a multi tenant app. Tenants are seperated by the domains. Each tenant have Members and Member class has a onetoone realtion to User model. See code below. For each Tenant at least a few Members has users with admin privilages. I can filter all models (created by me) to show in admin page which belong to that tenant. But whatever I do users and groups are shown for all tenants. I want to show the Users ( from django.contrib.auth.models) which belong to that tenant. class Tenant(models.Model): name=models.CharField(max_length=255) subdomain=models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.name}" class TenantAwareModel(models.Model): tenant=models.ForeignKey(Tenant,on_delete=models.CASCADE) class Member(TenantAwareModel): name=models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user_type = models.IntegerField(choices=USER_ROLES,default=USER_NOTSET) user = models.OneToOneField(User,on_delete=models.CASCADE)` First issue is that I need to able to change what shows in the admin page for Users but since user is already added to the admin by auth.UserAdmin I can not call@admin.register(User) Can I unregister and register User again. If the answer to 1 question if NO do I have to have a customuser model so I can overwrite the Usermodel in the admin(I do not know creating a custom user also adds another model to admin page or … -
group by then annotate following relationships backwards in django
I can sum all payments for each Klient. But I need to know sum each type of payment. Here are my models: class Klient(models.Model): name = models.CharField(max_length=30) surname = models.CharField(max_length=30) class Platba(models.Model): PAYMENT = 'P' GIFT = 'G' TYPE = [ (PAYMENT, 'Patment'), (GIFT, 'Gift'), ] when = models.DateField() ammount = models.DecimalField(max_digits=10, decimal_places=2) klient = models.ForeignKey( Klient, on_delete=models.CASCADE, related_name="payments" ) type = models.CharField( 'Kind of payments', max_length=1, choices=TYPE, default=PAYMENT, ) here is annotate for each klient and summing all payments, then print all = Klient.objects.annotate(Sum("payments__ammount")) for k in all: print(k, " -> ", k.payments__ammount__sum) but I would like to get sum for each TYPE of Platba. so I can accesss like k.payments_p for Platba.PAYMENT and k.payments_g for Platba.GIFT if I do Klient.objects.values("id", "payments__type").annotate(Sum("payments__ammount")) then I get two rows for each klient and that is not what I want. thanks for help or tip -
Error on django-bootstrap-icons for cusom_icon in django project
Normal bootstrap icon is working fine. like {% bs_icon 'slack' size='2em' %}. But when I am going to use custom_icon using django_bootstrap_icons module by using {% custom_icon 'c-program' %}. Its producing error: KeyError at / 'fill-rule' Request Method: GET Request URL: http://localhost:8000/ Django Version: 4.1.8 Exception Type: KeyError Exception Value: 'fill-rule' Exception Location: /opt/setup/.venv/lib/python3.9/site-packages/django/utils/html.py, line 103, in format_html Raised during: apps.bio.views.IndexView Python Executable: /opt/setup/.venv/bin/python Python Version: 3.9.16 Python Path: ['/workdir/src', '/usr/local/lib/python39.zip', '/usr/local/lib/python3.9', '/usr/local/lib/python3.9/lib-dynload', '/opt/setup/.venv/lib/python3.9/site-packages'] -
How to run video through backend in DRF
Good evening. I would like to ask you one question. I'm making a movie list app in DRF and I don't understand how to run the video through the backend, could you help me with something I will be grateful for any help -
Django. Every migration repeat "Alter field..."
My model looks like this: class Deal(models.Model): in_quantity = models.IntegerField() exchange = models.CharField(max_length=255) note = models.TextField(max_length=10000, null=True) time_deal = models.DateTimeField(default=datetime.now()) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) And every migration I get this operation: - Alter field time_deal on deal here is the example of the migration: class Migration(migrations.Migration): dependencies = [ ("portfolio", "0024_rename_quantity_deal_in_quantity_and_more"), ] operations = [ migrations.AlterField( model_name="deal", name="note", field=models.TextField(max_length=10000, null=True), ), migrations.AlterField( model_name="deal", name="time_deal", field=models.DateTimeField( default=datetime.datetime(2023, 4, 26, 16, 59, 46, 769292) ), ), migrations.AlterField( model_name="historicaldeal", name="note", field=models.TextField(max_length=10000, null=True), ), migrations.AlterField( model_name="historicaldeal", name="time_deal", field=models.DateTimeField( default=datetime.datetime(2023, 4, 26, 16, 59, 46, 769292) ), ), ] Could you help me to avoid it in every migration? I searched for a solution on the internet, but found nothing. -
How to exclude media folder when deploying to railway
I have a django app hosted in railway, when I push the changes to github railway overrides the media folder as well and I lose all my images, is there a way to exclude the media folder from changing? (I tried gitignore and it didn't work), I'm using whitenoise to handle media and gunicorn to deploy the app. -
Django tutorial - no errors for sqlite3 but tables are not showing up
I'm following the Django tutorial and after running python manage.py migrate, the migration seems to run successfully. This is the output: (base) ➜ django_test git:(master) ✗ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying auth.0012_alter_user_first_name_max_length... OK Applying sessions.0001_initial... OK And db.sqlite3 is created within the django_test directory. However, when I try to list the tables, I'm returned with nothing in sqlite3: (base) ➜ ~ sqlite3 db.sqlite3 SQLite version 3.40.1 2022-12-28 14:03:47 Enter ".help" for usage hints. sqlite> .tables Django version is 4.2. What am I doing wrong here? -
Django / Template folders in different app
I want to create several apps in one Django project. Can I create a template folder in each app? or Should I add all my html's in one template folder in the main project app for each app? If it is possible, how can I configure settings.py? I tried but it just redirect to the same html. So I don't how to access several html in different template folders. -
what django supported database is best for representing trees or revision history?
I want to avoid representing a version control system for AI models in my postgres DB through django. What NoSQL DB can represent a tree structure and has a Django library? -
How to adapt Django hit count in a function based view where the page does not have an ID?
I have been successfully using djang-hitcount in a function based view thankfully to this awesome answer here: how to use Django Hitcount in a function based view rather than a class? This is however not working when the page the user is visiting does not have an id. Starting with the solution provided with link above which is: from hitcount.utils import get_hitcount_model from hitcount.views import HitCountMixin def some_view(request, pk): object = get_object_or_404(MyModel, pk=pk) context = {} # hitcount logic hit_count = get_hitcount_model().objects.get_for_object(object) hits = hit_count.hits hitcontext = context['hitcount'] = {'pk': hit_count.pk} hit_count_response = HitCountMixin.hit_count(request, hit_count) if hit_count_response.hit_counted: hits = hits + 1 hitcontext['hit_counted'] = hit_count_response.hit_counted hitcontext['hit_message'] = hit_count_response.hit_message hitcontext['total_hits'] = hits # … extra logic … return render(request, 'my_template.html', context) How would you adapt the code when the function does not include pk? def some_view(request): ... I thought I could get away with it by simply using object = request.build_absolute_uri(). But this is not working. my current code: (I simplied the code used in the orginal answer as I only need to be able to know who was consulting the page.) def function(request): #hit count stuff from here object = request.build_absolute_uri() <-- this is where I am unsure what to … -
Social Authentication with Djoser in Django REST Framework
I am new to Django and it's features. I started new project with Djoser as authentication library and now I would like to implement social authentication via Google, Facebook etc. I found so much libraries but some suggestions were about using custom user model or not for rest library. Is there any library that can work with Djoser?