Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploy django react app to heroku: Migration error ?: (staticfiles.W004) The directory '/app/static' in the STATICFILES_DIRS setting does not exist
My deployed website right now just shows the Django Rest Framework Page with none of my css or data (https://ever-actor.herokuapp.com/api/lines/) I'm thinking it has something to do with the migrations because after running heroku run python manage.py migrate I get the following error: WARNINGS: ?: (staticfiles.W004) The directory '/app/static' in the STATICFILES_DIRS setting does not exist. Here is my settings.py: from pathlib import Path import dotenv import dj_database_url import os from decouple import config BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) dotenv_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(dotenv_file): dotenv.load_dotenv(dotenv_file) SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['localhost', '127.0.0.1:8000', 'ever-actor.herokuapp', ] CSRF_TRUSTED_ORIGINS = ['http://localhost:8000'] CORS_ORIGIN_WHITELIST = [ 'http://localhost:8000', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'api.apps.ApiConfig', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' ROOT_URLCONF = 'ever_actor.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ # BASE_DIR / 'ever-react/build' os.path.join(BASE_DIR, 'build'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ever_actor.wsgi.application' # Database DATABASES = {} DATABASES['default'] = dj_database_url.config(conn_max_age=600) # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { … -
Update api for a User Model and OnetoOne Profile model in Django Rest Framework
I have one model called profile which is related to Django User Model through one to one relationship. I want to create an api endpoint which will accept all the data and update both the tables whenever required. Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) manager = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True, related_name="manager" ) middle_name = models.CharField(max_length=50, blank=True) fpo = models.ForeignKey(Fpo, on_delete=models.CASCADE, null=True, blank=True) image = models.ImageField( upload_to="profile_images", blank=True, null=True, default=None, verbose_name="Profile Image", ) type = models.IntegerField( choices=UserTypeChoice.choices, default=UserTypeChoice.FARMER, verbose_name="User Type", ) gender = models.PositiveSmallIntegerField( choices=GenderChoice.choices, null=True, blank=True ) date_of_birth = models.DateField(null=True, blank=True) pincode = models.CharField( max_length=6, verbose_name="Pincode", blank=True, null=True, ) gat_no = models.CharField( max_length=20, verbose_name="GAT No", blank=True, null=True, ) landholding_in_acre = models.DecimalField( max_digits=10, decimal_places=2, default=0, ) is_member = models.BooleanField(default=False) serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ( "middle_name", "manager", "fpo", "type", "date_of_birth", "gender", "gat_no", "landholding_in_acre", "landholding_registred_in_acre", "plotting_in_acre", "is_member", ) views.py class FarmersDetailView(generics.RetrieveUpdateDestroyAPIView): serializer_class = FarmerDetailsSerializer permission_classes = (permissions.IsAuthenticated,) authentication_classes = (TokenAuthentication,) def get_queryset(self): if self.request.user.is_authenticated: if self.request.user.profile.type == 3: return User.objects.filter(profile__type=4, manager=self.request.user) return User.objects.filter(profile__type=4) return User.objects.none() Not able to update with a single api. So here i want to update both profile and user models at the same time through a single endpoint. When I'll be … -
How to setup search in django-admin changelists in models related through ForeignKeys?
I have created the following four model classes: class InfrastructureModel(models.Model): ENTRY_ACTIVE_YES_NO_CHOICES = ( (True, 'Yes'), (False, 'No')) entryActiveYesNo = models.BooleanField(r"Is this database entry still active? (YES/NO)", null=False, blank=False, unique=False, choices=ENTRY_ACTIVE_YES_NO_CHOICES, help_text=r"Is this database entry still active? If it's been changed/modified to something else, mark this as False.") class AirportAdministrativeData(InfrastructureModel): officialAirportName=models.CharField(r"Airport's Official Name", max_length=100, null=False, blank=False, unique=True, help_text=r"Offical name of the Airport") def __str__(self): return self.officialAirportName class AirportAlternateName(InfrastructureModel): parentAirport=models.ForeignKey(AirportAdministrativeData,on_delete=models.RESTRICT,limit_choices_to={'entryActiveYesNo': True},verbose_name="Parent Airport",related_name='AirportOfficialName') alternateAirportName=models.CharField(r"Airport's Alternate Name", max_length=100, null=False, blank=False, unique=True, help_text=r"Alternate name of the Airport, if any.") class AirportLocation(InfrastructureModel): parentAirport=models.ForeignKey(AirportAdministrativeData,on_delete=models.RESTRICT,limit_choices_to={'entryActiveYesNo': True},verbose_name="Parent Airport") latitude=models.DecimalField(max_digits=9, decimal_places=6) longitude=models.DecimalField(max_digits=9, decimal_places=6) airportAddress=models.CharField(r"Airport's Address", max_length=200, null=False, blank=False, unique=True, help_text=r"Airport's Address") airportState=models.ForeignKey(State,on_delete=models.RESTRICT,limit_choices_to={'entryActiveYesNo': True},verbose_name="State") And their corresponding Admin classes are as follows: class AirportAdministrativeDataAdmin(admin.ModelAdmin): fields = ['officialAirportName', 'entryActiveYesNo'] list_display = ('officialAirportName', 'entryActiveYesNo') search_fields = ['officialAirportName'] search_help_text="Seach here for offical/alternate name of any airport in the Database." class AirportAlternateNameAdmin(admin.ModelAdmin): fields = ['parentAirport', 'alternateAirportName', 'entryActiveYesNo'] list_display = ('parentAirport', 'alternateAirportName', 'entryActiveYesNo') search_fields = ['alternateAirportName'] search_help_text="Seach here for offical/alternate name of any airport in the Database." class AirportLocationAdmin(admin.ModelAdmin): fields = ['parentAirport', 'latitude', 'longitude', 'airportAddress', 'airportState', 'entryActiveYesNo'] list_display = ('parentAirport', 'latitude', 'longitude', 'airportAddress', 'airportState', 'entryActiveYesNo') #search_fields = ['parentAirport'] search_help_text="Seach here for offical/alternate name of any airport in the Database." And their corresponding admin site registrations are … -
How to translate the name of permission in django
i have a question. When i add a group in django admin the permissions are displayed in English (can add, change etc) but i want to translate those permissions to in french since my website is based on django admin How can I do that? -
Django - Custom model cannot appear on User model
I have created a model in Django v4, and I want to show the information inside the User admin view. After migrating, a new table was created successfully and data is being stored. Here is the code: models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE ) address = models.CharField( max_length=20, blank=True, null=True ) def __str__(self): return self.user.username admin.py from django.contrib import admin from django.contrib.auth.models import User from .models import Profile class ProfileInline(admin.StackedInline): model = Profile can_delete = False verbose_name_plural = 'Extra Information' @admin.register(ProfileInline) class UserAdmin(admin.ModelAdmin): inlines = [ ProfileInline, ] The table that has been created has the following stored: id address user_id 3 Test 2 Where the user_id column, is a foreign key from the auth_user table, which is created automatically (I guess?). Now, when I try to run, makemigrations, etc, it shows me the following: AttributeError: type object 'ProfileInline' has no attribute '_meta' What is the proper way to have the information appended to the User, as the default sections do? -
Django + Caddy = CSRF protection issues
I deployed a Django 4 app with Daphne (ASGI) in a docker container. I use Caddy as a reverse proxy in front. It works, except I can't fill in any form because the CSRF protection kicks in. So no admin login, for example. I can currently access the admin interface in two ways: Directly through docker, via a SSH tunelled port Through Caddy, which is then forwarding to the Docker container. Option 1 works. I can log into the admin interface just as if I was running the development server locally. All is working as expected. However, option 2 (caddy reverse proxy) doesn't work. I can access Django and load pages, but any form submission will be blocked because the CSRF protection kicks in. CSRF verification failed. Request aborted. Reason given for failure: Origin checking failed - https://<mydomain.com> does not match any trusted origins. My Caddyfile contains this: <mydomain.com> { reverse_proxy localhost:8088 } localhost:8088 is the port exposed by my docker container. In an effort to eliminate potential issues, I've set the following to false in my config file: SECURE_SSL_REDIRECT (causes a redirect loop, probably related to the reverse proxying) SESSION_COOKIE_SECURE (I'd rather have it set to True, but I … -
Django Tenants superuser creation
When we create a superuser per scheme via ./manage.py create_tenant_superuser --username=admin2 --schema=client2 The created super user can also login to "public" schema's admin page as well as other schema's admin pages. While it can NOT edit other tenants' data it can modify the other super tenants information such as password's created under other schemas. So is this the expected behavior? should each tenant have their own ,fully isolated admin page under /Admin? -
I have a problem with Django database. in model
I have specified that my bio and image fields can be empty, but why does it give me an error and say that I have to fill it in? class User_account(models.Model): email = models.EmailField() fullname = models.CharField(max_length=30) username = models.CharField(max_length=20) password = models.CharField(max_length=30) marital_status = models.BooleanField(default=False) bio = models.CharField(null=True, max_length=200) visitor = models.IntegerField(default=0) image = models.ImageField(null=True, upload_to='profile_img') -
react : unexpected token < in JSON at position 0 with api call to django restframework
I have a react app running ok when i put yarn start, but giving me this error when I do yarn build and serve -s build : Unexpected token < in JSON at position 0 The code in question is: fetch("/api/blog/tags/?format=json") .then(response=>{ if (response.ok){ return response; } else{ var error= new Error('Error '+response.status+': '+response.statusText) error.response = response; throw error; } }, I have tried to change the api call adding ?format=json like this : /api/blog/tags/?format=json But I still have this error. From the many posts on the subject, i have seen it is caused by a body page in html when the fetch method is expecting json. But i dont know where to investigate to debug this now. Thank you -
AccessDeniedError at /auth/convert-token (access_denied) Your credentials aren't allowed <oauthlib.Request SANITIZED>
I am using Django 4.0 with python 3.9 and I installed drf-social-oauth2 in my app. I was using the now depreciated gapi Oauth2 for google login and it worked fine. Then I started getting warnings in my console that it'll not be in use for some time to come so I changed to the new google Identity Service(gsi client). What I used to get from gapi was an access_token which I use to verify users on my backend. now I get a credential jwt which I'm supposed to decode to get user details. when I send this code to the /auth/convert-token/ end point, I get AccessDeniedError at /auth/convert-token (access_denied) Your credentials aren't allowed <oauthlib.Request SANITIZED> all my details are correct and I'm stuck. Tested this using vscode thunder client. -
How do I edit my serializer create() method to make relationship to nested object in Django REST Framework?
In my app, Groups are created by Users class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["user_id", "username"] class GroupSerializer(serializers.ModelSerializer): owner = UserSerializer() class Meta: model = Group fields = ["name", "picture_url", "owner", "members"] def create(self, validated_data): owner_data = validated_data.pop("owner") user = User.objects.filter(user_id=owner_data.get("user_id")) instance = Group.objects.create(**validated_data) instance.owner = user instance.save return instance I'm trying to have it so that I can create a Group object, which can only have an existing User as its owner, but somehow when I post the following: "owner": { "user_id":6 }, "picture_url":"nothing", "name":"jazz club" } It returns this: { "owner": { "user_id": [ "user with this user id already exists." ], "username": [ "This field is required." ] } } For context, my post method looks like this: def post(self, request): new_group = request.data new_group["members"] = [] serializer = self.serializer_class(data=new_group) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) And my models look like this: class User(models.Model): id = models.BigAutoField(primary_key=True, unique=True) user_id = models.BigIntegerField(unique=True) username = models.CharField(max_length=100) class Group(models.Model): name = models.CharField(max_length=255, unique=True) picture_url = models.CharField(max_length=255) owner = models.ForeignKey( User, on_delete=models.CASCADE, related_name="owned_groups", blank=True, ) members = models.ManyToManyField(User, related_name="groups", blank=True) What do I need to change to make this work? I've tried a lot of different stuff. -
Django-import-export not importing csv or excel file in The Django admin site panel?
I am using the Django-import-export module in Django(version 4.0.1). I have 2 different tables named State and District the district model is using state_name as ForeignKey The fields in state table can be imported from the Django admin site panel without any issue as: but district attributes can not be imported via csv/excel file and the error is as follows: Line number: 1 - State matching query does not exist. ANDAMAN AND NICOBAR ISLANDS, NICOBARS Traceback (most recent call last): File "C:\Python_Abhilash\AppData\Local\Programs\Python\Python310\lib\site-packages\import_export\resources.py", line 667, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "C:\Python_Abhilash\AppData\Local\Programs\Python\Python310\lib\site-packages\import_export\resources.py", line 359, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "C:\Python_Abhilash\AppData\Local\Programs\Python\Python310\lib\site-packages\import_export\resources.py", line 352, in get_instance return instance_loader.get_instance(row) File "C:\Python_Abhilash\AppData\Local\Programs\Python\Python310\lib\site-packages\import_export\instance_loaders.py", line 29, in get_instance params[field.attribute] = field.clean(row) File "C:\Python_Abhilash\AppData\Local\Programs\Python\Python310\lib\site-packages\import_export\fields.py", line 66, in clean value = self.widget.clean(value, row=data, **kwargs) File "C:\Python_Abhilash\AppData\Local\Programs\Python\Python310\lib\site-packages\import_export\widgets.py", line 406, in clean return self.get_queryset(value, row, *args, **kwargs).get(**{self.field: val}) File "C:\Python_Abhilash\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 439, in get raise self.model.DoesNotExist( damuwhatsapp.models.State.DoesNotExist: State matching query does not exist. The model.py is as: from django.db import models #################################################################################### class State(models.Model): state_name = models.CharField(max_length=30) class Meta: db_table = 'State_Names' def __str__(self): return self.state_name #################################################################################### class District(models.Model): state_name = models.ForeignKey(State, on_delete=models.CASCADE) district_name = models.CharField(max_length=30) class Meta: db_table = 'District_Names' def __str__(self): return self.district_name The resources.py … -
connect ECONNREFUSED 127.0.0.1:9000 vscode error for dockerized project
Im trying to use debugpy in vscode for dockerized Django project, but i got this error i put port 9000 in docker compose and my remoteroot is correct this is my launch.json { "version": "0.2.0", "configurations": [ { "name": "Run Django", "type": "python", "request": "attach", "justMyCode": false, "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/s" } ], "port": 9000, "host": "localhost", } ] } i couldnt find problem, can u help me? thanks in advance -
Correct way of writing a filter query on a geodjango model (finding out if a multipolygon field contains a point)
I am new to geodjango and am trying to build an application after going through the tutorial. So, I have this model: from django.contrib.gis.db import models class CountryBorder(models.Model): f_code = models.CharField(max_length=5) name = models.CharField(max_length=254) .... .... #the multipolygonfield on which I want to perform lookup geom = models.MultiPolygonField(srid=4326) def __str__(self): return self.name and I am trying to find the model instance which contains (the model.geom field contains) a point. I tried doing that as described in the documentation: from app_name.models import CountryBorder from django.contrib.gis.geos import Point pnt = Point(23.1827, 75.7682) CountryBorder.objects.get(geom_contains=pnt) But I get the following error message: django.core.exceptions.FieldError: Cannot resolve keyword 'geom_contains' into field. Choices are: f_code, geom,name..... Am I missing something? -
Django Rest Framework @api_view(['POST])
Is there way to return default content in function based @api_view(['POST']) Like a class based generics.CreateAPIView enter image description here -
Django's prefetch_related method asynchronously blocking HTTP response
Does Django's prefetch_related method block the thread returning the http response in some sort of async way? def test_view(request): rows = SomeModel.objects.prefetch_related('some_m2m_field') num_rows = len(rows) print(num_rows) return JsonResponse({'num_rows':num_rows}) I know that the correct way to get the number of rows is .count(), I'm using len() here as a simple way to force evaluation of the queryset. In reality, I'm not even interested in the number of rows, just doing this as a simplification so that we don't have to get into my business logic. So, here's the goofy thing, when running on a DB with ~25k rows the above code will print the number to the terminal in just a second or two, but it will take over a minute to return the JSON to the browser!? When you remove the prefetch_related, everything happens nice and snappy, but I need that prefetch_related for my actual business logic, which has been omitted here for simplicity. I understand that the prefetch is going to make the query slower, but something else has to be going on here right? if it were just a slow query the print statement would take just as long as the JsonResponse? -
ModuleNotFoundError: No module named 'blog.settings' Django
I'm trying to create a simple blog app in Django. But, the problem is I keep getting an error when I try to run server: ModuleNotFoundError: No module named 'blog.settings' So far, I've checked the INSTALLED_APPS and urls.py and found no isssue with any of them. Basically, I don't know why am I am getting this error, so I would just list the some contents of my project: . └── my_site ├── blog │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── __init__.py │ │ └── __pycache__ │ │ └── __init__.cpython-38.pyc │ ├── models.py │ ├── __pycache__ │ │ ├── admin.cpython-38.pyc │ │ ├── apps.cpython-38.pyc │ │ ├── __init__.cpython-38.pyc │ │ ├── models.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── views.cpython-38.pyc │ ├── static │ │ └── blog │ │ ├── includes │ │ ├── index.css │ │ ├── post.css │ │ └── posts.css │ ├── templates │ │ └── blog │ │ ├── includes │ │ ├── index.html │ │ ├── post.html │ │ └── posts.html │ ├── tests.py │ ├── urls.py │ └── views.py ├── db.sqlite3 ├── manage.py ├── my_site │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ │ ├── … -
Azure deployed django app not displaying media files on Vuejs frontend in prooduction
These are the packages that I am using Django==3.2 django-storages==1.12.3 I am trying to deploy a django REST API with Vuejs frontend on azure. This is my directory structure for the django API. I have used djang-storages[azure] to use an azure container blob to store media files. I went through a tutorial to setup the blob connection with django. Some configuration that I did with settings.py are these Settings.py MEDIA_LOCATION = "media" AZURE_ACCOUNT_NAME = "my account name" AZURE_ACCOUNT_KEY="my token" AZURE_CUSTOM_DOMAIN = f'{AZURE_ACCOUNT_NAME}.blob.core.windows.net' AZURE_LOCATION="media" AZURE_CONTAINER="media" STATIC_LOCATION = "static" STATIC_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{STATIC_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.azure_storage.AzureStorage' DEFAULT_FILE_STORAGE = 'el.custom_azure.AzureMediaStorage' AZURE_CONNECTION_TIMEOUT_SECS=100 and my custom_azure.py looks like this custom_azure.py from storages.backends.azure_storage import AzureStorage class AzureMediaStorage(AzureStorage): account_name="eltechstorage" account_key="my token" azure_container="media" expiration_specs=None urls.py from django.contrib import admin from django.urls import path,include from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path("",include("main.urls")) ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) When I am using azure blob container to upload media files it is working perfectly in development environment and when I am testing the API from the deployed url, it is giving me the path of the file as expected on which if i go to, downloads the file for me, everything is … -
Django: 'Response' object has no attribute 'get' when using "del request.session['key']"
Hello I'm trying to practice my understanding of Django sessions and I ran into this error. what I'm trying to do is to save a counter to count how many times a user visited the (' ') route and display it on the Django template and then the key will be destroyed when visiting the route ('/destroy'). Views.py from django.shortcuts import redirect, render from flask import session,redirect # Create your views here. def index(request): request.session['counter']=int(request.session.get('counter',0))+1 return render(request,'index.html') def destroy(request): del request.session['counter'] return redirect('') urls.py from . import views urlpatterns = [ path('', views.index), path('destroy',views.destroy) ] django template <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>Counter</title> </head> <body> <div class="wrapper"> <h1>Counter</h1> <p>{{request.session.counter}} times</p> </div> </body> </html> -
django model pre_save update() has problems
Background: I have Tag models that have an attribute is_obsolete (default set to False) class Tag(model.Model): ... is_obsolete = False I have StatusInfo models that have a foreign key to Tag through "affected_tag". class StatusInfo(models.Model): ... affected_tag = ForeignKey(Tag) When the StatusInfo instance is created they fire off the pre_save() signal to change <StatusInfo>.affected_tag.is_obsolete=True @receiver(pre_save, sender=StatusInfo) def status_change_modification(sender, instance, *args, **kwargs): """ Changes tags and concepts to be obsolete or deprecated. if a tag is obsolete or deprecated, all of the tag's concepts are obsolete or deprecated """ assert hasattr(instance.affected_tag, "id") # set up variables kwargs = {} if instance.status == "d": kwargs["is_deprecated"] = True elif instance.status == "o": kwargs["is_obsolete"] = True inner_tag_status_change(instance, **kwargs) def inner_tag_status_change(instance, **kwargs): """ update the is_updated fields for status_info kwargs is either: kwargs = {'is_obsolete': True} # or {'is_deprecated': True} """ affected = Tag.objects.filter(id=instance.affected_tag.id).first() affected.__dict__.update(**kwargs) affected.save(update_fields=list(kwargs.keys())) Problem What I can't figure out is why when this hits the bottom of the test I still have my Tag instance self.soon_to_be_obsolete_tag.is_obsolete == False I've tried .update(**kwargs) and .save(updated_fields=list(kwargs.keys())) inside inner_tag_status_change() but it doesn't save the changes It looks good when stepping through it in debug mode then it reverts back for the last line of the test. … -
Django-unicorn| HTML & Django selected option return 404
I need some pointers around ajax while trying to select an option on the components I've published on the template I've got a 404 response from the JS script. I don't have enough knowledge to identify and debug the JS script myself any pointer for this problem would be greatly appreciated. my code so far: app's views.py from django.views.generic.base import TemplateView class ProductDetailView(TemplateView): template_name = 'product/product_detail.html' components.py from django_unicorn.components import UnicornView from django.http.request import HttpRequest as request from django.db.models import Q from django.shortcuts import get_object_or_404, get_list_or_404 from navigation.models import * from inventory.models import * class ProductDetailView(UnicornView): selected_finition= "" selected_size= "" def get_context_data(self, *args, **kwargs): context = super(ProductDetailView, self).get_context_data(**kwargs) #grab the slug in path to instantiate query with obj = get_object_or_404(Product, slug = self.request.get_full_path().split('/')[-2]) #print(f"product detail value data: {type(obj)}") detail = get_list_or_404(ProductDetail, SKU__startswith=obj.SKU) #print(f"product detail data: {detail}") context['obj'] = obj try: context['finition'] = ProductAttributeFinition.objects.filter(Q(SKU_id__in=detail)).distinct('name') except: return context['finition'] #print(f"dfinition detail :\n {context['finition']}") try: context['size'] = ProductAttributeSize.objects.filter(Q(SKU_id__in=detail)).distinct('value') except : return context['size'] #print(f"detail-size :\n {context['size']}") context['price'] = ProductDetailPrice.objects.filter(Q(SKU_id__in=detail)) #print(f"detail-price :\n {context['price']}") return context app's templates {% extends 'base.html' %} {% load unicorn %} {% block content %} {% unicorn 'product_detail' %} {% endblock %} unicorn templates <div> <h1>Product Detail Page unicorn</h1> <img src="{{obj.image.url}}"/> <p><span>{{obj.name}}</span></p> … -
Long running Celery task result in mysql 104 Connection reset by peer
At my Django application, I use celery to process very long-running conversion tasks (video, audio and picture encoding). In general everything is working as expected, but sometimes a task takes really long time to complete (talking 6 hrs. Or more here). At the very end of each of these conversion tasks, an update operation is trigger against my database: Files.objects.filter(pk=files_obj).update(... And exactly this is the point where my celery task breaks with this message: django.db.utils.OperationalError: (2006, "MySQL server has gone away (ConnectionResetError(104, 'Connection reset by peer'))") The full trace can be found here: https://pastebin.com/qKB5KdpR Currently, my settings.py for Database connections looks like this: import pymysql pymysql.install_as_MySQLdb() ... # MySQL DATABASES = { 'default': { 'ENGINE': 'django_prometheus.db.backends.mysql', # 'ATOMIC_REQUESTS': True, 'STORAGE_ENGINE': 'InnoDB', 'CONN_MAX_AGE': 600, 'OPTIONS': { 'init_command': 'SET innodb_strict_mode=1', 'connect_timeout': 600, 'charset': 'utf8', }, 'NAME': env.str('MYSQL_DATABASE'), 'USER': env.str('MYSQL_USER'), 'PASSWORD': env.str('MYSQL_PASSWORD'), 'HOST': env.str('MYSQL_HOST'), 'PORT': env.str('MYSQL_PORT'), } } DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' ... Enlarging CONN_MAX_AGE or connect_timeout does not make much sense to me here as tasks that are running for just 3 or 4 hrs. Are processed fine without this behavior. Currently, my guess is that this behavior is pymysql specific. Is there maybe a default timeout? Thanks in advance. -
How to set multiple enviroment variable in django-crontab ?Ac
According to this document https://pypi.org/project/django-crontab/ If I want to set a variable environment in crontab, I should do this CRONTAB_COMMAND_PREFIX="STAGE=production" provided I want to set multiple variables, what should I do ? I tried CRONTAB_COMMAND_PREFIX="STAGE=production,TOKEN=ABC" but seems to be not working -
how can I access updated template variable in different tags
How can i use a updated variable in different tags in django templates. I'm using python 3.10.x and django 4.0.4. Here is my template code. i want to use qn variable in the {% else %} part (after update). And for update I've written a custom tag. {% extends 'base.html' %} {% load static %} {% load custom_tags %} {% block style %} {% endblock %} {% block content %} <h1>Test</h1> {% if arr %} <form action="#" style="margin-left:10%;" > {% for line in arr %} {% with qn=line.0 %} <div class="form-check"> {% if line.0 not in "a, b, c, d" %} <h4> {{line}} </h4> {% update qn as line.0 %} ques{{qn}} {% else %} <input class="form-check-input" type="radio" name="ques{{qn}}" value="{{line}}" style="margin-left:2%; margin-right:1%;"> <label class="form-check-label" for="ques"> {{line}} </label> {% endif %} </div> {% endwith %} {% endfor %} <button type="submit" class="btn btn-primary" style="margin-top:3%;"> Submit Test </button> </form> {% else %} No Data {% endif %} {% endblock %} Here is the custom tag code from atexit import register from django import template import datetime register = template.Library() @register.simple_tag def update(val): data=val return data The qn variable is working fine if i'm using it in the {% if line.0 not in "a, b, … -
Failed to load resource: the server responded with a status of 503 (Service Unavailable)
I'm trying to deploy djnago web app on heroku. that is what console shows