Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Data from SAP to Django
How to stream data from SAP into a django webapp? Is there any documentation? Do I need an api from the sap api management system? Can I use sqlite3 as a database in django? Thank you for any help -
Django how to display subquerys in Template
My view: credits = Credit.objects.filter(account=OuterRef('pk')).values('account_id').annotate(sum_credits=Sum('amount')) debits = Debit.objects.filter(account=OuterRef('pk')).values('account_id').annotate(sum_debits=Sum('amount')) dif = Account.objects.annotate(credit_sum=Subquery(credits.values('sum_credits')),debit_sum=Subquery(debits.values('sum_debits')),balance=F('credit_sum') F('debit_sum')).values_list('name', 'balance') My template: {% for account in dif %} <tr> <td>{{ account }}</td> <td></td> <td></td> <td></td> </tr> {% endfor %} result : ('andrea', 10) ('mosca', 20) how to remove the parentheses? -
How do I properly condense this Python IF statement?
I am pretty new to Python, and trying to find a better way to code this. There has to be a way but just not sure how to do it. The two queries are essentially the same, so there has to be a way to reduce. Is there a more efficient way to do this? if set_date is not None: params = {CarTow.ACCEPTED,CarTow.UNCONFIRMED} if is_rejected != 'true': query = query\ .filter(createddate__lte=set_date) \ .car_statuses(CarTow.ACCEPTED) \ .order_by('-createddate') else: query = query\ .filter(airdate__lte=set_date) \ .car_statuses(CarTow.ACCEPTED,CarTow.UNCONFIRMED) \ .order_by('-createddate') return query Sorry if this is a simple question, newbie here. -
Django. JSON response not working as expected
In Django, I am simply sending some JSON back when a user makes a POST request to my server. I am sending different JSON responses depending on the information the user inputs to my api endpoint. (I am using POSTMAN to test this) My API checks if the passwords a user supplies match, and if so sends a success message, however if not send a failure message. If they match or don't match, the same JSON is always sent back. Which is not wanted. Here is my code: def signup(request): if request.method == 'POST': if request.POST.get('password1') == request.POST.get('confirmPassword'): return JsonResponse({'message': 'Well Done'}) print('Success') else: print('Do not match') return JsonResponse({'error': 'Password fields do not match'}, status=400) Postman input: { "password1": "test123", "confirmPassword": "deedeedde" } RESPONSE: { "message": "Well Done" } -
Render ValidationError in template
I am making a page for adding products to the web shop by the user, and I am having troubles with displaying ValidationError in my template. The ValidationError is raised if selected category isn't the most specific category to select. To select a category, the user has to go trough chained dependent combobox selection, where you start with one combobox for main category and once you select main category, another <select> appears for selecting a subcategory, and so on until the innermost subcategory is selected. category is a field on my base Product model (from which other models, such as Book or Shoes, inherit) and isn't listed in ModelForms' inner Meta class fields, thus I can't have clean_category method on my ModelForms. Here is my view: @login_required def product_create_view(request): if request.method == 'POST': main_category = request.session.get('main_category') create_product_form = mappings[main_category](request.POST) if create_product_form.is_valid(): obj = create_product_form.save(commit=False) category = request.session.get('category') if Category.objects.get(id=category).is_leaf_node(): obj.category = Category.objects.get(id=category) obj.save() else: raise forms.ValidationError('Please select most specific category.') return render(request, 'products/product_create.html', { 'categories': Category.objects.filter(parent=None) }) How to render the ValidationError in the template, i.e. how can I have my ValidationError in my {{ field.errors }}? Currently I am seeing a stack trace. -
Python/Django: How to reactivate pipenv after exiting
Please Everybody. I have a little problem with pipenv. For instance, I am work on a Django project and I decided to sleep. I had to shutdown my laptop for some reason. Then i woke up navigated to the project and I open it in VScode again. My question is how to I reactivate the pipenv environment again. I mean something like source bin/activate if you are using virtualenv I use pipenv shell but i want to be sure that is absolutely right. -
How to fix problem with DJANGO_SETTINGS_MODULE?
I am pretty beginner in django and in coding too. Stuck for a while with an error. Will really appreciate if someone's help me!I tried to google it and it gave me a lot of solutions, I tried them but it gave errors too. What should I write to make things done? I took this code from https://www.youtube.com/watch?v=a48xeeo5Vnk&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p&index=2 from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), ] And it gave me this error: File "urls.py", line 21, in <module> path('admin/', admin.site.urls), File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/functional.py", line 256, in inner self._setup() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 529, in _setup AdminSiteClass = import_string(apps.get_app_config('admin').default_site) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/registry.py", line 153, in get_app_config self.check_apps_ready() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 64, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.``` -
Change structure of JSON data for API POST request with Django
I have a Django REST API endpoint with this structure, that I need to post to an external API: { "body": [ "...", "...", "...", ], "title": [ "...", "...", "...", ], "id": [ "...", "...", "...", ] } The first item under 'body' goes with the first under 'title' and 'id', and so forth. The problem I'm having is that the API in question expects JSON data with the following structure: { "texts": [ { "body": "...", "title": "...", "id": "..." }, { "body": "...", "title": "...", "id": "..." }, { "body": "...", "title": "...", "id": "..." }, ], "language": "EN", } And I can't figure out how have my endpoint mirror that structure, with the bodies, titles, and ids grouped together, those groupings nested under texts, and with the language parameter appended at the end. The serializer I'm using in my views.py looks as follows: class MyReasonsSerializer(serializers.Serializer): body = serializers.SerializerMethodField() title = serializers.SerializerMethodField() id = serializers.SerializerMethodField() def get_body(self, obj): return obj.reasons.order_by('transaction_date').values_list('body', flat=True) def get_title(self, obj): return obj.reasons.order_by('transaction_date').values_list('title', flat=True) def get_id(self, obj): return obj.reasons.order_by('transaction_date').values_list('transaction_date', flat=True) class ReasonsData(RetrieveAPIView): queryset = Market.objects.all().prefetch_related('reasons') authentication_classes = [] permission_classes = [] serializer_class = MyReasonsSerializer Thanks in advance for any advice! -
slider menu in django suit not working in google chrome
Suddenly with a Google Chrome update, the slider menu does not work in django suit, with python2, but in other browsers such as safari if it works, I don't know why it should, or how it can be fixed -
"ERROR: Command errored out with exit status 1" while trying to perform "pip install mod-wsgi" in command prompt (Windows 10)
I want to deploy my django app using apache and mod_wsgi on Windows 10. I have Python 3.7 (64-bit) and Apache 2.4.41 Win64. I open up the admin command prompt and type "pip install mod-wsgi" The following occurs: Collecting mod-wsgi Using cached https://files.pythonhosted.org/packages/26/03/a3ed5abc2e66c82c40b0735c2f819c898d136879b00be4f5537126b6a4a4/mod_wsgi-4.6.7.tar.gz Installing collected packages: mod-wsgi Running setup.py install for mod-wsgi ... error ERROR: Command errored out with exit status 1: command: 'c:\program files\python37\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\jason\\AppData\\Local\\Temp\\pip-install-5snwyezc\\mod-wsgi\\setup.py'"'"'; __file__='"'"'C:\\Users\\jason\\AppData\\Local\\Temp\\pip-install-5snwyezc\\mod-wsgi\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\jason\AppData\Local\Temp\pip-record-6qml1kb3\install-record.txt' --single-version-externally-managed --compile cwd: C:\Users\jason\AppData\Local\Temp\pip-install-5snwyezc\mod-wsgi\ Complete output (33 lines): c:\program files\python37\lib\distutils\dist.py:274: UserWarning: Unknown distribution option: 'bugtrack_url' warnings.warn(msg) running install running build running build_py creating build creating build\lib.win-amd64-3.7 creating build\lib.win-amd64-3.7\mod_wsgi copying src\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi creating build\lib.win-amd64-3.7\mod_wsgi\server copying src\server\apxs_config.py -> build\lib.win-amd64-3.7\mod_wsgi\server copying src\server\environ.py -> build\lib.win-amd64-3.7\mod_wsgi\server copying src\server\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\server creating build\lib.win-amd64-3.7\mod_wsgi\server\management copying src\server\management\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\server\management creating build\lib.win-amd64-3.7\mod_wsgi\server\management\commands copying src\server\management\commands\runmodwsgi.py -> build\lib.win-amd64-3.7\mod_wsgi\server\management\commands copying src\server\management\commands\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\server\management\commands creating build\lib.win-amd64-3.7\mod_wsgi\docs copying docs\_build\html\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\docs creating build\lib.win-amd64-3.7\mod_wsgi\images copying images\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\images copying images\snake-whiskey.jpg -> build\lib.win-amd64-3.7\mod_wsgi\images running build_ext building 'mod_wsgi.server.mod_wsgi' extension creating build\temp.win-amd64-3.7 creating build\temp.win-amd64-3.7\Release creating build\temp.win-amd64-3.7\Release\src creating build\temp.win-amd64-3.7\Release\src\server C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Ic:\Apache24/include "-Ic:\program files\python37\include" "-Ic:\program files\python37\include" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files … -
Attaching profile to user model in django
I am trying to add some extra information to my user model...via the one-to-one link example here: https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#onetoone So I took their example: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) Implemented it on my own in an /accounts app that seemed to of showed up in my application once I got authentication and authorization stuff working in my djanog app. So the models.py in my /accounts looks like: class APOUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) institution = models.ForeignKey("mainpage.InstitutionMember", on_delete=models.PROTECT) on_site_status = models.ForeignKey("mainpage.SiteStatus", on_delete=models.PROTECT) refer_to_as = models.TextField(max_length = 30, blank=True) #if the above is custom room_preference = models.ForeignKey("housing.Room", on_delete=models.PROTECT) I can say: python3 manage.py makemigrations accounts It works, but when I try to run a python3 manage.py migrate it chokes with an error about a lazy reference in one of my other app's models: ValueError: The field housing.HousingRequest.user was declared with a lazy reference to 'accounts.apouser', but app 'accounts' isn't installed. I don't recall ever installing the accounts it seemed to always be there in my settings given by what I guess was this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', … -
Passing filtering options to a nested serializer in django DRF
assuming I have the following models and serializers : Models: class Album(models.Model): album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE) title = models.CharField(max_length=100) duration = models.IntegerField() and the following serializers : class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ['order', 'title', 'duration'] class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True, read_only=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] I would like to write a view that by getting a duration value will return a list of albums containing the tracks that the duration is equal to the given duration value. Assuming I have an album : a - of John, track1, duration : 60 track2, duration : 120 track3, duration : 60 b- of Mike, track1, duration : 60 track2, duration : 120 If I'll reach my endpoint with the value duration: 60, I want the following to return: [album : a, track1, duration : 60 track2, duration : 120 track3, duration : 60 album : b, track1, duration : 1:00 ] The main issue I am having is that I can't control the queryset of a nested serializer, what I would like to be able to do, is to pass the duration value … -
Update balance after withdrawal and deposit with python django app
I'm still new to django and i'm learning by trying to build a web bank account like app. I have created a users app and the bank app within my project. in my users app, i have models such as the user profile, user account details and user account. the user account model is designed to store the current account balance of the user. in the bank app, i have models such as deposit and withdrawals, these models have details of the deposit or withdrawal amount, date and time of withdrawal. Here is my user account model from django.db import models from django.contrib.auth.models import User class UserAccount(models.Model): class Meta: verbose_name = 'UserAccount' verbose_name_plural = 'UserAccounts' MAX_BALANCE = 10000000.00 MIN_BALANCE = 0.00 MAX_DEPOSIT = 2000000 MIN_DEPOSIT = 10000 MAX_WITHDRAW = 1000000 MIN_WITHDRAW = 10000 MAX_PORTFOLIO = 2000000 MIN_PORTFOLIO = 10000 user = models.OneToOneField(User, on_delete=models.CASCADE) created = models.DateTimeField(blank=True, null=True) modified = models.DateTimeField(blank=True, null=True) account_balance = models.PositiveIntegerField(verbose_name ='Current balance', default=0) def __str__(self): return f'{self.user.username} Account' then this is the deposit model i created in the bank app from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class MakeDeposit(models.Model): MAX_DEPOSIT = 2000000 MIN_DEPOSIT = 10000 DEPOSIT_STATUS_PENDING = … -
HTML select form with option to enter value does not store the entered value as object field in django
I have a Django form in which I have several drop-down menus that have an option to enter a custom value. In order to enter a custom value, I am using the following implementation to toggle a textbox whenever the custom value is selected from this implementation http://jsfiddle.net/6nq7w/4/ Whenever I select an option from the dropdown list and save the form, the model's object value (In this case it is EmployeeInformation.dept) retains the value selected, but it is not the case if I enter a custom value. In the below example, I use a chained dropdown implementation to load the Department based on the Department ID. For example - Let's say while filling the form I select the value Sales then the value of EmployeeInformation.dept = Sales, whereas when I select the option as Enter Manually and enter a new value say DeptXYZ the Django model object does not take this manually entered value as the data for the field Dept. models.py class EmployeeInformation(models.Model): name = models.Charfield(max_length=30,null=False, blank=False) dept_id = models.ForeignKey(DepartmentInformation, on_delete=models.SET_NULL, null=True) dept = models.ForeignKey(SubDeptInformation, on_delete=models.SET_NULL, null=True) salary = models.DecimalField(null=True, blank=True, decimal_places=2, max_digits=10) form.html <!DOCTYPE html> <html> <script> function toggleField(hideObj,showObj){ hideObj.disabled=true; hideObj.style.display='none'; showObj.disabled=false; showObj.style.display='inline'; showObj.focus(); } </script> <body> <form … -
How to put an image from ImageField on an html email template in django
I have in views.py: def buy(request): if request.method=='POST': form=forms.Purchase(request.POST) if form.is_valid(): form.save() user = Person.objects.filter(first_name=form.cleaned_data.get('first_name')).filter(last_name=form.cleaned_data.get('last_name')).first() name=form.cleaned_data.get('first_name') + form.cleaned_data.get('last_name') subject, from_email, to = 'Subject test1234', 'tasselsas@gmail.com', form.cleaned_data.get('email') html_content = render_to_string('tickets/mail_template.html', {'first_name':user.first_name, 'imagelink':user.qr_image}) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() return redirect('thankyou') else: form=forms.Purchase() return render(request, 'tickets/buy.html', {'form': form}) Inside of the ImagField is contained jpg image file, and I want it to show on the html email being sent. mail_template.html: {% extends "event/base.html" %} {% block content %} <p>{{ first_name }}</p> <img src= {{ imagelink }}> {% endblock content%} The first_name works, but the image does not. -
Forbidden You don't have permission to access this resource. django apache ubuntu
i tried to deploy my django application this is the conf file Alias /static /home/username/main_folder/app name/static <Directory /home/username/main_folder/app name/static> Require all granted </Directory> Alias /media /home/username/main_folder/app name/media <Directory /home/username/main_folder/app name/media> Require all granted </Directory> <Directory /home/username/main_folder/app name/app name> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/username/main_folder/app name/app name/wsgi.py WSGIDaemonProcess django_app python- path=/home/username/main_folder/app name python- home=/home/username/main_folder/venv WSGIProcessGroup django_app sudo ufw allow http/tcp but when i enable port 8000 0.0.0.0:8000 it will work fine is there something i missed ? -
Django error: 'QuerySet' object has no attribute 'destinations'
Doing little Django ecommerce project for a hobby. Can't seem to add an item to the cart. Get this error 'QuerySet' object has no attribute 'destinations'. Tried to clean the database, however did not work. my views.py def add_to_cart(request, slug): cart = Cart.objects.all() try: destination = Destination.objects.get(slug=slug) except Destination.DoesNotExist: print('does not exist') except: pass if not destination in cart.destinations.all(): cart.destinations.add(destination) else: cart.destinations.remove(destination) return redirect(reverse('cart')) models.py class Cart(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) destinations = models.ManyToManyField(Destination, blank=True, null=True) total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00) active = models.BooleanField(default=True) urls.py path('cart/<slug>', cart_views.add_to_cart, name='add_to_cart'), index.html <a href="{% url 'add_to_cart' destination.slug %}">Add</a> cart.html {% for destination in cart.destinations.all %} {{ destination }} {{ destination.price }} {% endfor %} Get this error 'QuerySet' object has no attribute 'destinations'. Much appreciate Your help! -
Failed to load resource: status of 500 (Internal Server Error) Django
I made an Admin user who uploads destinations. Data save in DB and get in a smooth way except for images. and Shows this Error in Console "Failed to load resource: the server responded with a status of 500 (Internal Server Error)" HTML {% for dest in dests %} <!-- Destination --> <div class="destination item"> <div class="destination_image"> <img src="{{dest.img.url}}" alt=""> {% if dest.offer %} <div class="spec_offer text-center"><a href="#">Special Offer</a></div> {% endif %} </div> <div class="destination_content"> <div class="destination_title"><a href="destinations.html">{{dest.name}}</a></div> <div class="destination_subtitle"><p>{{dest.description}}</p></div> <div class="destination_price">From ${{dest.price}}</div> </div> </div> {% endfor %} Views.py def index(request): dests = Destination.objects.all() return render (request, 'index.html',{'dests':dests}) In Chrome's Console: Failed to load resource: the server responded with a status of 500 (Internal Server Error) -
How to configure Django media root in Apache
This is my first time deploying to a production env and I am having a tough time getting my media folder settings to point to the correct directory. I would like to note that my static files are working correctly. My projects folder structure looks like: /sc /sc /sc /media /memos /payroll /users /static db.sqlite3 manage.py requirements.txt My projects settings.py MEDIA settings: STATIC_URL = '/users/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' My /etc/apache2/sites-available/sc.conf media and static settings: Alias /users/static /home/davida/sc/sc/static <Directory /home/davida/sc/sc/static> Require all granted </Directory> Alias /media /home/davida/sc/sc/media <Directory /home/davida/sc/sc/media> Require all granted </Directory> <Directory /home/davida/sc/sc/sc> <Files wsgi.py> Require all granted </Files> </Directory> When I run a process on my site, which usually works in development, it gives back this error: [Errno 2] No such file or directory: 'media/DavidAlford/Tips_By_Employee_Report.xls' This file is uploaded by the user previous to this process and exists in at that directory. Also, I have a script which should be deleting all the old files in this directory before user uploads new files but that is not working either so I assume this means that my Apache settings are wrong. -
How can I redirect to another Twilio task using Twilio and Django?
I'm creating a chatbot and I can't redirect to a task created at the Twilio Autopilot Console. What it does: user sends a message to the bot, the view gets called, does some stuff which I removed for clarity then redirects (or should) to an Autopilot task. @twilio_view def bot(request): account_sid = config('account_sid') auth_token = config('auth_token') client= Client(account_sid, auth_token) msgresponse = MessagingResponse() msgresponse.redirect(url="task://parametrizacao") return HttpResponse(status=200) If I redirect to another view, django-style, it works, but I want it to redirect to a Twilio Autopilot Task... -
Installing Geospatial libraries in Docker
django's official documentation lists 3 dependencies needed to start developing PostGIS application. They list a table depending on the database. I use docker for my local development and I am confused on which of those packages should be installed in the Django container and which in the PostgreSQL container. I am guessing some of them should be on both. Would appreciate your help on this. -
Redirect to download Django
I want to track how many times file has been downloaded. I see it this way: 1) Instead of <a href="{{ file.url }}" download>...</a>, I should redirect user for download view; <a href="download/{{ file.id }}/{{ file.name }}">...</a> file.id and file.name needed for proper work of function bellow. 2) In my download view I need to registrate download of specific file, let's say I have registrate_dl function that does its job. Also, I need to take that {{ file.url }} value like in first link from first paragraph. 3) Finally, I registered download for specific file and got {{ file.url }} as file_url variable. But, if, at the end of view function I place return redirect(file_url), it just redirects me to file, without starting download. So, how should i return this file_url, and trigger download? -
Computing the SHA256 hash of a FileResponse objects content
I have a file for which I have computed its SHA256Sum and have verified it is correct. hash1 = computeSHA256(filepath) I need to compute the hash again, but this time using the values inside response.streaming_content where response is a Django FileResponse object, which I have done as follows: response = FileResponse(request, open(filepath, 'rb'), content_type='application/json') content = b''.join(response.streaming_content) h = hashlib.sha256() h.update(str(content).encode('utf-8')) hash2 = h.hexdigest() This issue here is that hash1 != hash2. For example: hash1 = 7836496a8e17dac5aad5dea15409b06558d0feaf6c39198eae620afebb1fa097 hash2 = 70a3e07b20e722652740e93702b70322d042b9710b3087228e70551ad8301086 Can anyone see where I have gone wrong to cause the two hash values to not be equal? Note: the file is a Google Protobuf (.pbf) file, so is binary. -
How to put the username of the logged-in user in the databse each time a form is submitted
I have an application where a user can submit a form which goes into the database (POSTGRES). I want to be able to automatically send the username of the user logged in to the same database, so i can keep track of who is submitting. (I do not want to put a form line with the username, i want this to be dealt with in the back-end). what I managed to do is get the user-id, but it stays null, and I do not know how to get the username in the database and to complete it at each submission. I hope I am clear, thanls guys. Here is my code models.py from django.db import models as db_models from django.contrib.auth.models import User from django.contrib.gis.db import models class Fertidb(models.Model): user = db_models.ManytoManyField(User, on_delete=models.CASCADE) area = models.IntegerField() plot = models.FileField(upload_to='KML_FILES', blank=True) def __str__(self): return f' Parcelles de {self.user.username}' forms.py from django import forms from django.contrib.auth.models import User from .models import Fertidb class FertidbForm(forms.ModelForm): class Meta: model = Fertidb labels = { "plot": "Importez votre fichier KML" } fields = ['culture', 'area', 'plot'] views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import FertidbForm from django.contrib.auth.models … -
Request object has no user during process_request in django middleware
I have a custom middleware that I'm writing which I have added to my list of middlewares in settings. The middleware needs to access some attributes on the user attached to the request, and this works fine for requests made directly to the backend server. However, for CORS requests that come from the frontend, I'm seeing that the user is an AnonymousUser during process_request, and they only show up as authenticated in process_response. I have 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware' above my custom middleware in settings.py, so I would have expected this to work. Any advice on different things I should try to be able to access the authenticated user in my custom middleware's process_request method with CORS requests?