Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Virtual Environment SyntaxError
I just started learning about virtual environments and DJango on JetBrains Academy. The site told me to install DJango by creating a virtual environment first. I tried this in my IDLE Shell and this is the error I keep getting: python -m venv Classroom SyntaxError: invalid syntax python3 -m venv Classroom SyntaxError: invalid syntax Can anyone tell me how I can properly set up a virtual environment and install DJango? Thank you. -
Django docker could not access MYSQL in host server (using docker-compose)
I have a working django application run via docker to be used for production. Currently, its also using a mysql database which is also hosted using docker. This actually works fine. However, as what I learned, hosting mysql database on docker may not be a preferable way to do it in production. Which is why I wanted to use my host server, which has mysql running instead. My problem is, I can't seem to make it my django app connect to the host server's mysql server. This is my docker-compose file. version: '3.9' networks: default: external: true name: globalprint-shared-network services: #db: # image: mysql:5.7 # ports: # - "3307:3306" # hostname: globalprint-db # restart: always # volumes: # - production_db_volume:/var/lib/mysql # env_file: # - .env.prod app: build: context: . ports: - "8001:8000" volumes: - production_static_data:/vol/web hostname: globalprint-backend restart: always env_file: - .env.prod # depends_on: # - db proxy: build: context: ./proxy hostname: globalprint-backend-api volumes: - production_static_data:/vol/static restart: always ports: - "81:80" depends_on: - app volumes: production_static_data: production_db_volume: I actually have tried adding this in app service and made but still it did not work: extra_hosts: host.docker.internal:host-gateway My django settings for database is also this one. Its actually referencing to an … -
Use a variable with extends in Djano
I want to create a Django project with dynamic template (theme). I defined my active template name in setting.py like below. # GLOBAL VARIABLE FOR TEMPLATE ACTIVE_TEMPLATE = "presento" I want to use this variable my project. For example when I use this variable in extends I get an error like this. {% extends "frontend/{{ACTIVE_TEMPLATE}}/base/base.html" %} This is error. TemplateDoesNotExist at / frontend/{{ACTIVE_TEMPLATE}}/base/base.html What is your advice to solve this issue? -
Remove password field from django admin panel
I have implemented search and filtering for Post class in Django admin panel. Post class has no password filed but a password field appeared in admin panel. I want to remove it from admin panel. # admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.db import models from .models import Post, Comment class PostAdmin(UserAdmin): ordering = ('created_at',) list_display = ('author', 'blood_group', 'required_bags', 'contact_number', 'created_at', 'is_resolved', 'admin_approved') search_fields = ('author__name', 'blood_group', 'is_resolved',) # Can not add author as it is a foregin key to post readonly_fields = ('created_at',) exclude = ('password',) filter_horizontal = () list_filter = () fieldsets = () admin.site.register(Post, PostAdmin) admin.site.register(Comment) I have tried to remove the password field using exclude = ('password',) in admin.py of post app. It worked for my User model that actually had password field. But it is not working for Post model. Here is code for forms.py # forms.py from django.forms import ModelForm from .models import Post, Comment from django import forms class PostForm(ModelForm): class Meta: model = Post fields = ['description', 'address', 'blood_group', 'required_bags', 'deadlineDate', 'deadlineTime', 'contact_number', 'is_resolved'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name, field, in self.fields.items(): field.widget.attrs.update({'class' : 'form-control'}) self.fields['deadlineDate'].widget.input_type = 'date' self.fields['deadlineTime'].widget.input_type = 'time' self.fields['contact_number'].widget.input_type = 'number' … -
How to filter queryset by string field containing json (Django + SQLite)
I have the following situation. The Flight model (flights) has a field named 'airlines_codes' (TextField) in which I store data in JSON array like format: ["TB", "IR", "EP", "XX"] I need to filter the flights by 2-letter airline code (IATA format), for example 'XX', and I achieve this primitively but successfully like this: filtered_flights = Flight.objects.filter(airlines_codes__in='XX') This is great but actually not. I have flights where airlines_codes look like this: ["TBZ", "IR", "EP", "XXY"] Here there are 3-letter codes (ICAO format) and obviously the query filter above will not work. PS. I cannot move to PostgreSQL, also I cannot alter in anyway the database. This has to be achieved only by some query. Thanks for any idea. -
Cors problem with nginx/django from react app on docker
I have a question about cors implementation in django. Having a problem with setting the correct cors values. My deployment is on docker. I have a deployed 3 containers: backend: Django + DRF as backend (expose 8000 port) Nginx to server my backend (use exposed 8000 port and set it to 1338) frontend React app used with nginx (uses port 1337) Everything is on localhost. I use axios from frontend to call get/post requests. (I call to 1338 port then I think it is redirected to internal service on 8000 port) For backend I had to install django-cors-headers package to work with CORS. I think I set up it correctly. But there are scenarios where it does not work. In settings.py INSTALLED_APPS = [ ... "corsheaders", ] ... MIDDLEWARE = [ ... "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", ... ] First scenario In settings.py CORS_ALLOW_ALL_ORIGINS = True No get/post requests work. Get message: CORS Multiple Origin Not Allowed Second scenario In settings.py CORS_ALLOWED_ORIGINS = ["http://localhost:1337"] Works with get requests, but does not work with post requests. For post requests: options with error: CORS Missing Allow Header post with error: NS_ERROR_DOM_BAD_URI It works if I am not using nginx for backend. I am not sure … -
Why does the Stripe-Signature header never match the signature of request.body?
I'm using Python with Django and am trying to receive webhook events correctly from stripe. However I constantly get this error: stripe.error.SignatureVerificationError: No signatures found matching the expected signature for payload This is the code: WEBHOOK_SECRET = settings.STRIPE_WEBHOOK_SK @csrf_exempt def webhook(request): sig_header = request.headers.get('Stripe-Signature', None) payload = request.body try: event = stripe.Webhook.construct_event( payload=payload, sig_header=sig_header, secret=WEBHOOK_SECRET ) except ValueError as e: raise e except stripe.error.SignatureVerificationError as e: raise e return HttpResponse(status=200) I have also tried modifying the request body format like so: payload = request.body.decode('utf-8') # and also payload = json.loads(request.body) And yet no luck. The error is coming from the verify_header() class method inside the WebhookSignature class. This is the part of the method where it fails: if not any(util.secure_compare(expected_sig, s) for s in signatures): raise error.SignatureVerificationError( "No signatures found matching the expected signature for payload", header, payload, ) So I printed out exptected_sig and signatures before this line and found that regardless of what format request.body is in, signatures is always there (which is good), but they never match the signature from the header. Why is this? -
Adding input tools to a textarea
Am creating a blog website in Django where bloggers are not familiar with Markdown/Markup. So am planning to add these tools to my textarea.(image below). Please suggest an easy way to achieve this. -
Docker Django WhiteNoise, CSS are loaded but not visible
I have succesfuly created image of django, postgresql. I also used whitenoise to serve static files. They have loaded without problem. I see them in inspect mode, also via going directly to link of style 127.0.0.1:8000/static... It have worked without docker before. My problem is that even if they are loaded, no style is applied. Do you fellows have some ideas? Thanks for any help. -
Images not store in media folder but creating a folder and store
I am trying to upload some images in my app media folder. The problem is images uploaded successfully but not in media folder. Its creates another folder and store their. My code details are given bellow: urls.py from django.contrib import admin from django.urls import path from ssibdweb import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIAFILES_DIRS) settings.py MEDIA_DIR = BASE_DIR / 'media' MEDIA_URL = '/media/' MEDIAFILES_DIRS = [ STATIC_DIR, ] models.py class BlogImage(models.Model): id = models.AutoField(primary_key=True) sub_id = models.ForeignKey(Subject, on_delete=models.CASCADE) pic = models.ImageField(upload_to='blog/') def __str__(self): return str(self.id) I am using following form for upload <form method="POST" enctype="multipart/form-data" > -
Add crontab form in non-admin forms django
I want to add crontab schedule to a non admin form. I can see the registered jobs with crontab class Scheduler(ModelForm): class Meta: model = Scheduler fields = [ 'id', 'title', 'description', 'crontab' ] The problem here is I can't see the button to add a new schedule. How to add that can someone tell me. -
problem with updating counter with jquery inside loop with django
everything is working correctly, except when clicking the increment or decrement buttons, only the last product on the cart is updated!!!, for other carts, I can update the value manually and click the button it will updated without any problem !!! this is the code for .html in django {% for item in cart %} <div class="card rounded-3 mb-4 "> <div class="card-body p-4"> <div class="row d-flex justify-content-between align-items-center"> <div class="col-md-2 col-lg-2 col-xl-2"> <img src="{{ item.product.product_image.url }}" class="img-fluid rounded-3" alt="Cotton T-shirt"> </div> <div class="col-md-3 col-lg-3 col-xl-3"> <p class="lead fw-normal mb-2">{{ item.product.name }}</p> <p><span class="text-muted"> {% if item.product.is_service %} Service {% else %} Product {% endif %} </span> <span class="text-muted"> </div> <div class="col-md-3 col-lg-2 col-xl-2 d-flex product_data"> <input type="hidden" value="{{ item.product_id }}" class="prod_id"> {% csrf_token %} {% if item.product.is_service == False %} {% if item.product.quantity >= item.product_quantity %} <div class="container"> <div class="row"> <div class="col-lg-2"> <div class="input-group"> <span class="input-group-btn"> <button type="button" id="quantity-left-minus" class=" changeQuantity btn btn-primary btn-number" data-type="minus"> <span class="glyphicon glyphicon-minus"></span> </button> </span> <input type="number" id="quantity" class=" align-items-center qty-input" value="{{ item.product_quantity }}"> <span class="input-group-btn"> <button type="button" id="quantity-right-plus" class=" changeQuantity btn btn-primary btn-number" data-type="plus"> <span class="glyphicon glyphicon-plus"></span> </button> </span> </div> </div> </div> </div> {% else %} <h3>Out of Stock</h3> {% endif %} {% endif … -
Problem downloading full database in Django
First I used export_import to download the database but I only downloaded a single table at a time but I need to export the entire database to a file then import it back. Now I'm trying to fix it with another way I just saw using resources If you could help me to change it to a view instead of a function I would be grateful. Note: Thanks for the help. views.py from django.shortcuts import render from django.http import HttpResponse from .resources import CommentResource, CategoryResource # Create your views here. def export_data(request): if request.method == 'POST': # Get selected option from form file_format = request.POST['file-format'] comment_resource = CommentResource() dataset = comment_resource.export() print(type(CommentResource())) print(type(CategoryResource())) if file_format == 'CSV': response = HttpResponse(dataset.csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="exported_data.csv"' return response elif file_format == 'JSON': response = HttpResponse(dataset.json, content_type='application/json') response['Content-Disposition'] = 'attachment; filename="exported_data.json"' return response elif file_format == 'XLS (Excel)': response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="exported_data.xls"' return response return render(request, 'export_import_data_page.html') resources.py from import_export import resources from label.models import Comment, Category class CommentResource(resources.ModelResource): class Meta: model = Comment class CategoryResource(resources.ModelResource): class Meta: model = Category This is the html file to call the function to download the database export_import_data_page.html <!DOCTYPE html> <html> … -
How to remove "Select all" options from Django model admin
Django model admin allows to select all the objects in a page to take certain actions ('Delete selected' being one of them). After selecting all the model objects in a User model page, it gives an option to "Select all xxxx users" (xxxx being a number) as shown in the image. This allows the admin to select all the users and when exported to CSV, such a huge data size causes Gateway Timeout issue. We only want the admin to select the objects in a single page and not all of it in one go. Any help regarding this is appreciated. -
How to structure files in Django Rest Framework?
My requirement is the following: Create endpoints that will return various reports(json) representing organized data based on some specifications. Example: We have a car company with a lot of customers data. What I need to do is to generate reports which will contian month to month revenue from different categories of customers. Our project uses Django Rest Framework and the file structure is as the one below: mysite/ ├── manage.py │ ├── mysite/ │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py │ └── app1/ ├── api/v1/ │ └── serializer/ │ │ └── serializer_model1.py │ │ └── serializer_model2.py │ └── view/ │ │ └── view_model1.py │ │ └── view_model2.py │ └── permissions.py ├── migrations/ │ └── __init__.py ├── __init__.py ├── admin.py ├── apps.py ├── forms.py ├── signals.py ├── models.py ├── tests.py └── views.py // not used So, for "car" model we have one view and one serializer file inside api/v1/. My questions are: Is this structure ok? Where I should write those queries to generate data for the reports? (new app?, different view?) If I have snippets of code which are used on multiple views, where should I place that code so I can … -
Django Notification HQ - I installed the app manually but no signal is being sent
I have a django app and I wanted to install django-notification-hq (https://github.com/django-notifications/django-notifications) I wanted to modify some parts of the app so I downloaded the repo and install it. I first install it using the recommended approach in github (here below) and it all worked. $ git clone https://github.com/django-notifications/django-notifications $ cd django-notifications $ python setup.py sdist $ pip install dist/django-notifications-hq* However, I wanted to try a different way (also because I wanted to learn) and add the app like if had developed it entirely. So I removed everything I did I took the notifications folder inside django-notifications and added it directly to my project. I changed my project settings and add 'notifications.apps.Config', I updated my req.tx and installed necessary libraries Now, the project runs and nothing breaks....however, no notification is being generated. I followed as much as possible the code and noticed that it's the notify.send() that doesn't send anything. This makes me think that there is something about signals that I am not doing right? -
Django templates - sudden appearance of "" in my html
Has anyone discovered the sudden appearance of "&#xFEFF;" in their html? -
I want to be able to render a Django object on the HTML and have other Django objects manipulate the rendered HTML
I am building fan website for my portfolio for a popular MOBA game. What I want to happen is when you go to a champions detail page that shows the champions stats (attack damage, magic damage, etc), I want the user to be able to click on an item, and that items stats will add on the already rendered stat value. For example, Champion "x" has 25 base attack damage. Item "a" has 5 attack damage. Click on item "a" and the champion's stats will now show 30 attack damage. When double clicking the item it will remove the added 5 attack damage and now show 25 attack damage again. The clicking method and order is not mandatory but preferred because that was my initial draft and since I am learning I think I should force myself to deal with it. I was wondering if someone could point me in the right direction for using event listeners/what javascript or method would be the best way to do this, other than loading every single item into global variables in the script file. Code for reference. I have heard about AJAX but I don't want to dive into that into the moment … -
Getting same IP address for all my devices while getting the META data from the request
In my webapp I was getting the IP address of the user system and showing the same in the landing page. However for testing when I am making a request from all my devices at home I see same IP address(49.37.71.31). 2 questions Why is this happening How can I uniquely identify the machine which is making the request to my web app. index.html <div class="button add-list-button"> <a href="javascript:void(0)" class="btn">{{ ip }}</a> </div> views.py def index(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return render(request, 'index.html', context = {'ip':ip}) -
Tried to handle is_active=False accounts differently with simple jwt authetication but couldn't get it to work - Django Rest
I was trying to get a different error and handle the inActive accounts differently. I tried to use an answer from here https://github.com/jazzband/djangorestframework-simplejwt/issues/368 but I am still getting the same error 401 for inactive or is_active=False accounts. Below is my code custom serializer class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) # Add custom claims token['is_active'] = user.is_active token['is_teacher'] = user.is_teacher token['is_student'] = user.is_student token['is_superuser'] = user.is_superuser token['is_staff'] = user.is_staff return token def validate(self, attrs): data = super().validate(attrs) if not self.user.is_active: raise InActiveUser() token = self.get_token(self.user) data['refresh'] = str(token) data['access'] = str(token.access_token) if api_settings.UPDATE_LAST_LOGIN: update_last_login(None, self.user) return data custom view class CustomTokenObtainPairView(TokenObtainPairView): serializer_class = CustomTokenObtainPairSerializer def post(self, request, *args, **kwargs): print(f'\nCustomTokenObtainPairView is being called\n') serializer = self.get_serializer(data=request.data) try: serializer.is_valid(raise_exception=True) print(f'\nthis is the validated data {serializer.validated_data}\n') except AuthenticationFailed: print('is active exception raised') raise InActiveUser() except TokenError: print(f'token error raised') raise InvalidToken() return Response(serializer.validated_data, status=status.HTTP_200_OK) account/custom_authentication.py def custom_user_authentication_rule(user): print('custom authentication rule has been applied') return True if user is not None else False simple jwt settings in settings.py SIMPLE_JWT = { 'USER_AUTHENTICATION_RULE': 'account.custom_authentication.custom_user_authentication_rule', } Please suggest to me what should I do and correct me wherever I am wrong. -
How to create multiple dropdown of all my model
how to create an alphanumeric that picks first initial letter of model name and generate for every user that signup firstname = models.CharField(max_length=20) lastname = models.CharField(max_length=20) i want to create something like this firstname = Seung lastname = Jo this will be the alphanumeric generated = SJ000001 -
Page not found (404) Request Method: POST
I have stucked in this error for a few days can't able to find where the mistake is i tried my level best to clear the error but cant able to do it. views section from django.shortcuts import render,redirect from django.contrib.auth.models import User,auth # Create your views here. def register(request): if(request.method=='POST'): username=request.POST['username'] password1=request.POST['password1'] password2=request.POST['password2'] user=User.objects.create_user(username=username,password=password1) user.save(); print("user created") return redirect('/') else: return render(request,'registration.html') urls.py section from django.urls import path from . import views urlpatterns=[path('register/',views.register,name="register")] html section <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Registration</title> </head> <body> <form action="register" method="POST"> {% csrf_token %} USERNAME <input type="text" name="username" id=""> <br><br> PASSWORD <input type="password" name="password1" id=""> <br><br> RETYPE PASSWORD <input type="password" name="password2" id=""> <br><br> <input type="submit" value=""> </form> </body> </html> -
raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch in Django
I have this view that allows me to delete data. But the I keep getting the this error below whenever I click on the delete button. what I want to archive is when a user clicks the on GUARDAR, that model data should be deleted. But I keep getting the NoReverseMatch error bellow raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'book_delete' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<pk>[0-9]+)/delete/$'] View.py def book_delete(request, pk): envío = get_object_or_404(Control, pk=pk) data = dict() if request.method == 'POST': envío.delete() data['form_is_valid'] = True envíos = Control.objects.all().order_by('-fecha') data['html_book_list'] = render_to_string('includes/partial_envio_list.html', { 'envíos': envíos }) else: context = {'envío': envío} data['html_form'] = render_to_string('includes/partial_envío_delete.html', context, request=request) return JsonReson Model.py class Control(models.Model): control_id = models.AutoField(primary_key=True) cliente = models.ForeignKey(Cliente, null=True, blank=True, on_delete=models.CASCADE) familia = models.ForeignKey(Familia, null=True, blank=True, on_delete=models.CASCADE) estado = models.ForeignKey(Estado, null=True, blank=True, on_delete=models.CASCADE) fecha = models.DateField(blank=True, null=True) Fecha_desde = models.DateField(blank=True, null=True) Fecha_hasta = models.DateField(blank=True, null=True) control_id_hash = models.CharField(max_length=260, db_collation='utf8_unicode_ci') control_codigo = models.CharField(max_length=50, db_collation='utf8_unicode_ci') URL path('envío/<int:pk>/delete/', views.book_delete, name='book_delete'), template <form method="post" action="{% url 'agric:book_delete' control.pk %}" class="js-book-delete-form"> {% csrf_token %} <div class="modal-body"> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> <div class="modal-status bg-danger"></div> <div class="modal-body text-center py-4"> <h3>Are you sure?</h3> <p class="lead">Do you really want to delete envío <strong>{{ control.control_codigo }}</strong>?</p> </div> <div class="modal-footer" … -
How to update queryset field using some other dictionary in django
I have one dic and i want to update one field according to that dict. How to do that in django? -
Django ckeditor 5 upload images to Google Cloud Bucket
I am trying to use the package django-ckeditor-5 on my webapp. I am using django-storages with storages.backends.gcloud.GoogleCloudStorage backend. I have set these settings: CKEDITOR5_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' CKEDITOR_5_UPLOADS_FOLDER = 'uploads/' However, when I try to upload an image, I get this error: Internal Server Error: /ckeditor5/image_upload/ Traceback (most recent call last): File "/opt/homebrew/Caskroom/miniforge/base/envs/stokk/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/opt/homebrew/Caskroom/miniforge/base/envs/stokk/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/homebrew/Caskroom/miniforge/base/envs/stokk/lib/python3.9/site-packages/django_ckeditor_5/views.py", line 54, in upload_file url = handle_uploaded_file(request.FILES["upload"]) File "/opt/homebrew/Caskroom/miniforge/base/envs/stokk/lib/python3.9/site-packages/django_ckeditor_5/views.py", line 41, in handle_uploaded_file fs = storage(location=uploads_path) File "/opt/homebrew/Caskroom/miniforge/base/envs/stokk/lib/python3.9/site-packages/storages/backends/gcloud.py", line 97, in __init__ check_location(self) File "/opt/homebrew/Caskroom/miniforge/base/envs/stokk/lib/python3.9/site-packages/storages/utils.py", line 93, in check_location if storage.location.startswith('/'): AttributeError: 'PosixPath' object has no attribute 'startswith' [04/May/2022 15:00:20] "POST /ckeditor5/image_upload/ HTTP/1.1" 500 105904 Other relevant settings: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' django-ckeditor4 worked fine, so is it a question of supporting GCB storage or am I missing something in my settings?