Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I concatenate two different model query and order by a field that both models has
How can I concatenate two different model query and order by a field that both models has like progress fields. For example models.py class Gig(models.Model): author= models.ForeignKey(User) title = models.CharFields() progress = models.IntegerField() class Project(models.Model): author= models.ForeignKey(User) title = models.CharFields() progress = models.IntegerField() Can I do my view.py like this, for me to achieve it? İf No, How can I achieve it? views.py def fetch_all_item(request): gig = Gig.objects.filter(author_id = request.user.id) project = Project.objects.filter(author_id = request.user.id) total_item = (gig + project).order_by("progress") return render(request, "all_product.html", {"item": total_item}) I am trying to join two query set from Gig and Project models then send it to frontend in an ordering form by a field name called progress. -
How to deploy django based website running on a docker compose to my local home network?
I have the following setup: docker-compose.yml # Mentioning which format of dockerfile version: "3.9" # services or nicknamed the container services: # web service for the web web: # you should use the --build flag for every node package added build: . # Add additional commands for webpack to 'watch for changes and bundle it to production' command: python manage.py runserver 0.0.0.0:8000 volumes: - type: bind source: . target: /code ports: - "8000:8000" depends_on: - db environment: - "DJANGO_SECRET_KEY=django-insecure-m#x2vcrd_2un!9b4la%^)ou&hcib&nc9fvqn0s23z%i1e5))6&" - "DJANGO_DEBUG=True" expose: - 8000 db: image: postgres:13 # volumes: - postgres_data:/var/lib/postgresql/data/ # unsure of what this environment means. environment: - "POSTGRES_HOST_AUTH_METHOD=trust" # - "POSTGRES_USER=postgres" # Volumes set up volumes: postgres_data: and a settings file as ALLOWED_HOSTS = ['0.0.0.0', 'localhost', '127.0.0.1'] #127.0.0.1 is my localhost address. With my local wifi service's router IP as 192.168.0.1 Can you please help me deploy the django site on my local network? Do I have to set up something on my router? Or could you direct me towards resources(understanding networking) which will help me understand the same. -
django sqs makes request slower
Just installed sqs with django and celery to do background tasks like sending notifications and firebase messages I was using redis and it was fast when installed sqs the code is not async anymore, the errors even appear in the server terminal not the celery one! here's my settings.py CELERY_BROKER_TRANSPORT_OPTIONS = { "region": "us-east-1", } CELERY_BROKER_TRANSPORT = 'sqs' CELERY_BROKER_URL = f"sqs://{AWS_ACCESS_KEY_ID}:{AWS_SECRET_ACCESS_KEY}@" CELERY_TASK_DEFAULT_QUEUE = "hikeapp" CELERY_RESULT_BACKEND = None CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' when moved back to redis it became fast again, what am I doing wrong? -
Setting up wildcard subdomain dynamically
I have a domain example.com. For each user, I want to dynamically create a subdomain for them. Say for user1, it will have user1.example.com. For user2, it will have user2.example.com. -
404 error not found when debug = False in django multilanguages web app
Hello I am making a multilanguages django web app, When DEBUG = True => the multilanguages works fine means when i click on localhost:8000 it redirect me to localhost:8000/en or the last language I am puting anyway. When DEBUG = FALSE => I enter to localhost:8000 it gives me an error of 404 not found, here is my setting.py: I am puting the '*' because I am testing if possible to work anyway I am testing all. ALLOWED_HOSTS = ['localhost','localhost:8000','127.0.0.1','127.0.0.1:8000','*'] LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) LANGUAGE_CODE = 'en' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = [ ('en', ('English')), ('ko', ('Korean')), ] here is my urls.py from django.conf.urls.i18n import i18n_patterns urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns ( path('admin/', admin.site.urls), path('', include('app1.urls')), path('', include('app2.urls')), ) handler404='app1.views.handle_not_found' in my app1 urls.py urlpatterns = [ path('',views.index,name="index"), ] in debug = False it doesn't work so it doesn't know the path of locahost:8000 only it knows only localhost:8000/en how can I do so whenever. -
Django: normalize/modify and field in serializer
I have a model serializer like this: class FoooSerializers(serializers.ModelSerializer): class Meta: model = Food fields = [ 'id', 'price',] Here I have the price with trailing zeros like this: 50.000 and I want to .normalize() to remove the trailing zeros from it. Is this possible to do that in this serializer? -
Is it possible to update a value of a Typescript variable from external code in an html file?
in the .ts file: function showOrHideWarehouseTable(all_warehouses_table: string) { const checkBox = document.getElementById( "edit-" + all_warehouses_table ) as HTMLInputElement | null; if (checkBox != null) { if (checkBox.checked == true) { let table = document.getElementById("main-table"); let inside_table = document.createElement("table"); inside_table.setAttribute( "id", "warehouse-table-" + all_warehouses_table ); table.append(inside_table); let warehouse_table_row_0 = inside_table.insertRow(0); let cell0 = warehouse_table_row_0.insertCell(0); in the .html file: <script> let warehouse_table_row_0_cell_0 = ` {{ form.inventory_summary_as_skids_final_number.label }} `; cell0.innerHTML = warehouse_table_row_0_cell_0 </script> is this possible with some configuration? FYI I am trying to capute the django render code -
Django serialize function returns error JSONEncoder.__init__() got an unexpected keyword argument 'fields'
I'm trying to serilize my salesnetwork.agency model into a geojson file, and according to Django docs I'm using the following code: markers = Agency.objects.all() geojson_file = serialize("geojson", markers, geometry_field="location", fields=("province",) ) But this code results in the following error: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Vahid Moradi\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Users\Vahid Moradi\AppData\Local\Programs\Python\Python310\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "D:\Projects\Navid Motor\Website\Django\NavidMotor.com\.venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\Projects\Navid Motor\Website\Django\NavidMotor.com\.venv\lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) ... return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "D:\Projects\Navid Motor\Website\Django\NavidMotor.com\navidmotor\urls.py", line 5, in <module> path("", include("core.urls")), File "D:\Projects\Navid Motor\Website\Django\NavidMotor.com\.venv\lib\site-packages\django\urls\conf.py", line 38, in include urlconf_module = import_module(urlconf_module) File "C:\Users\Vahid Moradi\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in … -
I cant add item via django admin panel
when i try to add remove or change something by djangos admin panel i get IntegrityError at /admin/app/place/2/delete/ FOREIGN KEY constraint failed Models.py class User(AbstractUser): pass class Currency(models.Model): name = models.CharField(max_length=64) sign = models.CharField(max_length=64) def __str__(self): return self.name class Place(models.Model): name = models.CharField(max_length=64, blank=True, null=True) currency = models.ForeignKey(Currency, on_delete=models.CASCADE, blank=True, null=True, related_name="currency") fb = models.CharField(max_length=128, blank=True, null=True) ig = models.CharField(max_length=128, blank=True, null=True) address = models.CharField(max_length=128, blank=True, null=True) wifi = models.CharField(max_length=32, blank=True, null=True) phone = models.CharField(max_length=16, blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="creator") def __str__(self): return self.name Admin.py admin.site.register(User) admin.site.register(Currency) admin.site.register(Place) i tried to remove an item and it gives me this error -
absolute path problem with saving image to s3 storage [closed]
when I want to create a new post from adminpanel and add an image file this happens .i searched but i couldn't solve the problem . i would be happy if you help -
Send Choices in Serilizer Django
models.py: class Distributor(models.Model): class ModeChoices(models.IntegerChoices): physical = 1, _('physical') digital = 2, _('digital') class StatusChoices(models.IntegerChoices): publish = 1, _('publish') pending = 2, _('pending') dont_publish = 3, _('dont_publish') serializers.py: modes = serializers.DictField(source=Distributor.ModeChoices.choices) not working ... -
I want to make a employee attendance and payroll management system in django . can anyone help me to design a database for the same
I want to design the database but I have no clue and this is my first project in college, I recently learn Django but to make a database for a real time project is very confusing for me . My task is to :- create login/sign up store Different businesses with different id of each business name create 2 roles :-employees and employer ,for every company (a user can work in more than one company with different roles) keep track of their attendance and salary -
Elasticsearch error: unavailable_shards_exception
I implemented elastic search in my django project. However due to an issue i had to uninstall my old mysql and instal again in my laptop. So had to create new db for the project. After that from today i see the following error when i try to create a new product. I cannot understand the error. Any help would be appreciated. Exception Type: BulkIndexError Exception Value: ('1 document(s) failed to index.', [{'index': {'_index': 'products', '_id': '13', 'status': 503, 'error': {'type': 'unavailable_shards_exception', 'reason': '[products][0] primary shard is not active Timeout: [1m], request: [BulkShardRequest [[products][0]] containing [index {[products][13], source[{"name":"test"}]}] and a refresh]'}, 'data': {'name': 'test'}}}]) I tried to update my documents file. But still the problem persists. I tried to restart elastic search. Still i have the same problem. However everything works fine in server. Only in local i face this problem. I am confused if it was caused because of using new db. -
How can I display something from data base after multiple criteria is satisfied in django
Here i have a Model Recommenders: ` class Recommenders(models.Model): objects = None Subject = models.ForeignKey(SendApproval, on_delete=models.CASCADE, null=True) Recommender = models.CharField(max_length=20, null=True) Status = models.CharField(null=True, max_length=8, default="Pending") Time = models.DateTimeField(auto_now_add=True) ` And another model Approvers: ` class Approvers(models.Model): objects = None Subject = models.ForeignKey(SendApproval, on_delete=models.CASCADE, null=True) Approver = models.CharField(max_length=20, null=True) Status = models.CharField(null=True, max_length=8, default="Pending") Time = models.DateTimeField(auto_now_add=True) ` And my SendApproval model as: ` class SendApproval(models.Model): Subject = models.CharField(max_length=256) Date = models.DateField(null=True) Attachment = models.FileField(upload_to=get_file_path) SentBy = models.CharField(null=True, max_length=100) Status = models.CharField(null= True, max_length=8, default="Pending") ` Now my problem is that I have to display the Subject and Attachment from SendApproval table only when all the recommenders Status in Recommenders table related to that subject is "Approved" Don't know how can i know that..Thanks in advance... Actually not having any Idea but the best answer will be appreciated...By the way I am new to StackOverflow...So please let me know it there is some ambiguity in my question. -
How to add an argument to a function in a python .bat file
I have a file with a function and a file that calls the functions. Finally, I run .bat I don't know how I can add an argument when calling the .bat file. So that the argument was added to the function as below. file_with_func.py def some_func(val): print(val) run_bat.py from bin.file_with_func import some_func some_func(val) myBat.bat set basePath=%cd% cd %~dp0 cd .. python manage.py shell < bin/run_bat.py cd %basePath% Now I would like to run .bat like this. \bin>.\myBat.bat "mystring" Or after starting, get options to choose from, e.g. \bin>.\myBat.bat >>> Choose 1 or 2 >>> 1 And then the function returns "You chose 1" -
psycopg2.errors.UndefinedTable: relation "django_admin_log" does not exist
I just started learning Django, and I'm following a book as guide (the book is from August 2022, so new) and I ran into 2 problems. The first one was that Python couldn't find the module psycopg2 which I then installed. Now I'm a little further and created my first model and migrated it to the database, which all seemed to work well. I then created a superuser and opened localhost:8000/admin/ and it sent me to the admin site, I logged in with my newly created user, so far so good. Now the problem. This is what the site shows me: And this is what the log says: I've tried many approaches I found on here, for example deleted the migrations folder in my applications folder and then migrated my application again. I'll just go through a few other commands I've tried: >> python manage.py migrate --run-syncdb admin CommandError: Can't use run_syncdb with app 'admin' as it has migrations. >> python manage.py sqlmigrate admin 0001 response: [The SQL query...] >> python manage.py syncdb response: Unknown command: 'syncdb' >> python manage.py migrate --fake Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, sessions Running migrations: No migrations to apply. This … -
Is there any package for Wildcard Subdomain in Routes: Assign Subdomain for Every User?
I have a domain example.com. For each user, I want to dynamically create a subdomain for them. Say for user1, it will have user1.example.com. For user2, it will have user2.example.com. I'm worried about its view and path! models.py class MyUser(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE, null = True) -
How to take back storage from my postgres db
I have a table named duplicates_duplicatebackendentry_documents that has a size of 49gb. This table has 2 indexes that are each 25 gb. And two constraints that are also each 25gb. The table is used by the duplicates module in a django app I deployed. I have now turned off the module. I am unable to run full vacuuum because I do not have the space necessary to run it. Deleting the table returns the storage (I tested in a dev env) but is there a way I can delete the bloat but keep the table, its constraints and indexes? I just want to empty the bloat along with all the contents. -
django slick report and nested categories
I am using in django the following models.py: class Expense(models.Model): name = models.CharField(max_length=50) date = models.DateField(unique=False, blank=False) slug = models.SlugField(unique=True, null=True, default='') # slug = AutoSlugField(null=True, default=None, unique=True, populate_from='name') price = models.DecimalField(default=0.0, blank=True, max_digits = 20, decimal_places = 2) category = models.ForeignKey( 'Category', related_name="Expense", on_delete=models.CASCADE ) account = models.ForeignKey(Account, on_delete=models.CASCADE, verbose_name=u"Account", help_text=u"account") def __str__(self): return '{},{},{}'.format(self.name, self.date, self.price) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Expense,self).save(*args, **kwargs) def get_absolute_url(self): return self.slug class Category(MPTTModel): name = models.CharField(max_length=200) slug = models.SlugField(unique=True, null=True, default='') # slug = AutoSlugField(null=True, default=None, unique=True, populate_from='name') parent = TreeForeignKey( 'self', blank=True, null=True, related_name='child', on_delete=models.CASCADE ) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "categories" def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) The TreeForeignKey allows me to define nested categories, such as Home -> Electricity and so on. I am using the following Slick Report view.py: class TotalExpenses(SlickReportView): report_model = Expense date_field = 'date' group_by = 'category' columns = ['name', SlickReportField.create(method=Sum, field='price', name='price__sum', verbose_name=('Total category $'))] charts_settings = [ { 'type': 'bar', 'data_source': 'price__sum', 'title_source': 'name', }, ] It works but I would like to sum only level 1 categories. Do you know how this … -
TypeError: User() got unexpected keyword arguments: 'password2' : Django JWT Authentication
I am trying to build a user authentication app using django JWT token, when i try to test my user authentication api and validate the password and password2 , it generate the following error: TypeError: User() got unexpected keyword arguments: 'password2' My serializers.py is as follows: from rest_framework import serializers from account.models import User class UserRegistrationSerializers(serializers.ModelSerializer): password2=serializers.CharField(style={'input_type':'password'}, write_only=True) class Meta: model = User fields=['email','name','tc','password','password2'] extra_kwargs={ 'password':{'write_only':True} } def validate(self, attrs): password=attrs.get('password') password2=attrs.get('password2') if password != password2: raise serializer.ValidationError("Password and Confirm Password Does not match") return attrs def validate_data(self, validate_data): return User.objects.create_user(**validate_data) and my views.py is as follows: from django.shortcuts import render from rest_framework.response import Response from rest_framework import status from rest_framework.views import APIView from account.serializers import UserRegistrationSerializers # Create your views here. class UserRegistrationView(APIView): def post(self, request, format=None): serializer= UserRegistrationSerializers(data=request.data) if serializer.is_valid(raise_exception=True): user= serializer.save() return Response({'msg':'Registration Successful'}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) my models.py file is as follows: from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser # Create your models here. class UserManager(BaseUserManager): def create_user(self, email, name, tc, password=None, password2=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), … -
How to install both Java 11 and Python 3.7 in Docker container using Dockerfile
I have a Django project, from inside which I am executing a jar executable file. But I am having trouble installing both Java 11 and Python using the Dockerfile. I believe the first step is to use a Linux Distro as a base image and install Java and Python on top of it. Can someone please help me with the Dockerfile for this use case? -
Django unique_together() for field1 and field2 and vice versa (field2 and field1)
It's possible to create duplicate thread with same first_person and second_person using unique_together() in django. class Meta: unique_together = ['first_person', 'second_person'] But just like that, Is it possible to make it work for same second_person and first_person too ? For example if first_person is abc@gmail.com and second_person is xyz@gmail.com then I can't create duplicate value but if I try to make second_person is abc@gmail.com and first_person is xyz@gmail.com then it again creates thread with same person that I dont want. Please let me know how to fix this. -
Django: Remove trailing zeros for a Django model field
Here is my Django field I created: class CurrencyField(models.DecimalField): INTEGER_PLACES = 15 DECIMAL_PLACES = 18 DECIMAL_PLACES_FOR_USER = 6 MAX_DIGITS = INTEGER_PLACES + DECIMAL_PLACES MAX_VALUE = Decimal('999999999999999.999999999999999999') MIN_VALUE = Decimal('-999999999999999.999999999999999999') def __init__(self, verbose_name=None, name=None, max_digits=MAX_DIGITS, decimal_places=DECIMAL_PLACES, **kwargs): super().__init__(verbose_name=verbose_name, name=name, max_digits=max_digits, decimal_places=decimal_places, **kwargs) By using this function I want to remove the trailing from this field def normalize_fraction(d): normalized = d.normalize() sign, digit, exponent = normalized.as_tuple() return normalized if exponent <= 0 else normalized.quantize(1) How can I use this function inside that field class to remove the trailing zeros? -
Creating category section with django
I'm trying to add a category section to my blog post form using django, the category field is created and I haven't got any error but the dropdown is not created. models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Category(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name def get_absolute_url(self): return reverse('posts') class Post(models.Model): STATUS = [ (0, 'Drafted'), (1, 'Published'), ] title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) published_on = models.DateTimeField(auto_now=True) content = models.TextField() status = models.IntegerField(choices=STATUS, default=0) category = models.CharField(max_length=200, default='uncategorized') class Meta: ordering = ['-created_on'] def __str__(self): return self.title def get_absolute_url(self): return reverse('my_blog:posts') forms.py from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'author', 'category', 'content') widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'author': forms.Select(attrs={'class': 'form-control'}), 'category': forms.Select(attrs={'class': 'form-control'}), 'content': forms.Textarea(attrs={'class': 'form-control'}), } admin.py from django.contrib import admin from .models import Post, Category, Comment admin.site.register(Post) admin.site.register(Category) This method was based on a tutorial and I'm wondering if this is the right way to create category fields. Any help, please? -
how to upload public image to digitalocean space using Django?
i upload an image to digital ochen by django and this is my code def uploadImage(request): data = request.data dish= FoodRecord(image=request.FILES.get('image')) dish.save() after upload code i can't accsess to the image with output AWSAccessKeyId and Expires after image link ,,for example this is work https://fra1.digitaloceanspaces.com/logatta-space/fossa/media/food/08eat-articleLarge-v2.jpg?AWSAccessKeyId=DO00GN8LVUJB9VNAQL69&Signature=4a7jBIKfZzYnNaghBxnE25VnUQM%3D&Expires=1667725564 this is not work https://fra1.digitaloceanspaces.com/logatta-space/fossa/media/food/08eat-articleLarge-v2.jpg becuse don't have permisions my qustion how to make my image public from pyhon code ?