Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker can't access django localhost
I have Django 3.2.18 installed and it works perfectly fine. the problem starts when I want to start a django project and use docker containers. my Dockerfile content is like this: FROM python:3.9.13 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /app COPY requirements.txt /app/ RUN pip3 install --upgrade pip RUN pip3 install -r requirements.txt COPY ./core /app CMD ["python","manage.py", "runserver", "0.0.0.0:8000"] I run docker build -t django . and it builds the project fine! it also runs perfect. but the moment I enter https://0.0.0.0:8000 in my browser it fails. Insted of django debug first page (The page with a rocket), it shows me This site can’t be reached as if it can't access my localhost. At first I thought it was my windows build version that was the problem, but I've upgraded my windows and still no defrence! I have searched the Internet and no one seeem to had this problem before. Changed my OS version. Deleted and re-created my django project. I'm expecting to see django first page on https://0.0.0.0:8000 -
Django ORM distinct over annotated value
I have a model which has a DateTimeField timestamp. What would be the best way to see the number of entries for each day (month, hours etc.) just by using Django ORM (not raw SQL)? -
Doesn't translate the page in Django
settings.py: USE_I18N = True USE_L10N = True LANGUAGES = [ ('en', 'English'), ('ru', 'Русский'), ] LANGUAGE_CODE = 'ru' urls.py: """djangokurs URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.urls import path, include from django.conf.urls.i18n import i18n_patterns urlpatterns = [ path('admin/', admin.site.urls), path('orders/', include('orders.urls')), path('', include('products.urls')), path('accounts/', include('accounts.urls')), path('basket/', include('baskets.urls')), ] urlpatterns = i18n_patterns( *urlpatterns, path('i18n/', include('django.conf.urls.i18n')), ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I also created locale/en/LC_MESSAGES/django.mo and used {% trans "text" %} tags. But language is not changed. In console in my browser "locale changed ru" with source "content.js.:678" I try to write activate('en') print("Current language:", get_language()) But nothing will change. I also switched urls from ru to en, but it did not help either. -
How to pass multiple parameters in Django URL? [duplicate]
I am working on a website that deals with the NFL. The user would start on the Seasons page with a URL of: '/season'. They then select a season which brings them to the weeks page which displays all weeks of that season with an example URL of '/season/2022/week'. They can select a week and it will display all the games in that week. The URL would look like '/season/2022/week/5/games'. Is a URL like this possible? Also, how would I get those parameters (2022, 5) into views.py in order to filter the queryset? I have tried this and have been unsuccessful on getting this to work. I know there are other possible solutions but this URL looks clean and descriptive to me. -
Django ORM annotate query with length of JSONField array contents
I have a basic Model with a JSONField that defaults to a list: class Map(models.Model): id = models.UUIDField( primary_key=True, editable=False, default=uuid.uuid4, ) locations = models.JSONField( default=list, blank=True, encoder=serializers.json.DjangoJSONEncoder ) In my admin list view I'd like a column displaying the length of locations. That is, annotate the queryset to do the equivalent of len(obj.locations) but I haven't found any examples of this scenario. I know I could write an accessor for the admin class that does len(obj.locations) to add the column/values but I'd also like to sort/order by this field's value. -
in django i keep getting this ModuleNotFoundError: No module named receipts. everything else seems to be running fine
i forked and cloned a gitlab repository. and it included a bunch of tests you can run in terminal. All the test's pass except for test_feature_08.py im not sure what else to do right now to get it to pass vscode directory layout receipts.views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from receipts.models import Receipt @login_required def receipt_list(request): receipts = Receipt.objects.filter(purchaser=request.user) context = { "receipts": receipts, } return render(request, "receipts/list.html", context) receipts.urls.py from django.urls import path from receipts.views import receipt_list urlpatterns = [ path("", receipt_list, name="home"), ] expenses.urls.py from django.contrib import admin from django.urls import include, path from django.shortcuts import redirect def return_home(request): return redirect("home") urlpatterns = [ path("", return_home), path("admin/", admin.site.urls), path("receipts/", include("receipts.urls")), path("accounts/", include("accounts.urls")), ] Traceback (most recent call last): File "/Users/tommyg/django-two-shot/receipts/views.py", line 3, in <module> from receipts.models import Receipt ModuleNotFoundError: No module named 'receipts' -
React Front end, Django back-end, Braintree API CORS error
Hello I've been struggling with this issue for days now, I have built an app in react, the backend is using django and DRF, and I'm using braintree as payment platform, I'm trying to POST a form from react to django but in react I'm getting the error saying fetch fails because it was blocked by CORS, in django I get an error 400 saying bad request, and the request type is OPTIONS, I did some troubleshoot and turns out the form is been sent empty(I was reading about OPTIONS and it seems if the server does not allow the request then it turns into an empty array). I have added django-cors-headers to apps installed, middleware, allowed hosts, etc.. anyway, here's my code. DebitCard.js import { useState, useEffect } from 'react'; import axios from 'axios'; import * as braintree from 'braintree-web' function DebitCard() { const storedData = localStorage.getItem('donationData'); const formData = storedData ? JSON.parse(storedData) : null; const [clientToken, setClientToken] = useState(null); const [client, setClient] = useState(null); const [hostedFieldsInstance, setHostedFieldsInstance] = useState(null) useEffect(() => { async function fetchClientToken() { try { const response = await fetch('http://127.0.0.1:3001/client-token/'); const jsonResponse = await response.json(); const clientToken = jsonResponse.client_token; setClientToken(clientToken); } catch (err) { console.error('Failed … -
How to create a TimescaleDB Hypertable from Django models?
By defining a Django model, you can't create a hypertable in TimescaleDB, I got an error like: Cannot create a unique index without using the partitioning key with the following (example) model: class Record(models.Model): class State(models.Choices): ONLINE = "online" OFFLINE = "offline" time = models.DateTimeField() mode = models.CharField(max_length=10, choices=Mode.choices) state = models.CharField(max_length=10, choices=State.choices) Does anyone know how can I fix this? -
Background-image does not load CSS, DJANGO
I am trying to load this image from css but the image does not display, the css is in /static/css/styles.css and the image is in /static/imagenes/proyecto1.jpg .Project:first-child{ background-image: url('../imagenes/proyecto1.jpg') ; background-repeat: no-repeat; background-size: cover; } I want to get the image to be able to be displayed, here is the html and css * { box-sizing: border-box; } body { margin: 0; font-family: 'Proxima Nova', sans-serif; padding: 0 ; background-color: rgb(245, 245, 245); } h1{ font-size: 2.5em; color: #f9cccc; margin: 0; } h2 {font-size: 2em;} h3 {font-size: 2em} p {font-size: 1em;} input { width: 20em; border-radius: 1px; border: 2px solid #000000; font-size: 1em; } textarea{ width: 25em; height: 10em; font-size: 1em; } button { font-size: 1.25em; font-weight: bold; padding: 5px 15px; background-color: #f9cccc; border-radius: 5px; border: 2px solid #000000; box-shadow: 2px 2px 10px #000000; } button:hover{ background-color: #FF69B4 } .color-acento{color: #d1553f;} img{ max-width: 100%; } .toggle-menu{ position: absolute; top: .5rem; right: 1rem; cursor: pointer; width: 40px; z-index: 1; } @media screen and (min-width: 768px) { .toggle-menu { display: none; } } .main-menu{ list-style: none; margin-top: 0; margin-bottom: 0; padding-left: 0; display: flex; flex-direction: column; align-items: center; transition: transform 0.3s ; transform: translateY(-100%); } .main-menu--show{ transform: translateY(0); } .toggle-menu__checkbox{ display: none; … -
Python Mailchimp Transactional payload not being recognized by mailchimp template
I am using the MailchimpTransactional package to send an email with a dynamic body, and mailchimp is rendering the subject, from, to and other field correctly. However; the variables in the actual body of the template are not being populated in the mailchimp email. Below is my payload I am sending. Nothing in the template_content key is being used in the template: Template code: <header></header> *|HTML:BODY|* <footer></footer> Payload: mailchimp = MailchimpTransactional.Client(MAILCHIMP_KEY) message = { 'template_name': 'general-template', 'merge_language': 'mailchimp', 'template_content': [{ 'name': 'BODY', 'content': '<h1>HEY LISTEN!</h1>' }], 'message': { 'to': [{ 'email': 'test1@example.com', 'type': 'to' }, { 'email': 'test@example.com', 'type': 'cc' }], 'subject': 'Test Subject', 'attachments': [], 'from_email': 'no-reply@test.com', 'from_name': None, 'headers': { 'Reply-To': '{}' } } } mailchimp.messages.send_template(message) The email sends just find, however, all the email returns is below: What am I doing wrong? -
DJANGO - python manage.py migrate - ERROR: django.db.utils.OperationalError: (1054, "Unknown column in 'field list'")
I have changed the default database in Django project to database, which I have created in MySQL Workbench, which contains tables and relationships between them. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'data_storage', 'USER': 'root', 'PASSWORD': 'my_password', 'HOST': 'localhost', 'PORT': '3306', } } I am following the instructions in: https://rafed.github.io/devra/posts/database/how-to-connect-django-to-existing-database/ Running python manage.py inspectdb > my_app/models.py generated models successfully. After I run cmdlet python manage.py migrate, I get error: django.db.utils.OperationalError: (1054, "Unknown column 'auth_permission.content_type_id' in 'field list'") FULL PROMPT: (.venv) PS C:\Users\Prakse\Desktop\DjangoApp> python manage.py migrate Operations to perform: Apply all migrations: DjangoWebPage, admin, auth, contenttypes, sessions Running migrations: No migrations to apply. Traceback (most recent call last): File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\django\db\backends\mysql\base.py", line 75, in execute return self.cursor.execute(query, args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\pymysql\cursors.py", line 158, in execute result = self._query(query) ^^^^^^^^^^^^^^^^^^ File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\pymysql\cursors.py", line 325, in _query conn.query(q) File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\pymysql\connections.py", line 549, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\pymysql\connections.py", line 779, in _read_query_result result.read() File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\pymysql\connections.py", line 1157, in read first_packet = self.connection._read_packet() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\pymysql\connections.py", line 729, in _read_packet packet.raise_for_error() File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error err.raise_mysql_exception(self._data) File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.OperationalError: (1054, "Unknown column … -
"set_password" in Django is not hashing my password properly
So I'm building a user model in Django but when I test it in my server, the passwords are saved as it is written, which means the system breaks when I try to make a login since the password is not hashed. Here's my create user function: def create_user(self, email, password, **extra_fields): """ Create and save a user with the given email and password. """ if not email: raise ValueError(_("The Email must be set")) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user I already tried with make_password which is one of the functions that django hashers has but still no luck. What am i doing wrong? -
I can't get a queryset from GenericForeignKey
How to fix this error FieldError at /movies/ Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. This is a class for getting user activity by queryset from typing import Dict, Any from django.db.models.base import ModelBase from django.db.models.query import QuerySet from specifications.serializers import ActivitySerializer class UserActivity(object): def __init__(self, user) -> None: self.user = user def get_activity(self, model: ModelBase, query: QuerySet) -> Dict[str, Any]|None: if model._meta.model_name == "comment": objects = model.objects.filter(user=self.user, comment__in=query) serializer = ActivitySerializer(objects, many=True) else: objects = model.objects.filter( user=self.user, content_object__in=query ) serializer = ActivitySerializer(objects, many=True) return serializer.data I have a view for getting movies class MovieListView(APIView): def get(self, request): movies = Movie.objects.all() paginator = PageNumberPagination() paginator.page_size = 10 page = paginator.paginate_queryset(movies, request) serializer = MovieListSerializer(page, many=True) user_activity = UserActivity(request.user) data = { "movies": serializer.data, } if request.user.is_authenticated: user_activity = UserActivity(request.user) activity = { "user": { "ratings": user_activity.get_activity(Rating, page), "watchlist": user_activity.get_activity(WatchList, page) } } data.update(activity) response = Response(data) response['X-Total-Count'] = paginator.page.paginator.count response['X-Page-Size'] = paginator.page_size response['X-Page'] = paginator.page.number return response I have 2 models (movie, rating) class Movie(models.Model): ... comments = GenericRelation(Comment) ratings = GenericRelation(Rating) watchlist = GenericRelation(WatchList) class Rating(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, … -
Azure web app hosting React frontend & Python Django Backend Issues
I am attempting to host this website on Azure on behalf of my team, I have had issues. The current issue has me stumped; Azure says the website is hosted & is running. I can see that Azure is hosting it, but when I go to the website, there is nothing there. I do not know if I need to have something on our end connect to the link azure provides us, the website can run locally, as when we run it, it will host on localhost, and we can navigate it and the locally hosted database. When I attempt to run the website, on azure it says that it is running, but if I go to the link azure provides, it is the default azure website. Here is the GitHub if you want to take a look, any pointers or potential fixes would be greatly appreciated. I'll be more than happy to elaborate on any information anyone needs. -
Django_tables2 only shows the default table
So, I am creating a small app where I need to show an HTML table from the database entries. So I am using Django and the best solution for it was Django_tables2. And for the default setting, where all the fields from the model are being displayed it works ok. But I needed to add another column for a button and that's when I ran into a problem. I cannot add/delete a column or anything in the table. The changes I make in the Table class are rejected and the default settings are being still used. I tried removing the template or the model from the View class, but nothing worked. I tried editing the Table class again, but nothing. I tried switching the View class from SingleTableView to SingleMixinView, but that just breaks it even more. This is my Table class: class InsertTable(tables.Table): class Meta: model = Insert template_name = "list.html" fields = ['id', 'name', 'phone', 'description', 'date', 'done', 'edit'] edit = tables.TemplateColumn(template_name="edit.html", verbose_name="edit", orderable=False) This is my view class: class List(SingleTableView): model = Insert table_class = InsertTable template_name = "list.html" -
Function(instance, filename)
I,m working with my first project in Django, And I have a model like that: def get_image_path(instance, filename): category_name_path = instance.category.category_name return f"{category_name_path}/{filename}" class Gallery(models.Model): description = models.TextField() category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) image = ResizedImageField(size=[1920, 1920], upload_to=get_image_path) def __str__(self): return '%s %s %s' % (self.category, self.image.url, self.description) It works but I cannot understand how the 'filename' argument is passed to the function? How it works? ;) -
Executing the bat file before starting the iis site
My django application uses environment variables that must be set via a bat file. How to do it via python (for example via subprocess) I do not know because when executing a bat file via python, a new process is created in which environment variables are set, but when the process ends, all environment variables disappear and they are not reflected in the creator process. My django server is running on IIS. Perhaps you should configure IIS somehow so that it executes first .bat file and then launched my django project and this django project inherited all the environment variables that it created .bat file. -
I am getting MultiValueDictKeyError at /gf/ 'name'
Error ImageI am getting following error. I have no option to set name property(before same error pop up but resolved by changing name) since I am using form then how to resolve it. MultiValueDictKeyError at /gf/ 'name' Request Method:GETRequest URL:http://127.0.0.1:8000/gf/?age=28&csrfmiddlewaretoken=0NribXMzevzOMqH3YoYiK65wqODRNRj3oiKBT50X5NK4BTi7j87UhMTRndTpz8S5Django Version:4.2Exception Type:MultiValueDictKeyErrorException Value:'name' Code: views.py from django.shortcuts import render from django.shortcuts import render from .forms import * def name_view(request): form=Nameform() return render(request,'name.html',{'form':form}) def age_view(request): form=AgeForm() name=request.GET['name'] request.session['name']=name return render(request,'age.html',{'form':form}) def gf_view(request): form=GFForm() age=request.GET['age'] request.session['age']=age return render(request,'gf.html',{'form':form}) def result_view(request): gf=request.GET['gf'] request.session['gf']=gf return render(request,'result.html') forms.py from django import forms class Nameform(forms.Form): name=forms.CharField() class AgeForm(forms.Form): age=forms.IntegerField() class GFForm(forms.Form): gf=forms.CharField() name.html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <h1>Name Registration Form</h1><hr> <form action="{%url 'age'%}" > {{form}} {%csrf_token%}<br><br> <input type="submit" name="" value="Submit Name"> </form> </body> </html> age.html: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <h1>Age Registration Form</h1><hr> <form action="{%url 'gf'%}" > {{form}} {%csrf_token%}<br><br> <input type="submit" name="" value="Submit Age"> </form> </body> </html> gf.html: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <h1>GF Registration Form</h1><hr> <form action="{%url 'result'%}" > {{form}} {%csrf_token%}<br><br> <input type="submit" name="" value="Submit GF's Name"> </form> </body> </html> result.html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> {%if request.session%} <h1>Thanks for … -
Having trouble sorting a table by column header that is populated by Django Pagination
I'm making a SaaS application using Django that displays a table where each row represents a loan, and each column represents information about that loan (name, date, amount, rate, etc.). In my first version of the software, I passed all of the loans in the database into the table, and then used Javascript to sort the table on the client side. The table was sorted alphabetically by name as default, but the user could click any of the column headers to resort the table by that column. The user could click the same column a second time to reverse the sort order of that column (i.e. click once to sort by amount ascending, twice to sort by amount descending). This worked well but when I decided to add more loans to the database, I realized I needed Pagination. In my current version, I have changed the application so that I'm using Django's Pagination and sorting the data in my views.py file before passing it to the HTML template. I hadn't done Pagination before in Django so I used ChatGPT to help but I now have a solution that sort of works, but I'm not quite sure how to debug what's … -
django forms 'tuple' object has no attribute '_meta'
`I am getting this error when i post the data in django forms 'tuple' object has no attribute '_meta'` Views.py def user_ajax_info(request): if request.method == "POST": req_type = request.POST.get('type') if req_type == "Personalinfoform": empId = request.POST.get("employee_id") user_obj = User.objects.get(username=empId) print(user_obj,'user object') additional_info_obj = PersonalInfo.objects.get_or_create(employee=user_obj) form = AssociatePersonalInfoForm(request.POST, instance=additional_info_obj) if form.is_valid(): additional_info_obj = form.save(commit=False) additional_info_obj.employee = request.user form.save() return JsonResponse({"status": "success"}, status=200) else: return JsonResponse({"status": "failure"}, status=400) return redirect('user:profile') This is my forms forms.py I added filters in this form class AssociatePersonalInfoForm(forms.ModelForm): GENDER_CHOICES = [ ('Male', 'Male'), ('Female', 'Female') ] MARITAL_CHOICES = [ ('Married', 'Married'), ('Single', 'Single'), ('Widowed', 'Widowed'), ('Separated', 'Separated'), ('Divorced', 'Divorced') ] MEDICAL_CHOICES = [ ('Self', 'Self'), ('Spouse', 'Spouse'), ('Children', 'Children'), ('Parents', 'Parents'), ] Relation_CHOICES = [ ('Father', 'Father'), ('Mother', 'Mother'), ('Spouse', 'Spouse'), ] gender = forms.ChoiceField(widget=forms.Select(attrs={'required': 'required'}), choices=GENDER_CHOICES) nationality = forms.ModelChoiceField(queryset=Nationality.objects.all().order_by("nationality_name"), empty_label="Select") email = forms.EmailField(max_length=254) caddressfile = forms.ModelChoiceField(queryset=CurrentAddressProoff.objects.all().order_by("rent_receipt"), empty_label="Select") # per_addressfile = forms.ModelChoiceField(queryset=PermentAddressProoff.objects.all().order_by("adharcard"), empty_label="Select") # maritalstatus = models.CharField(max_length=20, choices=MARITAL_CHOICES, null=True, blank=True) # alpha version # child_info = forms.ModelChoiceField(queryset=Employee_childDetails.objects.all().order_by("child_name"), empty_label="Select") # medicalinsurance_preferencee = forms.ChoiceField( choices=MEDICAL_CHOICES) # emergency_relations = forms.ChoiceField( choices=Relation_CHOICES) approved_status = forms.CheckboxInput() class Meta: model = PersonalInfo fields = ('employee','fullname','preffered_name','gender','nationality','contactnum','alternate_num','email','alternate_email', 'fathername','father_dob','mothername','mother_dob','maritalstatus','spousename','spouse_dob','cline1','cline2','carea','ccity','cdistrict','cstate','cpincode','caddressfile','pline1','pline2','parea','pcity','pdistrict','pstate','pstate','ppincode','per_addressfile','child_info','medicalinsurance_preferencee','emergencycontactname1','emergency_relations','emergencycontactnumber','emergencycontactnumber2') ) This my models class PersonalInfo(models.Model): MARITAL_CHOICES = [ ('Married', 'Married'), ('Single', 'Single'), ('Widowed', 'Widowed'), ('Separated', 'Separated'), … -
What class instance should be used for request of authenticate()?
I have backend which uses the Ldap class MyLDAPBackend(LDAPBackend): def authenticate(self, request, username=None, password=None, **kwargs): print("Try ldap auth") print(type(request)) # <class 'django.core.handlers.wsgi.WSGIRequest'> user = LDAPBackend.authenticate(request, username, password,kwargs) This shows the error like this, 'WSGIRequest' object has no attribute 'settings' So, I checked the source code in [django-auth-ldap][1] library. class LDAPBackend: def authenticate(self, request, username=None, password=None, **kwargs): if username is None: return None if password or self.settings.PERMIT_EMPTY_PASSWORD: ldap_user = _LDAPUser(self, username=username.strip(), request=request) user = self.authenticate_ldap_user(ldap_user, password) else: logger.debug("Rejecting empty password for %s", username) user = None return user It expect the instance which has access to settings.py, however framework pass the <class 'django.core.handlers.wsgi.WSGIRequest'> to authenticate. How can I solve this? -
Access Microsoft Graph API in Django Project
I have a Django project that uses django-microsoft-auth for user authentication and I would like to know how I could go about get users' profile pictures from the Microsoft Graph API if they are logged in. I know from the documentation that I need to use https://graph.microsoft.com/v1.0/me/photo/$value to get the picture data then I can encode it as Base64 then I can use a context processor to pass it to my base.html template and put it in an image as seen in this stackoverflow post. What I don't know how to do is implement getting the data from the API. I know I need an access token, but I'm not sure how to get that since all of the authentication is handled by the django-microsoft-aith package. -
How can I annotate a django queryset with more than one values
I have an application that scrapes some eshops every day, and I record the Price of every Item. A simplified version of my models looks like this: class Item(models.Model): name = models.CharField(max_length=512, blank=True) class Price(models.Model): item = models.ForeignKey("Item", on_delete=models.CASCADE) timestamp = models.DateTimeField(blank=True) per_item = models.FloatField(blank=True) And my tables can look like this: # Item id | name ----------- 1i | item-1 2i | item-2 3i | item-3 # Price id | item | timestamp | per_item -------------------------------------- 1p | i1 | 2023-04-10 | 10.0 2p | i2 | 2023-04-10 | 2.0 3p | i3 | 2023-04-10 | 14.5 4p | i1 | 2023-04-11 | 11.0 5p | i3 | 2023-04-11 | 12.5 6p | i2 | 2023-04-12 | 2.0 7p | i3 | 2023-04-12 | 14.5 8p | i1 | 2023-04-13 | 12.0 9p | i2 | 2023-04-13 | 3.5 10p | i3 | 2023-04-13 | 15.0 Note that not all Items exist every day, some of them may be present today, missing tomorrow and back again on the day after, and so on. What I want to do I'm trying to write a query that for a given day it will give me the last 2 Prices for every … -
The user is not added to the group. Django Forms
I have a form to create an employee, and in this form there is a "groups" field. When submitting the form, a user is created but not added to the selected group froms class CreateEmployeeForm(auth_forms.UserCreationForm): class Meta: model = user_model fields = [ 'username', 'password1', 'password2', 'email', 'first_name', 'last_name', 'phone_number', 'gender', 'groups', 'middle_name', ] views My View accepts 3 arguments.(form_class, template, success_url) class DirectorCreateEmployeeView(CreateView): template_name = 'director/create_employee_director.html' form_class = CreateEmployeeForm success_url = reverse_lazy('director_list_employee_view') def user_registered_callback(sender, user, request, **kwargs): group_name = request.POST['group_id'] or None if group_name: try: g = Group.objects.get(name=group_name) except Group.DoewNotExists: g = None if g: g.user_set.add(user) html in html I used a custom crispy form <form action="" method="post"> { % csrf_token % } < div class = "card-body" > < h6 class = "card-title" > Creation empl < /h6> < div class = "row" > < div class = "col-md-6" > < div class = "form-group" > { { form.first_name | as_crispy_field } } < /div> < div class = "form-group" > { { form.last_name | as_crispy_field } } < /div> < div class = "form-group" > { { form.middle_name | as_crispy_field } } < /div> < div class = "form-group" > { { form.password1 | as_crispy_field } } … -
Vercel Django Deployment Error : 500: INTERNAL_SERVER_ERROR. Unable to import module 'backend.settings'
I have created a Django Project which I wanna use as backend for my React project. In the root of the project there are two folders : backend for django and frontends for react. Also I have provided a screenshot of the directory tree of my project: screenshot I added requirements.txt and vercel.json with all required stuff below is the code snippets for both. Also I have added vercel to allowed domains according to the documentation. But when I deploy the app through GitHub in vercel, deployment process finishes but when I visit the website I get 500 INTERNAL_SERVER_ERROR which further says 'FUNCTION_INVOCATION_FAILED' So then I go to vercel and check Runtime Logs and I get to see the following error printed multiple times: [ERROR] Runtime.ImportModuleError: Unable to import module 'vc__handler__python': No module named 'backend.settings' Traceback (most recent call last): So the error is not probably due to missing dependencies in requirements.txt but with the import error of my project files. In this case the settings.py. I don't really understand what's causing the import error since I gave correct paths of wsgi.py in vercel.json requirements.txt asgiref==3.6.0 Django==4.2 djangorestframework==3.14.0 python-dotenv==1.0.0 pytz==2023.3 sqlparse==0.4.3 tzdata==2023.3 vercel.json { "builds": [{ "src": "backend/backend/wsgi.py", "use": "@vercel/python", …