Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I recover the database on xampp mysql but store procedures were lost
I have an issue with XAMPP MySQL unable to start MySQL and access databases. I start MySQL and recover the database, but my stores procedures did not exist. where do they go? how do get them back. Thank you. I expect steps on how to fix this problem, queries or commands which shows the steps to get sored procedures back. -
How to do session-based authentication
For the backend of a project, we are combining FastAPI and Django. Why FastAPI? We need to use WebSockets and FastAPI supports that natively We like the Pydantic validation & auto-documentation it include Why Django? We want to make use of the builtin authentication & authorization (permissions) features We like to be able to use its ORM Why not Django-ninja? It does not support WebSockets Why not Django with Django Rest Framework for the API & with Channels for WebSockets? We prefer FastAPIs API features over DRF We like that FastAPI supports WebSockets natively We would like to authenticate & authorize the FastAPI endpoints based on the auth features that Django has (builtin User sessions & permissions). I'm struggling to find a good way of securing the FastAPI endpoints with the sessions from Django. In the code below you can see the current setup: main.py: FastAPI is set up here with (1) a router containing the FastAPI endpoints and (2) the Django application mounted router.py: Contains the FastAPI endpoints, I would like to make use of Django's builtin user sessions for authentication & authorization of the FastAPI endpoints. ## main.py (FastAPI) import os from django.conf import settings from django.core.asgi import … -
Django LoginRequiredMixin not redirecting to login page
I have a django e-commerce website and when I am trying to add a product without logging in, I am not being redirected to the login page. When I try to add a product without being logged in, on my terminal it says: [16/Jun/2024 07:18:26] "POST /cart/ HTTP/1.1" 302 0 [16/Jun/2024 07:18:26] "GET /login/?next=/cart/ HTTP/1.1" 200 134934 But I stay on the same page. Why is this not redirecting me to the login page? Thanks in advance! My views.py: def user_login_view(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') CustomUser = authenticate(request, username=username, password=password) if CustomUser is not None: login(request, CustomUser) messages.success(request, 'Login successful.') return redirect('home') else: messages.error(request, 'Invalid username or password.') return render(request, 'users/user_login.html') class CartView(LoginRequiredMixin, View): def get(self, request): cart_items = Cart.objects.filter(user=request.user) total_price = sum(item.product.price * item.quantity for item in cart_items) return render(request, 'business/cart.html', {'cart_items': cart_items, 'total_price': total_price}) @method_decorator(login_required) def post(self, request): try: data = json.loads(request.body) product_id = data.get('product_id') selected_variations = data.get('selected_variations', []) quantity = data.get('quantity', 1) # Get the quantity from the request logger.debug(f'Received product_id: {product_id} with variations: {selected_variations} with quantity {quantity}') except json.JSONDecodeError: logger.error("Invalid JSON data in the request body") return JsonResponse({'error': 'Invalid JSON data'}, status=400) if not product_id: logger.error("No product_id provided in the … -
How to get a value from radio buttons in Django form?
I have a HTML form. I need to get a value from radio button to pass it ti the model instance, but I'm getting a request without chosen radio button value, what's the problem? product.html <form action="{% url 'add_comment' %}" method="POST" class="addCommentForm" id="commentProductForm"> {% csrf_token %} <input type="text" name="comment_text" class="search-input" id="comment_text" placeholder="Введите отзыв..."> <div class="rating-area"> <label for="star-5" title="Оценка «5»"></label> <input type="radio" id="star-5" name="rating" value="5"> <label for="star-4" title="Оценка «4»"></label> <input type="radio" id="star-4" name="rating" value="4"> <label for="star-3" title="Оценка «3»"></label> <input type="radio" id="star-3" name="rating" value="3"> <label for="star-2" title="Оценка «2»"></label> <input type="radio" id="star-2" name="rating" value="2"> <label for="star-1" title="Оценка «1»"></label> <input type="radio" id="star-1" name="rating" value="1"> </div> <input type="hidden" name="product_id" value="{{ product.id }}"> <input type="submit" value="ОТПРАВИТЬ" class="search-btn"> </form> views.py def add_comment(request): if request.method == 'POST': ''' A request like b'comment_text=r&product_id=14395& csrfmiddlewaretoken=2inK4JGd1nqjS79p5Z6x78IupBqMOcNGGMuFJKW8zYIN2pzMlij4hyumV7G5k0H1' But without choosen radio button ''' print(f'\n{request.body}\n') text = request.POST.get('comment_text') product_id = request.POST.get('product_id') stars = request.POST.get('rating') # Here it shows None print(f'\n\nType: {type(stars)}\nValue: {stars}\n\n') if text == '': return JsonResponse({'success': False, 'message': 'Invalid data'}) profile = Profile.objects.get(user=request.user) product = Product.objects.get(id=product_id) Comment.objects.create(text=text, author=profile, product=product) return JsonResponse({'success': True, 'text': text, 'author': profile.first_name}) return JsonResponse({'success': False}) -
How do I update my code to have login and signup on the same page in django?
I want to have the login and sign up form on the same page, I also want to signup and login depending on which button was clicked. Here is my registration page enter image description here enter image description here and here is my views.py def register_view(request): if request.method == "POST": form = UserRegisterForm(request.POST or None) if form.is_valid(): new_user = form.save() username = form.cleaned_data.get("username") messages.success(request, f"Hey {username}, Your account was created successfuly") new_user = authenticate(username=form.cleaned_data['email'], password = form.cleaned_data['password1']) login(request, new_user) return redirect("core:index") else: print("User cannot be registered") form = UserRegisterForm() context = { 'form': form, } return render(request, "userauths/sign-up.html", context) def login_view(request): if request.user.is_authenticated: return redirect("core:index") if request.method == "POST": email = request.POST.get("email") password = request.POST.get("password") try: user = User.object.get(email=email) except: messages.warning(request, f"User with {email} does not exist") user = authenticate(request, email=email, password=password) if user is not None: login(request, user) messages.succes(request, "You are logged in") return redirect("core:index") else: messages.warning(request, "User does not exist. Create an account!!") context = { } return render(request, "userauths/sign-in.html", context) register.html <div class="login-form"> <form class="sign-in-htm" method="post" method="POST"> {% csrf_token%} <div class="group"> <label for="user" class="label">Email</label> <input id="user" type="text" class="input" required name="email"> </div> <div class="group"> <label for="pass" class="label">Password</label> <input id="pass" type="password" class="input" name="password" required data-type="password"> </div> <div class="group"> … -
No module named 'diabetes_proj'
I struck with problem when i was trying to deploy my Django project on Heroku infrastructure. I have this heroku logs --tails: 2024-06-15T18:37:26.503332+00:00 app[web.1]: return util.import_app(self.app_uri) 2024-06-15T18:37:26.503332+00:00 app[web.1]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2024-06-15T18:37:26.503333+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.12/site-packages/gunicorn/util.py", line 371, in import_app 2024-06-15T18:37:26.503333+00:00 app[web.1]: mod = importlib.import_module(module) 2024-06-15T18:37:26.503333+00:00 app[web.1]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2024-06-15T18:37:26.503333+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.12/importlib/_init_.py", line 90, in import_module 2024-06-15T18:37:26.503333+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2024-06-15T18:37:26.503334+00:00 app[web.1]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2024-06-15T18:37:26.503334+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1387, in _gcd_import 2024-06-15T18:37:26.503334+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1360, in _find_and_load 2024-06-15T18:37:26.503334+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1310, in _find_and_load_unlocked 2024-06-15T18:37:26.503334+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed 2024-06-15T18:37:26.503335+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1387, in _gcd_import 2024-06-15T18:37:26.503335+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1360, in _find_and_load 2024-06-15T18:37:26.503335+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1324, in _find_and_load_unlocked 2024-06-15T18:37:26.503335+00:00 app[web.1]: ModuleNotFoundError: No module named 'diabetes_proj' 2024-06-15T18:37:26.503390+00:00 app[web.1]: [2024-06-15 18:37:26 +0000] [9] [INFO] Worker exiting (pid: 9) 2024-06-15T18:37:26.523181+00:00 app[web.1]: [2024-06-15 18:37:26 +0000] [2] [ERROR] Worker (pid:9) exited with code 3 2024-06-15T18:37:26.523524+00:00 app[web.1]: [2024-06-15 18:37:26 +0000] [2] [ERROR] Shutting down: Master 2024-06-15T18:37:26.523543+00:00 app[web.1]: [2024-06-15 18:37:26 +0000] [2] [ERROR] Reason: Worker failed to boot. 2024-06-15T18:37:26.603484+00:00 heroku[web.1]: Process exited with status 3 2024-06-15T18:37:26.629365+00:00 heroku[web.1]: State changed from starting to crashed Heroku can't find my wsgi.py file. Here … -
504 Timeouts after setting django CSRF_TRUSTED_ORIGINS
I have a django 5.0 site deployed to elastic beanstalk with a domain and https through cloud front. When i make POST requests without the CSRF_TRUSTED_ORIGINS setting set, i get 403 errors. When i set the CSRF_TRUSTED_ORIGINS setting, i get 504 timeouts. I have tried SSH'ing into the box and running the POST directly against the django site-- it does the timeout there too. So it's definitely not AWS. Something with django. I've also tried downgrading to django 4-- didn't work either. Everything works perfectly locally. Any ideas? -
Replace Redis in a Django with Valkey
TLDR: Has anyone had experience replacing Redis with Valkey in their Docker compose for Django? I have a running Django instance that also uses Redis. Here I would like to replace Redis with Valkey. Currently I do not use Redis more than it is used by the standard processes of Django, but I became aware of it through the processes in Redis and their change of license. My question is whether I need to pay attention to anything special when switching and whether there are any known weaknesses or problems. Also in relation to a Docker Compose setting. -
Deploying Django project with Nginx, uWSGI and docker
I am trying to deploy and run a django application by using uWSGI, Nginx and docker on DigitalOcean. The Nginx and uWSGI works fine (I think) but I do not know why the uWSGI do not recieve any requests from Nginx. Here is my nginx configuration # upstream for uWSGI upstream uwsgi_app { server unix:/tmp/uwsgi/my_project.sock; } # upstream for Daphne upstream daphne { server unix:/tmp/uwsgi/my_project_daphne.sock; } server { listen 80; server_name www.domaine.com domaine.com; return 301 https://$host$request_uri; } server { listen 443 ssl; ssl_certificate /code/django_project/ssl/certs/cert.pem; ssl_certificate_key /code/django_project/ssl/certs/key.pem server_name www.domaine.com domaine.com; error_log stderr warn; access_log /dev/stdout main; location / { include /etc/nginx/uwsgi_params; uwsgi_pass uwsgi_app; } location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_pass http://daphne; } location /static/ { alias /code/django_project/staticfiles/; } location /media/ { alias /code/django_project/mediafiles/; } } my uWSGI file [uwsgi] socket = /tmp/uwsgi/my_project.sock chdir = /code/django_project/ module = django_project.wsgi:application master = true processes = 2 chmod-socket = 666 uid = www-data gid = www-data harakiri = 60 vacuum = true buffer-size = 32768 logger = file:/tmp/uwsgi.log log-maxsize = 200000 **My Dockerfile ** FROM python:3.11.5 ### 3. Set environment variables ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 RUN mkdir /code COPY . /code/ WORKDIR /code RUN … -
Not able to connect mysql with my django app inside docker
Refer https://github.com/sumitlohan/SocialNetworking repo for the code. Please check pipfile, dockerfile and docker-compose file to fix the issue. -
How to properly extend the Django default auth user model?
I created a CustomUser model which extends the django Abstract user now every user i create can neither log into the admin dashboard nor the app login page I tried even creating a Profile model which calls auth user model as a foreign key but it's quit tiresome and involves a lot of querying -
Processing process and UniqueConstraint Django
I did model with constraints: class DiscountSchema(models.Model): ... class Meta: verbose_name = "DiscountSchema" constraints = [ constraints.UniqueConstraint( fields=( "level", "level_value", "discount_rate", "background_col", "foreground_col", "loyalty_card", ), violation_error_message="UNIQUEERROR", name="Uniqueschema", ) ] How can I process this constraints when I create instance in serializer? Now I have: try: serializer.is_valid(raise_exception=True) return serializer.save() except IntegrityError as e: if "Uniqueschema" in e.args[0]: pass else: raise e Is there better way? -
How to design a separate authentication server using the ROPC OAuth2 flow?
I have to implement a separate authentication server using OAuth. The tech-stack that I am using is django and graphQL. As I am maintaining a separate server for authentication, I have created two django projects that run on two different ports, one for the authentication and the other as a resource server to perform CRUD operations on the user model. But since I have to authenticate the user using username and password and should issue access tokens, should I define the 'user' model in the project module which is dedicated for the authentication server? But if I am creating the 'user' model on the authentication server side, every time when the user requests for some information, my resource server needs to make a request to the authentication server to get that information. Is this a common practice? I have tried creating views in my authentication server, as in '/register' and '/verifytoken'. The resource server will place POST requests to these views using graphQL while registering the user and also while trying to access aa protecrted resource to verify the access token. But since I am using /register and /verifytoken routes, does it come under using REST API? If yes, how … -
Django models migration gives an error on a table that does not exist
I am making a project using Django with Django models (SQLite). I applied some changes to my models but when migrating it was giving me the following error: ValueError: Field 'id' expected a number but got 'FAL'. I commented out the changes and tried to re-migrate however despite I removed the changes it still gives me the same error. This is my models.py (including the commented out changes): from django.db import models from django.utils import timezone # Create your models here. # BOROUGHS = [ # ("GRE", "Greenwich"), # ("BEX", "Bexley"), # ("LEW", "Lewisham"), # ("HOM", "Homerton"), # ("OOB", "Out of borough") # ] # SPECIALITIES = [ # ("CAR", "Cardiology"), # ("COE", "Geriatric"), # ("PED", "Paediatric"), # ("ONC", "Oncology"), # ("ORT", "Orthopaedic"), # ("NEU", "Neurology"), # ("RES", "Respiratory") # ] # REASONS = [ # ("FAL", "Fall"), # ("NEU", "Neuro"), # ("GEN", "Generally unwell"), # ("MEH", "Mental health"), # ("ORT", "Orthopaedic"), # ("RES", "Respiratory") # ] # LOCATION = [ # ("HOM", "Home"), # ("WAR", "Ward"), # ("ICB", "Rehab unit"), # ("PLC", "Placement") # ] # class Doctor(models.Model): # name: models.CharField(max_length=50) # speciality: models.CharField(max_length=50, default="COE") # class AdmissionReason(models.Model): # reason: models.CharField(max_length=50, default="FAL") # class Borough(models.Model): # Borough: models.CharField(max_length=20, default="GRE") … -
Django context processor code not working
I am trying to use context_processors.py to show the number of unread_messages on my base.html message icon, but for some reason it is not working. While the unread_message counter is working for the user_messages_view properly, it just won't work for base.html. I tried changing the logic of my context_processors.py, but same result. So my models.py: class Message(models.Model): sender = models.ForeignKey(CustomUser, related_name='sent_messages', on_delete=models.CASCADE) recipient = models.ForeignKey(CustomUser, related_name='received_messages', on_delete=models.CASCADE) business = models.ForeignKey(Business, related_name='messages', on_delete=models.CASCADE, null=True) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) def __str__(self): return f'Message from {self.sender} to {self.recipient} in {self.business}' @property def sender_is_business(self): return self.sender.business.exists() @property def recipient_is_business(self): return self.recipient.business.exists() My views.py: @login_required def user_messages_view(request): businesses = Business.objects.filter( Q(messages__sender=request.user) | Q(messages__recipient=request.user) ).distinct() user_messages = [] latest_messages = [] for business in businesses: if request.user == business.seller: # Query messages for business with other users messages = Message.objects.filter( Q(sender=business.seller) | Q(recipient=business.seller) ).filter(business=business).order_by('-timestamp') for user, chat in itertools.groupby(messages, lambda m: m.recipient if m.sender == request.user else m.sender): last_message = next(chat) unread_count = Message.objects.filter(recipient=business.seller, sender=user, business=business, is_read=False).count() user_messages.append({ 'business': business, 'last_message': last_message, 'user': user, 'unread_count': unread_count, }) latest_messages.append(last_message) else: last_message = Message.objects.filter( Q(sender=request.user, recipient=business.seller) | Q(sender=business.seller, recipient=request.user) ).filter(business=business).order_by('-timestamp').first() unread_count = Message.objects.filter(recipient=request.user, sender=business.seller, is_read=False).count() user_messages.append({ 'business': business, 'last_message': last_message, 'unread_count': unread_count, }) … -
Django IntegrityError: How to handle ForeignKeyViolation in a delete view?
I’m facing an issue when trying to delete records in Django. I have a delete function for companies, but sometimes I encounter an IntegrityError if the company has related records in another table. I tried handling the IntegrityError, but it doesn’t help—the error occurs after the try-except block and results in a 500 error. Here’s my code: @login_required(login_url=reverse_lazy('autintification')) def delete_cp_company(request): db_name = LOCAL_DB if DEBUG else request.get_host().split(".")[0] cp_company_ids = json.loads(request.POST.get('cp_company_ids')) no_del = [] for ids in cp_company_ids: company = CP_company_for_pattern.objects.using(db_name).get(id=ids) print('id', ids) try: company.delete() except: no_del.append({ 'id': company.id, 'name': company.com_name, }) return JsonResponse(data={'no_delete': no_del}) Here’s the JavaScript that sends the delete request: function delete_cp_company() { let check_box = $('.cp_company_list_block .check_for_choose_item'); let ids_to_delete = []; for (let i = 0; i < check_box.length; i++) { if (check_box[i].checked) { let deleted_tr = $(check_box[i]).closest('tr'); let deleted_tr_id = deleted_tr.data("id"); ids_to_delete.push(deleted_tr_id); } } $.ajax({ url: "/delete_cp_company", method: "POST", data: { cp_company_ids: JSON.stringify(ids_to_delete), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), }, enctype: "multipart/form-data", dataType: 'json', success: function (data) { processCompanyDelete(ids_to_delete, data.no_delete) }, error: function (xhr, status, error) { console.error('AJAX Error: ' + status + ' - ' + error); }, }); } I tried handling the IntegrityError in the try-except block, but the error still causes a 500 response. I also … -
Django Form using fields from multiple models
I have the following in my models.py from django.db import models # Create your models here. class DPlaces(models.Model): restaurant = models.CharField(blank=False, unique=True, max_length=50) def __str__(self): return self.restaurant class DEntry(models.Model): place = models.ForeignKey(DPlaces, on_delete=models.CASCADE) e4date = models.DateField(blank=False) I have the following in my forms.py from django import forms from .models import DEntry, DPlaces class DEntryFilterForm(forms.Form): place = forms.ModelMultipleChoiceField( queryset=DPlaces.objects.all(), widget=forms.SelectMultiple(attrs={'class': 'form-control'}), required=False, ) e4date = forms.ModelMultipleChoiceField( queryset=DEntry.objects.order_by().values_list('e4date', flat=True).distinct(), widget=forms.SelectMultiple(attrs={'class': 'form-control'}), required=False, ) def __init__(self, *args, **kwargs): super(DEntryFilterForm, self).__init__(*args, **kwargs) self.fields['place'].queryset = DPlaces.objects.all() self.fields['e4date'].queryset = DEntry.objects.values_list('e4date', flat=True).distinct() in my views.py file I have def entrytable_view(request): data_entries = DEntry.objects.all() filtered_entries = None if request.method == 'GET': form = DEntryFilterForm(request.GET) if form.is_valid(): # Do Something The form works and form.is_valid returns true if a choice on 'place' field is selected but fails and form.is_valid returns false if a choice on 'e4date' field is selected. I suspect this is because the e4date field is not on the DPlaces model (it is on the DEntry model), but I am not sure. I any case, I am clueless on how to get this working. Any help is appreciated. -
How to manage multiple formset in Django with JavaScript
I have the following problem: I'm loading a form(Form A "Evento") for the User of application fill, in that Form I have to load dynamically another form(Form B "Logistica"), so that the User can add several Form B just clicking the button. I managed to load dynamically these Logistica/Form B for the User, but when I go to the saving part I only managed to receive the fields in a tuple, for example the Form B has a field called "nome", instead of receiving N FormB "nome" fields, I receive only 1 with a [] with the values of each Form. I realize that Django is thinking that instead of N FormB, I have only 1 FormB and it is concatenating the fields Problem https://github.com/ian-santos-nascimento/Django-event-management This is my form <form method="post" role="form" action="{% url 'evento_create' %}"> {% csrf_token %} <div class="form-group"> <label for="{{ form.nome.id_for_label }}">Nome</label> {{ form.nome }} </div> <div class="form-group"> <label for="{{ form.descricao.id_for_label }}">Descrição</label> {{ form.descricao }} </div> <div class="form-group"> <label for="{{ form.observacao.id_for_label }}">Observação</label> {{ form.observacao }} </div> <div class="row"> <div class="col"> <label for="{{ form.local.id_for_label }}">Local</label> {{ form.local }} </div> <div class="col"> <label for="{{ form.local.id_for_label }}">Cliente</label> {{ form.cliente }} </div> </div> <div class="form-group mt-3"> <label>Comidas</label> <div style="height: 30vh;overflow-y: scroll; … -
Simple JWT says sometimes "Token is invalid or expired" and sometimes gives correct output
I have a Django REST backend configured Simple-JWT solution. About 2/3 of the requests return # {"detail":"Given token not valid for any token type","code":"token_not_valid","messages":[{"token_class":"AccessToken","token_type":"access","message":"Token is invalid or expired"}]} and the rest returns the normal outcome. e.g. these curls I did directly one after another and the first fails while the second (same access token) returns a right value: C:\Users\user>curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzE4NDAxMzc5LCJpYXQiOjE3MTg0MDA0NzksImp0aSI6Ijc2YTcwZjU0OTA2ZjQwOTNhYzc2MzRhYTFmNmJjNTlhIiwidXNlcl9pZCI6Miwicm9sZSI6MSwibGFuZ3VhZ2UiOm51bGwsImZ1bGxfYWNjZXNzX2dyb3VwIjp0cnVlfQ.p8BRy95SSiBmqeSjmCkAHFddRjKmzEOowP2RT34Jp6Y" http://3.71.19.16/accounts/courses/ {"detail":"Given token not valid for any token type","code":"token_not_valid","messages":[{"token_class":"AccessToken","token_type":"access","message":"Token is invalid or expired"}]} C:\Users\user>curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzE4NDAxMzc5LCJpYXQiOjE3MTg0MDA0NzksImp0aSI6Ijc2YTcwZjU0OTA2ZjQwOTNhYzc2MzRhYTFmNmJjNTlhIiwidXNlcl9pZCI6Miwicm9sZSI6MSwibGFuZ3VhZ2UiOm51bGwsImZ1bGxfYWNjZXNzX2dyb3VwIjp0cnVlfQ.p8BRy95SSiBmqeSjmCkAHFddRjKmzEOowP2RT34Jp6Y" http://3.71.19.16/accounts/courses/ [{"id":1,"name":"Testkurs 1","language":1,"teacher":2,"grade":5,"start_date":null,"study_started":false,"activate_final_test":false,"number_of_students":90,"created_at":"2024-06-11T14:13:15.498484Z","scheduled_study_start":null,"scheduled_final_test":null,"demo":false},{"id":2,"name":"Testkurs 2","language":1,"teacher":2,"grade":5,"start_date":null,"study_started":false,"activate_final_test":false,"number_of_students":70,"created_at":"2024-06-11T14:17:58.503959Z","scheduled_study_start":null,"scheduled_final_test":null,"demo":false},{"id":3,"name":"Test","language":1,"teacher":2,"grade":5,"start_date":null,"study_started":false,"activate_final_test":false,"number_of_students":0,"created_at":"2024-06-13T22:35:51.513376Z","scheduled_study_start":null,"scheduled_final_test":null,"demo":false}] This is my Django Simple JWT-Setup: SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(minutes=15), "REFRESH_TOKEN_LIFETIME": timedelta(days=90), "ROTATE_REFRESH_TOKENS": True, "BLACKLIST_AFTER_ROTATION": True, "UPDATE_LAST_LOGIN": False, "ALGORITHM": "HS256", "VERIFYING_KEY": "", "AUDIENCE": None, "ISSUER": None, "JSON_ENCODER": None, "JWK_URL": None, "LEEWAY": 60, "AUTH_HEADER_TYPES": ("Bearer",), "AUTH_HEADER_NAME": "HTTP_AUTHORIZATION", "USER_ID_FIELD": "id", "USER_ID_CLAIM": "user_id", "USER_AUTHENTICATION_RULE": "rest_framework_simplejwt.authentication.default_user_authentication_rule", "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",), "TOKEN_TYPE_CLAIM": "token_type", "TOKEN_USER_CLASS": "rest_framework_simplejwt.models.TokenUser", "JTI_CLAIM": "jti", "SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp", "SLIDING_TOKEN_LIFETIME": timedelta(minutes=15), "SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1), "TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainPairSerializer", "TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSerializer", "TOKEN_VERIFY_SERIALIZER": "rest_framework_simplejwt.serializers.TokenVerifySerializer", "TOKEN_BLACKLIST_SERIALIZER": "rest_framework_simplejwt.serializers.TokenBlacklistSerializer", "SLIDING_TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainSlidingSerializer", "SLIDING_TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSlidingSerializer", } and my nginx config server { listen 80; server_name 127.0.0.1; # change with url location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/ubuntu/USER/static/; } location / { # Add the necessary headers proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For … -
Django App Embedded in Shopify not setting CSRF token
We are facing a bit of an issue with CSRF tokens in our application. Our Django application is embedded in Shopify. I know browsers are getting a bit strict on the third-party cookies but haven't been able to find a solution to setting the CSRF token it the browser. For now, we are forced to comment out 'django.middleware.csrf.CsrfViewMiddleware', in settings.py, which I don't believe is the correct way to go. In my settings.py: CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True ALLOWED_HOSTS = [ "admin.shopify.com", "www.mydomain.com", ] CSRF_TRUSTED_ORIGINS = [ "admin.shopify.com", "www.mydomain.com", ] ... MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... # Session settings SESSION_ENGINE = 'django.contrib.sessions.backends.db' SESSION_COOKIE_NAME = 'sessionid' SESSION_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = None SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_AGE = 1209600 SESSION_EXPIRE_AT_BROWSER_CLOSE = False SESSION_SAVE_EVERY_REQUEST = True CSRF_COOKIE_NAME = 'csrftoken' CSRF_COOKIE_SECURE = True CSRF_COOKIE_SAMESITE = None Then, in my JavaScript I have the following code to set the CSRF cookie: // CSRF Token function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { … -
Django Error: config() takes 0 positional arguments but 1 was given
Why am I seeing this error? I have placed my SECRET_KEY in an .env file and I reference it using config from decouple in settings.py. Isn't it necessary to list the argument 'SECRET_KEY' inside config() in order for the program to access my secret key from the .env file? (I did activate the virtual environment). See below. Django Project Folder Structure: I created the .env file in the same app folder that contains the settings.py file. from settings.py: from decouple import config SECRET_KEY = config('SECRET_KEY') from .env: SECRET_KEY='epluribusunum' -
ValueError when i migrate in my Django project
I'm trying to make a music streaming website using Django. I have this error when i use the terminal command "migrate": "ValueError: Field 'song_id' expected a number but got '' ". I don't understand where "song_id" take a value that is not a number. How can i fix it and what is the code line with the problem? this is my views.py: def myPlaylist(request, id): user = request.user if user.is_authenticated: # Extracting Playlists of the Authenticated User myPlaylists = list(Playlist.objects.filter(user=user)) if user.is_authenticated: if request.method == "POST": song_id = request.POST["music_id"] playlist = Playlist.objects.filter(playlist_id=id).first() if song_id in playlist.music_ids: playlist.music_ids.remove(song_id) playlist.plays -= 1 playlist.save() message = "Successfull" print(message) return HttpResponse(json.dumps({'message': message})) else: images = os.listdir("music_app/static/PlaylistImages") print(images) randomImagePath = random.choice(images) randomImagePath = "PlaylistImages/" + randomImagePath print(randomImagePath) currPlaylist = Playlist.objects.filter(playlist_id=id).first() music_ids = currPlaylist.music_ids playlistSongs = [] recommendedSingers = [] for music_id in music_ids: song = Song.objects.filter(song_id=music_id).first() random.shuffle(recommendedSingers) recommendedSingers = list(set(recommendedSingers))[:6] playlistSongs.append(song) return render(request, "myPlaylist.html", {'playlistInfo': currPlaylist, 'playlistSongs': playlistSongs, 'myPlaylists': myPlaylists, 'recommendedSingers': recommendedSingers, 'randomImagePath': randomImagePath}) def addSongToPlaylist(request): user = request.user if user.is_authenticated: try: data = request.POST['data'] ids = data.split("|") song_id = ids[0][2:] playlist_id = ids[1][2:] print(ids[0][2:], ids[1][2:]) currPlaylist = Playlist.objects.filter(playlist_id=playlist_id).first() if song_id not in currPlaylist.music_ids: currPlaylist.music_ids.append(song_id) currPlaylist.plays = len(currPlaylist.music_ids) currPlaylist.save() return HttpResponse("Successfull") except: return redirect("/") # … -
How to unify the result of three queries into one keeping the order given by order by in Django
I am trying to get a list from a model to show the results ordered by status, for example: first "active", then "in progress" and "not active" at the bottom of the list. At the same time the results for each status must be ordered by the date. I am using Django version 4.0 and MySQL database. I tried to implement this using Union, but the results are not being ordered correctly. Here is the Model code: class LegalDocument(CreateAndUpdateDatesModel): class DocumentStatus(models.TextChoices): ACTIVE = 'Activo', 'Activo' EXPIRED = 'Vencido', 'Vencido' EVALUATING = 'Evaluación', 'Evaluación' REJECTED = 'Rescindido', 'Rescindido' RESOLVED = 'Resuelto', 'Resuelto' class DocumentType(models.TextChoices): CONTRACT = 'Contrato', 'Contrato' AGREEMENT = 'Convenio', 'Convenio' MEMORANDUM = 'Memorándum', 'Memorándum' ADDENDUM = 'Enmienda', 'Enmienda' LETTER = 'Carta', 'Carta' OTHER = 'Otro', 'Otro' document_number = models.CharField(max_length=100, unique=True) title = models.CharField(max_length=100) description = RichTextUploadingField() status = models.CharField(max_length=100, choices=DocumentStatus.choices, default=DocumentStatus.ACTIVE) expiration_date = models.DateField(null=True, blank=True) And here is how I am implenting the query with union: legal_documents = LegalDocument.objects.all() active_documents = legal_documents.filter(status=LegalDocument.DocumentStatus.ACTIVE).order_by('expiration_date') evaluating_document = legal_documents.filter(status=LegalDocument.DocumentStatus.EVALUATING).order_by('expiration_date') expired_documents = legal_documents.filter(status=LegalDocument.DocumentStatus.EXPIRED).order_by('expiration_date') rejected_documents = legal_documents.filter(status=LegalDocument.DocumentStatus.REJECTED).order_by('expiration_date') resolved_documents = legal_documents.filter(status=LegalDocument.DocumentStatus.RESOLVED).order_by('expiration_date') legal_documents = active_documents.union(evaluating_document, expired_documents, rejected_documents, resolved_documents, all=True) The result I am getting, please pay attention to "Expiration Date" column (dates are in format %Y-%m-%d): Title … -
How to use Django generated fields to get a single value from a many-to-many relationship?
I have a Django model representing a Book, which can have many different types of Person, including AUTHOR, EDITOR, ILLUSTRATOR, etc. class PersonType(models.Model): name = models.CharField() class Person(models.Model): name = models.TextField() class Book(models.Model): title = models.TextField() people = models.ManyToManyField(Person, through="PersonBook") class PersonBook(models.Model): person_type = models.ForeignKey(PersonType, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) book = models.ForeignKey(Book, on_delete=models.CASCADE) I was hoping to use Django's new GeneratedFields to create a property on Book with the name author that could query the many to many relationship and set the value equal to the first Person with the "AUTHOR" PersonType. I'm certain there are other ways of doing this with Managers and what not, but I'm curious as to how I can do this with Django's new GeneratedFields, if that's even possible. The documentation on Django's Query expressions doesn't show any examples along relationships, so I'm not sure if it's possible to do anything there. -
nginx dont redirect to my django app after using gunnicorn in production
I have a django app, running with docker, that i want to deploy with self-hosting. When i do python manage.py runserver 0.0.0.0:8000 i can do a curl 127.0.0.1:8000/api/endpoint and see that it get redirected to the app, but when i use gunicorn on the same port and ip the request never gets redirected to the app. I dont see whats the diffrence could be as i map to 0.0.0.0:8000 both places? upstream app_upstream { # 'app' is the name of the server from the container that is going to be used. With port 8000 server app:8000; } server { # Should respond to in localhost and listen to 8000 server_name localhost; listen 8000; location / { proxy_pass http://app_upstream; # This is the name of the upstream server that we defined above proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } #test Entrypoint script gunicorn --bind 0.0.0.0:8000 app.wsgi docker-compose --- services: nginx: image: "nginx:latest" volumes: - "./nginx/:/etc/nginx/conf.d/" ports: - "8000:8000" networks: - webnet depends_on: - app app: build: context: . dockerfile: Dockerfile # Uncommented block # build: # context: . # image: soma1337/cryptobackend:latest volumes: - ".:/app" env_file: - "env-$RTE" depends_on: - db networks: - dbnet - webnet db: image: "postgres:13-alpine" …