Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Static files are not being loaded correctly in the browser when I access my site
Problem Description: I'm trying to set up a directory structure in my Django project where the static folder is inside the user folder, which is in turn inside the templates folder. My intention is to have static files located close to the template files. However, I'm having difficulties getting Django to properly serve static files from this directory structure. Directory Structure: project/ ├── templates/ │ └── user/ │ ├── index.html │ └── static/ │ └── css/ │ └── main.css └── ... Additional Details: I've configured STATIC_URL in settings.py: STATICFILES_DIRS = [os.path.join(BASE_DIR,'/templates/user/static/')] STATIC_URL = '/static/' In my index.html file, I'm using the <link rel="stylesheet" href="{% static 'css/main.css' %}"> tag to reference static files. Issue Faced: Despite adjusting the settings, I'm unable to make Django serve static files properly from this specific directory structure. I've tried different configurations, such as changing STATIC_URL, but I still haven't succeeded. Any help would be greatly appreciated. -
Wagtail always uses default site for URLs
I am using the Django site framework with wagtail. Wagtail correctly gives me the settings I specified for each site. I as of now have 2 sites registered: 127.0.0.1 172.1.16.155 So, when I visit 127.0.0.1, I get all the site settings for 127.0.0.1, and vice versa. The issue is, I have 172.1.16.155 as my default site. When I navigate to a URL from 127.0.0.1, (example: 127.0.0.1/home/) it will go to 172.1.16.1 (172.1.16.155/home/), and the same thing the other way around if I set the default site to the loopback addr. I have tried using both page.full_url and page.url, but to no avail. I have tried adding http://127.0.0.1 to the site settings (though I know this is incorrect), also to no avail. Some possibly relevant Django settings: # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env("SECRET_KEY",default="django-insecure-#=($lwdhz$drt5@h752_puh!y^5aqxh!bn($t_$^x(qd#1p5=e") DEBUG = str(env("DEBUG", default="False")).lower() in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh'] SECURE_CROSS_ORIGIN_OPENER_POLICY = None ALLOWED_HOSTS = env("DJANGO_ALLOWED_HOSTS",default="127.0.0.1 localhost").split(" ") CSRF_TRUSTED_ORIGINS = env("CSRF_TRUSTED_ORIGINS",default="http://127.0.0.1 http://localhost").split(" ") # Search # https://docs.wagtail.org/en/stable/topics/search/backends.html WAGTAILSEARCH_BACKENDS = { "default": { "BACKEND": "wagtail.search.backends.database", } } # Base URL to use when referring to full URLs within the Wagtail admin backend - # e.g. in notification … -
Isolating User Sessions for AWS Credentials in a Django-Kubernetes Web Application
I am currently developing a web application using Django that takes AWS credentials from the user and retrieves data from their specific AWS bucket. Each user has distinct AWS credentials and accesses different AWS buckets. The AWS credentials are used temporarily for the duration of the user session until logout. The application is set up such that it uses the AWS credentials to retrieve data through Python code, using these credentials for the duration of the session. The goal is to deploy this application on a Kubernetes cluster. Now, I am facing a scenario where multiple users could be accessing the application simultaneously. Here are the specifics: User 1 logs in to the application on Computer 1 using AWS Credentials 1. User 2 logs in to the application on Computer 2 using AWS Credentials 2. In the given scenario, it is crucial that User 1 only sees data from the AWS bucket associated with AWS Credentials 1, and User 2 only sees data from the AWS bucket associated with AWS Credentials 2. The data shown to one user should not be mixed up or reflected on the other user's screen, even upon page refreshes. My question is, how can I … -
I dont understand how to integrate mattermost API into the companies product
I am an intern at a company and I need to integrate the Mattermost chat API into my product. Its an angular application that uses graphql and django on the backend. I understand the basics of APIs but I dont know how to actually implement this so that people can chat with eachother on the website. I added a chat icon in the navigation bar. And I specified the API I wanted to use. But I am confused on how to move forward. I dont need a fully functioning feature that will be pushed to prod, its just a basic proof of concept. Its my first internship, im really scared and I dont want to disapoint. Any help is appreciated. -
UUID value as function argument - Uncaught SyntaxError
Good day dear Community! I have a simple JS function which takes an "id" as argument: <script> function deleteBl(id){ fetch('', { method: 'DELETE', headers: { 'X-CSRFToken': '{{ csrf_token }}' }, body: JSON.stringify({ 'id': id }), credentials: 'same-origin', }) } </script> and below Django template: {% for item in bl_query_set %} <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{ item.bl_number }}</td> <td class="text-center">{{ item.cargo_name }}</td> <td>{{ item.cargo_quantity }} {{ item.cargo_measurement }}</td> <td> <a onclick="deleteBl({{ item.id }})"> <i class="fas fa-trash-alt"></i> </a> </td> </tr> {% endfor %} and it works pretty well, there are no any console errors if I use default Id as primary key. But I need to use UUID as a primary key and in that case I get an error: "Uncaught SyntaxError: Invalid or unexpected token". See below screenshot please So, how I can resolve mentioned issue? Thanks for any help in advance! -
How can i make shuffle in django Forms?
I have got a project like quiz. But i need to shuffle the answers in questions. here is my code: template.html <form method="post"> {% csrf_token %} <h3>{{ current_question.text }}</h3> {{ form.selected_answer }} <button type="submit">Next</button> </form> views.py if request.method == 'POST': form = QuestionForm(request.POST, question=current_question) if form.is_valid(): user_answer = form.cleaned_data['selected_answer'] user_test.useranswer_set.update_or_create(question=current_question, defaults={'selected_answer': user_answer}) return redirect('test', test_id=test_id) else: form = QuestionForm(question=current_question) There is my django form. I try like this but it doesn't work: from django import forms from .models import Answer import random from django.db.models.query import QuerySet class QuestionForm(forms.Form): selected_answer = forms.ModelChoiceField( queryset=Answer.objects.none(), widget=forms.RadioSelect, empty_label=None ) def __init__(self, *args, question=None, **kwargs): super().__init__(*args, **kwargs) if question: answers = list(question.answer_set.all()) random.shuffle(answers) self.fields['selected_answer'].queryset = answers -
Got AttributeError when attempting to get a value for field 'field_name' on serializer `MySerializer`
I'm using django to create RESTApi with django-rest-framework. I've view that returns all subscriptions of student. In view, I should filter Subscriptions by company, and student and return it. But @api_view(['GET']) @permission_classes([permissions.ProfileLevelPermission]) def my_view(request, pk): try: company = models.Profile.objects.get( user=request.user, is_active=True).company except: return Response("Company is not found", status=status.HTTP_400_BAD_REQUEST) try: student = models.Student.objects.get( id=pk, company=company, status='1') except: return Response("Student is not found", status=status.HTTP_400_BAD_REQUEST) history = models.Subscription.objects.filter( student__id=student.pk, company__id=company.pk) data = serializers.SubscriptionSerializer(history).data return Response({"data": data}, status=status.HTTP_200_OK) And here is my 'serializer' class SubscriptionSerializer(ModelSerializer): class Meta: fields = ('__all__') model = models.Subscription And here is my models class Subscription(models.Model): STATUS_TYPES = ( ('0', "Permanently deleted"), ('1', "Active") ) cost = models.CharField(max_length=255) month = models.DateTimeField(default=timezone.now()) group = models.ForeignKey(Group, on_delete=models.PROTECT) student = models.ForeignKey(Student, on_delete=models.PROTECT) company = models.ForeignKey(Company, on_delete=models.CASCADE) status = models.CharField(choices=STATUS_TYPES, max_length=15) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.student.name If I send GET request, I'm getting this error I have no idea what kind of error I'm getting. -
django - get serializer output into another serializer
I want to get the output of one serializer 'RoomSerializer' into 'JoinRoomSerializer's fields. I have tried to get the 'RoomSerializer' as a variable into 'JoinRoomSerializer' and then pass it in 'fields', but im getting the following error: Got AttributeError when attempting to get a value for field room_extends on serializer JoinedRoomSerializer. The serializer field might be named incorrectly and not match any attribute or key on the UserRoom instance. Original exception text was: 'UserRoom' object has no attribute 'room_extends'. The Room model has field name and JoinRoom model has foreign key to room My serializers: class RoomSerializer(serializers.ModelSerializer): """Serializer for displaying all fields of the Room""" class Meta(): model = Room fields = ['name'] class JoinedRoomSerializer(serializers.ModelSerializer): """Serializer for displaying the following fields of the joined UserRoom table""" room_extends = RoomSerializer(many=True) class Meta(): model = UserRoom fields = ['room_extends', 'date_joined'] -
Django HttpResponse takes much CPU time
Django takes way too much CPU time to send response to localhost using the development server (same thing happens with gunicorn but a worker timeout occurs). The response size shouldn't be more than 15KB so the content size isn't the problem. I am using a virtual environment (venv) on Ubuntu 22.04. My code is the following: def time_series(request: HttpRequest) -> JsonResponse | HttpResponseBadRequest: """ This view returns a set of time series based on the user's query. Args: request (HttpRequest): The request object passed by django. Returns: JsonResponse | HttpResponseBadRequest: An object containing the time series or an error response. """ # Check this StackOverflow thread to see how group by works in Django: # https://stackoverflow.com/a/629691/11718554 if (patents := get_patents(request)) is None: return HttpResponseBadRequest("No patent query in the current session.") print(len(get_patent_ids(request))) applications_per_year = list( patents.values("application_year") .annotate(count=Count("id")) .order_by("application_year") .values("application_year", "count") ) granted_patents_per_year = list( patents.values("granted_year") .annotate(count=Count("id")) .order_by("granted_year") .values("granted_year", "count") ) granted_patents_per_type_year = list( patents.values("granted_year", "type") .annotate(count=Count("id")) .order_by("granted_year", "type") .values("granted_year", "type", "count") ) granted_patents_per_office_year = list( patents.values("granted_year", "office") .annotate(count=Count("id")) .order_by("granted_year", "office") .values("granted_year", "office", "count") ) pct_protected_patents_per_year = list( patents.filter(pct_data__granted=True) .values("granted_year") .annotate(count=Count("id")) .order_by("granted_year") .values("granted_year", "count") ) granted_patents_per_cpc_year = list( patents.annotate(cpc_section=Substr("cpc_groups__cpc_group", 1, 1)) .values("granted_year", "cpc_section") .annotate(count=Count("id")) .order_by("granted_year", "cpc_section") .values("granted_year", "cpc_section", "count") ) citations_made_per_year = … -
TailwindCSS grid-columns don't apply in Django Template
I'm using TailwindCSS in a Django template. I want to display all elements of a form in 3 columns, but somehow they all get displayed within one column. When I change to 2 columns, it works, but in all other n-columns (3, 4, 5, 6 ...) it doesn't. Anybody knows what the issue is here? Here's the template: <form method="get"> <div class="grid grid-cols-3 md:grid-cols-3 sm:grid-cols-3 lg:grid-cols-3 xl:grid-cols-3 2xl:grid-cols-3"> {% for elem in filter.form %} <div class="">123</div> {% endfor %} </div> <button type="submit">Go!</button> </form> -
Unable to create Google Meet Link in python with django
I'm trying to create a Google Meet event using the Google Calendar API in Python, but I'm encountering an HttpError. Here's the code I'm using to create the event: import logging import uuid from google.oauth2.service_account import Credentials as GoogleCredentials from googleapiclient.discovery import build from googleapiclient.errors import HttpError from courses.models import Teacher logger = logging.getLogger('google_calendar') def create_google_meet_event(teacher: Teacher, start_time, end_time, summary, description): # Retrieve the service account file path service_account_file_path = teacher.service_account_file.path # Use service account credentials credentials = GoogleCredentials.from_service_account_file(service_account_file_path, scopes=['https://www.googleapis.com/auth/calendar']) service = build('calendar', 'v3', credentials=credentials) event = { 'summary': summary, 'description': description, 'start': { 'dateTime': start_time.isoformat(), 'timeZone': 'UTC', }, 'end': { 'dateTime': end_time.isoformat(), 'timeZone': 'UTC', }, 'conferenceData': { 'createRequest': { 'requestId': uuid.uuid4().hex, 'conferenceSolutionKey': { 'type': 'hangoutsMeet' }, } } } try: # Insert the event into the teacher's calendar created_event = service.events().insert(calendarId='primary', conferenceDataVersion=1, body=event).execute() # Get the Google Meet link meet_link = created_event.get('hangoutLink') return meet_link except HttpError as error: # Handle the error as appropriate in your Django view logger.error(error) raise Exception(error) I have ensured that the service_account_file_path is correct, and the teacher object contains the correct credentials. Exception: <HttpError 400 when requesting https://www.googleapis.com/calendar/v3/calendars/primary/events?conferenceDataVersion=1&alt=json returned "Invalid conference type value.". Details: "[{'domain': 'global', 'reason': 'invalid', 'message': 'Invalid conference type value.'}]"> Ive … -
How to get a react page in my django backend to send it in mail
I have a backend server using Django framework and frontend using React.js I have a page that shows some statistics and wish to export this page in my backend so that I can send it in mail for recipients every interval (15 minutes, 30 minutes..). The page changes every minute so that I can't upload the page as pdf once in backend and use it later. I found that I can use headless browser to make a request to frontend to get the page but I have concerns about this appoach.. Or how heavy it is to add a headless browser in my backend server. And I don't want to recreate the page again in Django using templates because I won't be able to copy the design and also it is extra development time and duplicated code. I can see that those who use server side rendering can acheive this task easily while the page is renedered in backend.. that means they can use the page to send it in mail as pdf or to send it as a response to clients. I expect to have a good performance and wish to have some overview if this task already exist … -
How to get values with a different "path" in the database?
I want to get values from a table (the end goal is to create a dataframe out of a queryset). Those values depend on a form submitted by a user. Here is a simplified snippet of my models: class Report_Sample(models.Model): assay = models.CharField(max_length=50) samtools_data = models.ForeignKey( "Samtools_data", on_delete=models.DO_NOTHING, blank=True, null=True ) picard = models.ForeignKey( "Picard", on_delete=models.DO_NOTHING, blank=True, null=True class Samtools_data(models.Model): total_passed = models.IntegerField(null=True) total_failed = models.IntegerField(null=True) class Picard(models.Model): sample = models.CharField(max_length=10) library = models.CharField(max_length=10) read_group = models.CharField(max_length=10) picard_hs_metrics = models.ForeignKey( "Picard_hs_metrics", on_delete=models.DO_NOTHING, blank=True, null=True ) class Picard_hs_metrics(models.Model): bait_set = models.CharField(max_length=10) bait_territory = models.FloatField() Using the form, the user can select a subset of Report_sample objects and a metric to look at. So let's say the user wants the Samtools total_passed field. I can do: subset_report_samples = Report_sample.objects.filter(whatever_filter_the_user_wanted) metric_filter = None for model in apps.get_models(): for field in model._meta.get_fields(): if field.name == metric: metric_filter = f"{model.__name__.lower()}__{metric}" break subset_report_samples.objects.values(metric_filter) If we want to access the Picard_hs_metrics table however this breaks because of the intermediary table Picard. I thought about using a try/except block using from django.core.exceptions import FieldError but it feels horrible to use. So i was wondering if there was a Django method to find that metric_filter string given the field … -
How to create models for quiz application in django?
I'm working on a quiz app in django. I don't really know how to create the models for that. Basically, I need a quiz in sometimes questions are 'multiple choice', but sometimes they are 'short answer'. models.py class Quiz(models.Model): question = models.CharField(max_length=200) opt1 = models.CharField(max_length=100, null=True) opt2 = models.CharField(max_length=100, null=True) opt3 = models.CharField(max_length=100, null=True) opt4 = models.CharField(max_length=100, null=True) short_answer = models.CharField(max_length=100, null=True) def __str__(self): return self.question This is what I've already done. I don't know how will I understand if the current question is short answer or multiple choice. I think that if the short_answer field is empty, I can render the multiple choice. If it's not empty, I render short answer. Is it correct to do so? -
How to properly type client.post response in django test?
@pytest.mark.django_db def my_test( self, client, ): with monkeypatch_requests(resp_json={'values': []}): r: JsonResponse = client.post( self.endpoint, self.request_payload, content_type='application/json', ) assert r.status_code == 201, r.content assert r.json() == {'key': value} PyCharm is complainging Unresolved attribute reference 'json' for class 'JsonResponse', but I can use it. When I run the test in debugger and hover over json I can see functools.partial(<bound method ClientMixin._parse_json of <django.test.client.Client object at 0x7f3b81399d30>>, <JsonResponse status_code=201, "application/json">) -
Django what if the change is applied on database manually
I have short question. Let's assume in migration file I have some change that was already done manually on database level. Does migration will be applied without throwing an error? -
I can not find mod_wsgi model in Apache modules environment - Django
I am new to Django and I tried to connect it with Apache through mod_wsgi but it seems new versions of Apache does not support such kind of module. Am I right? Or is there any different way I could deploy my Django project in production? I saw on the official page I could use nginx. Any opinions? -
Django threaded / nested comments
What's the best way to implement threaded/nested comments in Django? I've read a bit about MPTT and django-threadedcomments but all the posts seem to be from years ago. Is using MPTT still the 'accepted' way or is there a newer way to do it? -
nowait or another method in Django admin page
I'm using Django and trying to find something similar to nowait=True in Django admin page. I have some script which locks entries(select for update) during working. So, when I try to change some fields values in Django admin page for that entry when its locked, admin page waits for unlocking that entry(in my case it could take minutes). I want to raise error(something like "database entry is locked") in admin page without waiting for unlocking. -
Django request.session.get() returns None across different view classes
I am working on a Django project and I'm encountering an issue with session variables. I set a session variable in one view, but when I try to access it in another view, it returns None. Here's a simplified version of my code: In my LoginVerification view: from rest_framework.views import APIView from rest_framework.response import Response class LoginVerification(APIView): def post(request): # ... login logic ... # If login is successful, I store the AWS access key in the session request.session['aws_access_key'] = 'your-access-key' return Response({"message": "Login successful"}) In my BucketSize view: from rest_framework.views import APIView from rest_framework.response import Response class BucketSize(APIView): def get(self, request): # Here, I try to retrieve the AWS access key from the session aws_access_key = request.session.get('aws_access_key') if aws_access_key is None: return Response({'status': 'error', 'error': 'No AWS access key found in session.'}) # ... remaining logic ... return Response({'status': 'success', 'bucketsize': bucketsize, 'unit': unit}) In the BucketSize view, request.session.get('aws_access_key') is always returning None, even though I have set it in the LoginVerification view. I have checked the following: The session variable is being set: The code in the LoginVerification view is running without errors. The session has not expired: I'm testing the BucketSize view immediately after the LoginVerification view. … -
for displayeding two digits id's
def project_list(request): project_details = Project.objects.all().exclude(status__gt=1) users_details = Users.objects.all().exclude(status__gt=1) return render(request, 'project/list.html', {"projects": project_details, "users": users_details}) this view {% for user_id in project.users %} {% for user in users %} {% if user.id|stringformat:"s" == user_id %} {{ user.first_name }}, {% endif %} {% endfor %} {% endfor %} not displayed having two digit's in id's in above pic u can see for name_2 ihave passed id 11 not displayed I need to get like this in above screen name_2 firstname_1 id is 7 and like that it need to display two digit id 11 name firstname_4 -
Template variable for email in Django allauth socialaccount signup
What template variable does the email field in the form in socialaccount /signup.html in Django allauth use? In the allauth/templates/socialaccount/signup.html there is this form: <form class="signup" id="signup_form" method="post" action="{% url 'socialaccount_signup' %}"> {% csrf_token %} {{ form.as_p }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button type="submit">{% trans "Sign Up" %} &raquo;</button> </form> To style the fields and delete labels I want to drop the form and use my own input fields. I can extract the tags inspecting the from in the browser but the value= from the email input field is already populated with my email address and I can't see the variable it uses. Can you help me with it? I tried to find it in the source code but i can't understand it. It seems that it renders the SocialAccount model in the form. I have tried from value="{{ email }}" to value="{{ socialaccount.get_social_account().user.get_email() }}" everything. -
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'accounts.User' that has not been installed
i'm getting these error in my code: raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'accounts.User' that has not been installed Why am i getting this Error?? I can't understand why it doesn't work i'm added AUTH_USER_MODEL = 'accounts.User' to settings models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser from .managers import UserManager from django.contrib.auth.mixins import PermissionRequiredMixin class User(AbstractBaseUser, PermissionRequiredMixin): email = models.EmailField(max_length=255, unique=True) phone_number = models.CharField(max_length=11, unique=True) full_name = models.CharField(max_length=100) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = ('email', 'full_name') # just for createsuperuser def __str__(self): return self.email @property def is_staff(self): return self.is_admin managers.py from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def create_user(self, phone_number, email, full_name, password): if not phone_number: raise ValueError('user most have phone number') if not email: raise ValueError('user most have email') if not full_name: raise ValueError('user most have full name') user = self.model(phone_number=phone_number, email=self.normalize_email(email), full_name=full_name) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone_number, email, full_name, password): user = self.create_user(phone_number, email, full_name, password) user.is_admin = True user.is_superuser = True user.save(using=self._db) return user forms.py from django import forms from .models import User from django.core.exceptions import ValidationError from django.contrib.auth.forms import ReadOnlyPasswordHashField class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput) class Meta: model … -
How to block Trinity.txt.bak calls in nginx
I am runnning some web servers using nginx as a proxy in front of django applications. Every now and then I see calls to https://*.[MY.DOMAIN]/nice%20ports,/Trinity.txt.bak being passed to Django which generates the exception "Invalid HTTP_HOST header". How can I block these kind of requests in nginx so they never reach Django? -
Django forget password in login page
We know in the Django login admin page you can just enter user/pass and log in to the admin panel. But is there any method to add the forget password option to this page? Or there is any package for it?