Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Static Files Not Loading Correctly in Production with Apache
I've been struggling with serving static files in a Django application deployed on Apache. Despite following numerous guides and suggestions, I'm still encountering 404 errors for my static files. Below are the relevant details of my setup and the issues I'm facing. Environment: Django Version: 3.0 Python Version: 3.8 Web Server: Apache2 OS: Ubuntu Problem Description: In development mode with DEBUG=True, the static files load correctly and I can see my React build. However, in production with DEBUG=False (or even with Debug=True), I encounter the following errors: 404 errors for JavaScript and CSS files MIME type errors stating that the files are being served as text/html instead of their correct types Errors in Browser Console: GET https://www.myapp.com/static/js/main.a14a4a4b.js net::ERR_ABORTED 404 (Not Found) Refused to execute script from 'https://www.myapp.com/static/js/main.a14a4a4b.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. Refused to apply style from 'https://www.myapp.com/static/css/main.868dfa48.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. GET https://www.myapp.com/favicon.png 404 (Not Found) GET https://www.myapp.com/manifest.json 404 (Not Found) Manifest: Line: 1, column: 1, Syntax error. Directory Structure: Here's the structure of my staticfiles directory: /var/www/jmyapp/staticfiles: asset-manifest.json css favicon.png index.html js logo192.png logo512.png … -
window.location.href doesn't adding referer header when executed inside html wrapper but running that in console is adding referer header. Why?
I have two subdomains, let's call them x.example.com and y.example.com. When a user requests x.example.com, the server redirects them to y.example.com. On y.example.com, there's a feature that displays specific content if the referer header matches a certain value. However, when the request comes to y.example.com after the redirection, it doesn't have any referer header attached to it. I'm using Django on the backend to handle the redirection with HttpResponseRedirect("y.example.com"). I attempted to include the referer header in the server's response using Django, but it didn't seem to have any effect. response = HttpResponseRedirect("y.example.com") response['referer'] = 'https://x.example.com' Additionally, I tried implementing a redirection in JavaScript by returning HTML with embedded JavaScript code, but that also didn't result in the referer header being passed along. Interestingly, directly executing the JavaScript redirection in the browser console did include the referer header. I'm puzzled as to why it's not working as expected. Can you suggest an alternative approach to achieve the desired behavior? html_content = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Redirecting...</title> </head> <body> <h1>Redirecting...</h1> <script> // JavaScript code for redirection window.location.href = 'https://y.example.com'; }); </script> </body> </html> """ # Return the HTML response with embedded JavaScript return … -
504 Deadline Exceeded while using langchain_google_genai
Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/langchain_google_genai/embeddings.py", line 146, in embed_documents result = self.client.batch_embed_contents( File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/client.py", line 1350, in batch_embed_contents response = rpc( File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/google/api_core/gapic_v1/method.py", line 131, in call return wrapped_func(*args, **kwargs) File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/google/api_core/retry/retry_unary.py", line 293, in retry_wrapped_func return retry_target( File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/google/api_core/retry/retry_unary.py", line 153, in retry_target _retry_error_helper( File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/google/api_core/retry/retry_base.py", line 212, in _retry_error_helper raise final_exc from source_exc File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/google/api_core/retry/retry_unary.py", line 144, in retry_target result = target() File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/google/api_core/timeout.py", line 120, in func_with_timeout return func(*args, **kwargs) File "/Users/dhvanipatel/Library/Python/3.9/li b/python/site-packages/google/api_core/grpc_helpers.py", line 78, in error_remapped_callable raise exceptions.from_grpc_error(exc) from exc google.api_core.exceptions.DeadlineExceeded: 504 Deadline Exceeded The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/django/core/management/commands/runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/django/core/management/base.py", line 485, in check all_issues = checks.run_checks( File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/django/core/checks/urls.py", line 24, in check_resolver return check_method() File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/django/urls/resolvers.py", line 494, in check for pattern in self.url_patterns: File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/django/urls/resolvers.py", line 715, … -
How to deploy front end & backend apps on same machine with same domain but different ports?
I have two apps one for frontend built using ReactJS and one is for backend built using Django. I have server machine where I have deployed both the apps. Now I want to use Nginx (because of SSL) to host both my application on the same machine with same domain name but the ports are different. I know how to do it for different domains or subdomain but I don't have another domain/subdomain with me right now. So I want to aks how I can achive this in Nginx? For example my FE is using port 4173 & BE is using 8000,I am able to configure Nginx to serve my FE but I am getting this error, Blocked loading mixed active content because my FE which is httpstrying to connect to backend on port 8000 which is not https. Here is my nginx config file server { listen 80; server_name camfire.pp.ua; # Перенаправлення HTTP на HTTPS location / { return 301 https://$host$request_uri; } } server { listen 443 ssl; server_name camfire.pp.ua; # Шляхи до сертифікатів SSL ssl_certificate /etc/letsencrypt/live/camfire.pp.ua/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/camfire.pp.ua/privkey.pem; # Проксирування запитів до FrontEnd location / { proxy_pass http://localhost:4173; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header … -
**404 Error with `drf_with_firebase_auth` Signup Endpoint**
I'm following the tutorial from the GitHub repository [https://github.com/Abiorh001/drf_with_firebase_auth] and have completed the setup steps. However, I'm encountering a 404 error (Not Found) when trying to send a signup request to http://127.0.0.1:8000/api/v1/users/auth/sign-up/ using Postman. I've checked the urls.py file and the URL pattern seems to be defined correctly. I've also set the environment variables for Firebase credentials as instructed in the tutorial. There are no error messages in the console. this is the result when i try to send request in postman For reference, this is urls.py from accounts app: urlpatterns = [ path('auth/sign-up/', AuthCreateNewUserView.as_view(), name='auth-create-user'), path('auth/sign-in/', AuthLoginExisitingUserView.as_view(), name='auth-login-drive-user'), path('<str:pk>/', RetrieveUpdateDestroyExistingUser.as_view(), name='retrieve-update-user'), path('auth/update-email-address/', UpdateUserEmailAddressView.as_view(), name='user-update-email-address'), path('auth/reset-password/', UserPasswordResetView.as_view(), name='user-reset-password'), ] and this is my main projects urls.py api_version = 'v1' urlpatterns = [ path(f'api/{api_version}/admin/', admin.site.urls), path(f'api/{api_version}/users/', include('accounts.urls')), re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), path(f'api/{api_version}/swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path(f'api/{api_version}/redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ] What could be causing the 404 error when trying to sign up Thanks in advance for any help! I have looked for solution all over the internet but i found nothing that could help me. -
JWT refresh in Angular 17
My backend is Django restframework. when I give my credentials it gives me tokens which are consist of refresh and access tokens. In my backend my access_tokens expiration time is 2 minutes(just for testing but will increase till 15 minutes). and refresh_tokens expiration time is 15 days. when my access_token expires I send my refresh_token to fetch new access_token(only provides access_token). On front_end (Angular 17), I have implemented to fetch the new access_tokens instead of getting new tokens I am getting logout after 2 minutes. I am new to Angular. I tried to debug but couldn't find the solution. I am posting my service class and interceptor. export const authInterceptor: HttpInterceptorFn = (req, next) => { const auth_service = inject(AuthService); const accessToken = auth_service.getAccessToken(); let authReq = req; if (accessToken) { authReq = req.clone({ setHeaders: { Authorization: `Bearer ${accessToken}` } }); } return next(authReq).pipe( catchError((error: HttpErrorResponse) => { if (error.status === 401 && error.error.code === 'token_not_valid') { console.log('Token expired, attempting to refresh...'); // Token expired, attempt to refresh return auth_service.refreshTokenRequest().pipe( switchMap(() => { const newAccessToken = auth_service.getAccessToken(); if (newAccessToken) { console.log('New access token received'); authReq = req.clone({ setHeaders: { Authorization: `Bearer ${newAccessToken}` } }); } return next(authReq); }), catchError((err) => … -
django using template tag from one app to the other
hey guys Im stuck in some problem, as a question, I'm working on a django base website which has 5 pages two apps in it, blog app has posts in it and the other app website is for home_page, so the deal is I have to show the latest posts in home_page with using template tag but with my solution it was never shown. # index_tag.py Post is what I created in blog models and called here for reuse it from django import template from blog.models import Post register = template.Library() @register.inclusion_tag('website/home-latest-posts.html') def latestposts(arg=3): posts = Post.objects.filter(status=1).order_by('published_date')[arg:] return {'posts': posts} <!-- home-latest-posts.html --> {% load static %} {% load index_tags %} <div class="row"> <div class="active-recent-blog-carusel"> {% for post in posts %} <div class="single-recent-blog-post item"> <div class="thumb"> <img class="img-fluid" src="{{post.image.url}}" alt=""> </div> <div class="details"> <div class="tags"> <ul> <li> <a href="#">Travel</a> </li> <li> <a href="#">Life Style</a> </li> </ul> </div> <a href="{% url 'website:index' pid=post.id %}"><h4 class="title">{{post.title}}</h4></a> <p>{{post.content}}</p> <h6 class="date">{{post.published_date|date:'d M Y'}}</h6> </div> </div> {% endfor %} </div> </div> <!-- index.html after many codes this is the template tag that I created --> {% extends "base.html" %} {% load static %} {% load index_tags %} {% block content %} <!-- Start blog Area … -
how to send data with formset empty_form to database Django
i use inlineformset_factory to create dynamic row in django for create or update i don't have a problem but for empty_form i get some issues formset.empty_form.visible_fields they don't send data for database and save it. template code {{formset.management_form}} {% for fields in formset.empty_form.visible_fields %} <td>{{fields}}</td> {% endfor %} view.py if form.is_valid(): save_form = form.save() if formset.is_valid(): formset.save() save_form.save() return redirect("/") form.py ItemFormSet = inlineformset_factory( Invoice, InvoiceItem, form=InvoiceItemForm, extra=1,can_delete=False) i want clicck a button add field and post this field value to database in django -
Django ValueError: dictionary update sequence element #0 has length 653; 2 is required
i am sending request to backend like this const createOrderButton = document.getElementById('createUserCart'); createOrderButton.addEventListener('click', function () { const urlAddress = document.getElementById('cart-wrapper').getAttribute('action'); console.log(JSON.stringify(cart)); if (urlAddress === '/orders/') { let promise = fetch(urlAddress, { method: "POST", headers: { 'Content-Type': 'application/json', "X-CSRFToken": CSRF_TOKEN }, body: JSON.stringify(cart) }); console.log(promise); } }); the cart object is like [{"product_id" : 1, "name" : "item1", "img_src":"https://...", ...}, {}, ...] my views.py class CreateCart(View): template_name = "orders/index.html" def post(self, request): user_cart = json.loads(request.body.decode()) random_id = uuid.uuid4() date_create = now() cart_objects_to_create = [ Cart( user=User.objects.get(id=request.user.id), product=Product.objects.get( id=int(el['product_id']) ), cart_id=random_id, date_create=date_create ) for el in user_cart ] Cart.objects.bulk_create(cart_objects_to_create) return render(request, self.template_name) This code is insert objects into sql table, but dont render template and i see error Internal Server Error: /orders/ Traceback (most recent call last): File "/Users/danya/CodeProject/djangoMarketPlace/venv/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/danya/CodeProject/djangoMarketPlace/venv/lib/python3.12/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/danya/CodeProject/djangoMarketPlace/venv/lib/python3.12/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/danya/CodeProject/djangoMarketPlace/venv/lib/python3.12/site-packages/django/views/generic/base.py", line 143, in dispatch return handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/danya/CodeProject/djangoMarketPlace/orders/views.py", line 42, in post return render(request, self.template_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/danya/CodeProject/djangoMarketPlace/venv/lib/python3.12/site-packages/django/shortcuts.py", line 25, in render content = loader.render_to_string(template_name, context, request, using=using) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/danya/CodeProject/djangoMarketPlace/venv/lib/python3.12/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, … -
paypal subscription payment doesnt open on django
I am trying to make a subscription using django and paypal payment. I'm trying to complete a course. I have made my plans in business sandbox. I've used the code it gives you after making plans and turn them on. I simply copied and pasted the code into my page. It is a local server. When I click on Paypal buttons they open a blank page. I checked my Inspect and it shows these each time I click on links. First error: create_order_error Object { err: 'Create Subscription Api response error:\n\n{\n "name": "RESOURCE_NOT_FOUND",\n "message": "The specified resource does not exist.",\n "debug_id": "f913475242396",\n "details": [\n {\n "issue": "INVALID_RESOURCE_ID",\n "description": "Requested resource ID was not found."\n }\n ],\n "links": [\n {\n "href": "https://developer.paypal.com/docs/api/v1/billing/subscriptions#RESOURCE_NOT_FOUND",\n "rel": "information_link",\n "method": "GET"\n }\n ]\n}', timestamp: "1717846131222", referer: "www.sandbox.paypal.com", sdkCorrelationID: "0b604ba725142", sessionID: "uid_ffb7a1abe3_mte6mjc6mjk", clientID: "AZDxjDScFpQtjWTOUtWKbyN_bDt4OgqaF4eYXlewfBP4-8aqX3PiV8e1GWU6liB2CUXlkA59kJXE7M6R", env: "sandbox", buttonSessionID: "uid_ef868db584_mte6mjg6ndg", buttonCorrelationID: "f3594475ad16f", token: null } Seconf error: Uncaught Error: Create Subscription Api response error: { "name": "RESOURCE_NOT_FOUND", "message": "The specified resource does not exist.", "debug_id": "f693155709fe0", "details": [ { "issue": "INVALID_RESOURCE_ID", "description": "Requested resource ID was not found." } ], "links": [ { "href": "https://developer.paypal.com/docs/api/v1/billing/subscriptions#RESOURCE_NOT_FOUND", "rel": "information_link", "method": "GET" } ] } Last one is a warning: click_initiate_payment_reject Object … -
How can I solve the no module_found issue in Django?
after creating the venv I have installed the django to the venv.Also I have added the installed apps also but its showing no module named module_name.settings error. Can anyone help ? ModuleNotFoundError: No module named 'chatbot.settings' I were trying to create a chatbot and actually it were working in the begining, because of an issue in git i just changed the folder. Since that happens the same error is showing And also I have tried to create the project from the beginning and the same error is encountering. -
Are name="submit" and name="next" predefined attributes in Django?
I'm reading a book 'Python Crash Course 2nd edition' and currently doing a Django project. And in a form there are button with name="submit" and and hidden input element with name="next". In the book it says that the button with name="submit" is a submit button and a hidden form element with name "next" is the value argument that tells Django where to redirect the user after they’ve logged in successfully. I tried to search up button with name="submit" and input hidden element with name="next" in Django but wasn't able to find any info. How does it work? Are those somewhere predefined or no? <form method="post" action="{% url 'users:login' %}"> {% csrf_token %} {{ form.as_p }} <button name="submit">Log in</button> <input type="hidden" name="next" value="{% url 'learning_logs:index' %}" /> </form> -
Redis aa cache manager in django project
What is the difference between using redis as pip install redis in your django project and keeping redis as a separate instance in another server? Will using redis in a project incur additional costs if I am using in as a package in my ec2 instance. -
Django form to save m2m additional fields (using custom through\assosiation table)
I have a "Recipe" model, which contains multiple "Product" models and the relationship between Recipe and Product holds the quantity of the products. Thus, I need a custom intermediary model. models.py: class Product(models.Model): name = models.CharField(max_length=50, null=False, blank=False) quantity = models.PositiveSmallIntegerField(null=False, blank=False) ... class Recipe(models.Model): name = models.CharField(max_length=50, null=False, blank=False) ingredients = models.ManyToManyField(Product, through='ProductRecipe') ... class ProductRecipe(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) quantity = models.SmallIntegerField(null=True) A Recipe object is created based on a form and the Product objects to be part of the Parent object are selected by checkboxes. My question is, how can we add ProductRecipe.quantity field to my form when Recipe object is being created. Here is my forms.py that I use for Recipe object creation class RecipeForm(ModelForm): class Meta: model = Recipe fields = ['name ', ... , 'ingredients'] ingredients = forms.ModelMultipleChoiceField( queryset=Product.objects.all(), widget=forms.CheckboxSelectMultiple ) Trying to have additional field 'quantity' while creating Recipe object from django form -
module 'jwt' has no attribute 'PyJWTError'
module 'jwt' has no attribute 'PyJWTError' I'm trying to set up authorization via Google and I get this error. Is it a problem with version incompatibility? Sorry, I'm new to this. Exception Location: /usr/local/lib/python3.11/site-packages/allauth/socialaccount/internal/jwtkit.py, line 85, in verify_and_decode Django Version: 5.0.6 PyJWT Version: 2.8.0 -
Insert different formated date in django
I have a Date input field in my form like below. <label class="form-label">Date of Birth</label> {{ form.date_of_birth }} {% if form.date_of_birth.errors %} <div class="alert alert-danger">{{ form.date_of_birth.errors }}</div> {% endif %} I am trying to insert date 08/06/2024. I am getting error Enter a valid date.. I am using below code in forms.py. date_of_birth = forms.DateField( required=True, input_formats=['%d/%m/%Y'] ) I am using below code in settings.py. DATE_INPUT_FORMATS = ['%d/%m/%Y'] -
How to Implement a Mock Authorization Service in a Django Project for Token-Based Authentication?
I'm currently working on a Django project where I need to implement a mock authorization service to simulate the integration of an authentication system. The goal is to ensure that each API request is authenticated and authorized using tokens from the mock authorization provider. Here are the details of my current setup: urls.py: from django.contrib import admin from django.urls import path, include from rest_framework import routers from rest_framework.authtoken import views as authtoken_views from security.views import SecurityRecordViewSet, UserCreate router = routers.DefaultRouter() router.register(r'security-records', SecurityRecordViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), path('api-token-auth/', authtoken_views.obtain_auth_token), path('register/', UserCreate.as_view(), name='user-create'), ] models.py: from django.db import models class SecurityRecord(models.Model): name = models.CharField(max_length=100) description = models.TextField() def __str__(self): return self.name serializers.py: from django.contrib.auth.models import User from rest_framework import serializers from .models import SecurityRecord class SecurityRecordSerializer(serializers.ModelSerializer): class Meta: model = SecurityRecord fields = ['id', 'name', 'description'] def validate(self, attrs): name = attrs.get('name', '') if len(name) < 5: raise serializers.ValidationError('Name must be at least 5 characters long.') description = attrs.get('description', '') if len(description) < 10: raise serializers.ValidationError('Description must be at least 10 characters long.') return super().validate(attrs) class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'password', 'email'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user( … -
I'm not being able to create users in my django application through the registration form that I created
I can create users through the manage.py shell, but not through the registration form, when I click the submit button, it just reloads the page and nothing else happens, also, my vs code is underscoring the create_user function in the line "user = Account.objects.create_user(...", it says "Cannot access attribute "create_user" for class "BaseManager[Account]"" This is my forms.py: from django import forms from .models import Account class RegistrationForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput(attrs={ 'placeholder': 'Enter Password', })) ` confirm_password = forms.CharField(widget=forms.PasswordInput(attrs={ 'placeholder': 'Confirm Password', })) email = forms.EmailField( max_length=255, help_text="Required. Add a valid email address.") document = forms.CharField(widget=forms.TextInput(attrs={ 'placeholder': '(CPF/RG/PASSPORT)', }), max_length=15, help_text="Enter a valid CPF, RG, or Passport.") address = forms.CharField(widget=forms.TextInput(attrs={ 'placeholder': '1337 Example St, FL, US', }), max_length=255, help_text="Enter your address.") class Meta: model = Account fields = ['first_name', 'last_name', 'username', 'phone_number', 'email', 'address', 'document', 'password'] def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) self.fields['phone_number'].widget.attrs['placeholder'] = '(xx) x xxxx-xxxx' for field in self.fields: self.fields[field].widget.attrs['class'] = 'form-control'` This is my models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, first_name, last_name, document, phone_number, email, username, address=None, password=None, TCM_wallet=0): if not email: raise ValueError('User must have an email address.') if not username: raise ValueError('User must have a username.') if … -
How is my Heroku app using Postgres if I haven't explicitly configured it?
I'm working moving a local Django app to Heroku so I can access from other computers. This is a personal project, which means I've been hacking a few things together to learn the systems. I have been using SQLite3 locally (that was the default, I didn't know any better). I've attached a Postgres database to the Heroku application. With some initial tests, I've noticed that the Heroku version of the app is able to use the Postgres database, though I have made no changes to my settings.py file. For example, this is what my database configuration looks like: DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3"), } I am surprised by this compatibility. How is the Heroku app able to connect to the Postgres database when I haven't done any explicit configuration to make it work? I assume there is something happening behind the scenes that overrides the SQLite3 database config in favor of the Postgres database. -
Django lookup values in table from array of keys in template
I’ve been battling with this Django and DB issue for the last few days but am stuck now. I have an SQLite DB with, among other things, a table with attribute_id and attribute_name. The attribute_id fields increase in 10 step increments as I may need to manually insert attributes without impacting the ids and order of existing attributes. It currently has 186 attributes in it with ids from 10 to 1830. I don’t expect this table to ever grow beyond 200 attributes so it’s small and always will be. That may be important for performance purposes. In another table in the same DB I have items, currently about 1000. This number will grow but I don’t expect it to ever grow beyond 100,000 items. Every item in the table has a text field called attributes that holds an array with the attribute_id of one or more attributes. I don’t expect an item to ever have more than 10 attribute_ids in this field. In a Django template I wish to show the attribute_name for each item in comma separated text while retaining the order of the attribute_ids in the array. That is where I’m stuck. In a For Loop of potentially … -
I cannot create a pre-filled form in python django
I am doing a simple project to practice CRUD in Django and I am working on a simple "To Do" project and these area my codes- models.py from django.db import models # Create your models here. class ToDoList(models.Model): title = models.CharField(max_length = 100, null = False , blank = False) description = models.CharField(max_length = 1000 , null = True , blank = True ) date = models.DateField(null = True , blank = True ) def __str__(self): return self.title forms.py from django.forms import ModelForm from django import forms from .models import ToDoList class ToDoForm(ModelForm): class Meta : model = ToDoList fields = ['title','description','date'] widgets = { 'title': forms.TextInput(attrs={'class':'form-control'}), 'description':forms.Textarea(attrs={'class':'form-control'}), 'date': forms.DateInput(attrs={'type':'date'}), } urls.py from django.urls import path from . import views urlpatterns = [ path("",views.homepage,name = 'home_page'), path("add-new",views.add_todo,name = 'add_new'), path("delete-todo/<todo_id>",views.delete_todo,name = "delete_todo"), path("update_todo/<todo_id>",views.update_todo,name = "update_todo"), ] views.py from django.shortcuts import render , redirect from .forms import ToDoForm from django.contrib import messages from .models import ToDoList # Codes for the homepage def homepage(request): todos = ToDoList.objects.all() return render(request, 'index.html' , {'todos':todos}) # Codes for the add new todo def add_todo(request): form = ToDoForm() if request.method == "POST": form = ToDoForm(request.POST) if form.is_valid(): form.save() messages.success(request,("Added new todo")) return redirect('home_page') else: print('not valid') … -
Django: Get a button to cancel a booking from database
Some context for my question: My current project is an apartment booking homepage with Django (including allauth). Depending on who is logged in, different content is displayed. When a regular user (guest) logs in a Booking subpage "your-bookings.html" is displayed with an overview of the individual guests' bookings. When a superuser (apartment host) logs in a Booking subpage "all-bookings.html" is displayed with an overview of all guests' bookings. I've added 'cancel' buttons to those pages so that the guest can cancel their booking by clicking the button that sets the booking status from "requested" to "cancelled" in the database. The same function should also be available for the host with regard to all guests' bookings. your-bookings.html (functionality works as expected) <h1>Your Bookings</h1> {% if user.is_authenticated %} {% for booking in object_list %} <div class="card mx-auto" style="width:25rem;background-color:#e4dee8;"> <div class="card-body"> <h3 class="card-title">Booking number {{booking.id}}</h3><br> <h6 class="card-subtitle mb-2 text-body-secondary"> <b>Booking date:</b><br>{{booking.booking_date}}<br><br> <b>Status:</b> {{booking.booking_status}}<br><br> </h6> <p class="card-text"> <b>Name:</b><br> {{booking.first_name}} {{booking.last_name}}<br> [...] <b>Your message:</b><br> {{booking.message}}<br> </p> {% if booking.booking_status == "Requested" %} <button class="btn btn-card-cancel cancel border-dark" data-booking_id="{{ booking.id }}">Cancel Booking</button> {% endif %} </div> </div> <br> {% endfor %} {% endif %} all-bookings.html (functionality does not work as expected) <h1>All Bookings</h1> {% if user.is_superuser … -
Celery, Redis: multiplicating tasks and not executing them
Celery eats up RAM. We're using Celery in Django REST with Redis as the broker. Celery is used to send and retry sending callbacks, if unsuccessful (retry policy was to try sending callbacks with exponentially growing timeout between attempts, already removed). Once around every 1m 40s the use of RAM increases by 48mb while there's spam of this in the logs for a few seconds: celery_worker-1 | [2024-06-06 19:17:32,442: INFO/MainProcess] Task core.requests.celery_tasks.send_callback_task[6135c471-7f7e-471c-9f05-ba126418c002] received celery_worker-1 | [2024-06-06 19:17:32,444: INFO/MainProcess] Task core.requests.celery_tasks.send_callback_task[6135c471-7f7e-471c-9f05-ba126418c002] received celery_worker-1 | [2024-06-06 19:17:32,445: INFO/MainProcess] Task core.requests.celery_tasks.send_callback_task[6135c471-7f7e-471c-9f05-ba126418c002] received ... more 14 times celery_worker-1 | [2024-06-06 19:17:32,468: INFO/MainProcess] Task core.requests.celery_tasks.send_callback_task[f4aaa14f-8bda-442a-8856-af40f1d68e6d] received celery_worker-1 | [2024-06-06 19:17:32,469: INFO/MainProcess] Task core.requests.celery_tasks.send_callback_task[f4aaa14f-8bda-442a-8856-af40f1d68e6d] received celery_worker-1 | [2024-06-06 19:17:32,471: INFO/MainProcess] Task core.requests.celery_tasks.send_callback_task[f4aaa14f-8bda-442a-8856-af40f1d68e6d] received celery_worker-1 | [2024-06-06 19:17:32,472: INFO/MainProcess] Task core.requests.celery_tasks.send_callback_task[f4aaa14f-8bda-442a-8856-af40f1d68e6d] received ... more 55 times and many more with different IDs After some time we even get this in the logs: celery_worker-1 | [2024-06-07 17:32:56,200: INFO/MainProcess] Task core.requests.celery_tasks.send_callback_task[bb4b48c5-92d1-4226-aadf-bfdc387d4baf] received celery_worker-1 | [2024-06-07 17:32:56,200: WARNING/MainProcess] QoS: Disabled: prefetch_count exceeds 65535 The new tasks get executed instantly with logs like this (with no warnings about prefetch_count): celery_worker-1 | [2024-06-07 16:31:28,595: INFO/MainProcess] Task core.requests.celery_tasks.send_callback_task[7cdda9a2-ad10-434e-82c2-5232e64dc3b1] received celery_worker-1 | [2024-06-07 16:31:28,736: INFO/ForkPoolWorker-72] core.requests.celery_tasks.send_callback_task[7cdda9a2-ad10-434e-82c2-5232e64dc3b1]: {'msg': 'Callback sent!'} So I'm guessing these tasks … -
Nginx container is not able to connect to the other container for Django in the reverse proxy system
In my container for nginx output following error message. connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.10.1, server: localhost, request: "GET / HTTP/1.1", upstream: "http://192.168.10.2:8000/", host: "127.0.0.1" I want to solve this. In the docker-compose, there are three services; services: db: ...some descriptions... web: ...some descriptions... ports: - "8000:8000" depends_on: - db networks: - backend - frontend nginx: ...some descriptions... ports: - "80:80" depends_on: - web networks: - frontend ...some descriptions... networks: frontend: driver: bridge ipam: driver: default config: - subnet: 192.168.10.0/24 ...some descriptions... The "db" and "web" (Django) are connected. However, I can't build the connection beteween "web" and "nginx" through the "frontend" network. I have updated a configuration file "etc/nginx/nginx.conf", as shown below, and "nginx -t" command said these comments; nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful user nginx; worker_processes auto; error_log /var/log/nginx/error.log notice; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; upstream web { server web:8000; } server { listen 80; listen [::]:80; # … -
Delete data from cache using key prefix in Django
Am working with Django cache using Redis, these are sample of my cache keys determ_1ba243f3-2eda-4feb-bf24-1aa4c0cd2171 appr_hist_2bfd55e4-22c1-4cc3-a913-8ac2cde3801b appr_act_5a18c351-e172-4369-9a4b-118c3df5b25a but i get challenge when i want to delete cache using some part of key like determ_, appr_hist_, appr_act_ How will manage to accomplish this ? from django.core.cache import cache class CacheManager: @classmethod def delete_cache(self, prefixes = []): for pattern in prefixes: cache.delete(pattern) return True CacheManager.delete_cache(['determ_','appr_hist_', 'det_appr','appr_act_','deter_sect_'])