Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I add the path to python for vscode
My util.py file is sited at the same directory with views.py, why do I still have the ImportError: ImportError -
DJango Generic date views filtering
Hello I really need help with date views. I need a prediction based view on date. I have users and staff, users have their views while staff can see everything what a user did in their view right now I have a Dashboard for staff where they can choose the view of a user class Dashboard (AdminStaffRequiredMixin, LoginRequiredMixin, ListView): model = SchulverzeichnisTabelle template_name = 'SCHUK/Dashboard.html' context_object_name = 'Dashboard' the view {% for Ansicht in Dashboard %} <tbody> <tr> <th scope="row"></th> <td><a href="{% url 'Ansicht' Ansicht.Benutzer.pk %}">{{Ansicht.Konto}}</a></td> <td><a href="{% url 'Ansicht' Ansicht.Benutzer.pk %}">{{Ansicht.Schulname}}</a></td> <td><a href="{% url 'Ansicht' Ansicht.Benutzer.pk %}">{{Ansicht.SAB}}</a></td> <td><a href="{% url 'Ansicht' Ansicht.Benutzer.pk %}">{{Ansicht.GL}}</a></td> <td><a href="{% url 'Ansicht' Ansicht.Benutzer.pk %}">{{Ansicht.Teilstandort}}</a></td> </tr> </tbody> {% endfor %} Now when they view one view all the data that is show is a _set from user model (that is also why I just cant use simple django filter bc it is a set and I dont know how to filter only the set but thats just a side note) class Ansicht(AdminStaffRequiredMixin, LoginRequiredMixin, DetailView): model = User template_name = 'SCHUK/Ansicht.html' context_object_name = 'Ansicht' the view in short {% for Ansicht in Ansicht.schulverzeichnistabelle_set.all %} {{Ansicht.Konto}} {{Ansicht.S_Form}} {{Ansicht.Schulname}} {{Ansicht.SAB}} {{Ansicht.GL}} basically the same, but not all entries … -
Multiple widgets for one form field in Django
I have the following form: class ExcipientForm(ModelForm): class Meta: model = Excipient fields = ( "Excipient_type", "Excipient_concentration", ) widgets = { 'Excipient_type': Select(attrs={ 'style' : 'width:100%;', 'class' : 'dropdowns', }), 'Excipient_concentration': TextInput(attrs={ 'class': 'slider', 'type': 'number', 'value':"20", 'max':"100", 'step': "0.1", 'id':"excipient_concentration" } ) } ExcipientFormSet = inlineformset_factory( Parameters, Excipient, ExcipientForm, can_delete=False, min_num=1, extra=0 ) This is the template to post to the form: <form action="" id="form-container" method="POST"> {% csrf_token %} <div class='row'> <div class='col'> <label for="id_API_batch_number" class="form-label">API batch number : </label> </div> <div class='col'> {{ parameter_form.API_batch_number }} </div> </div> <hr class="my-4"> <div class='excipient-form'> {{ excipient_form }} {{excipient_form.id.auto_id}} <input type="range" class="slider" name="slidervalue" value='20' max="100" step="0.1" onchange="updateTextInputRange(this.value);"> </div> <button id="add-form" type="button">Add Excipient</button> <hr class="my-4"> <label for="num6" class="form-label">Total Concentration: </label> {{ parameter_form.Total_concentration }} <br></br> <input type="submit" id="submit" class="btn btn-primary" value="Submit"> </form> I'm trying to get the sliders and it's corresponding number field to "sync". This is the JS I have at the moment. //Update Textbox value from slider value function updateTextInputRange(val) { document.getElementByID('excipient_concentration').value = val; // text input //checkValueSum(); } Some of the things I tried: Finding out the ID for each instance of the slider and number input. This failed as every instance has the same ID. Tried using multiple widgets in … -
How to fix 8000 port is already in use django runserver problem?
I am trying to run Django project in ubuntu 20.04 LTS but it shows 8000 port already in use. I can run using> python manage.py runserver 8080 But I want to free my 8000 port How can I do that? (env) amol@amol-Ideapad-320:~/My Code/Python/ecommerse-models/ecomm$ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 03, 2022 - 15:12:45 Django version 4.1, using settings 'ecomm.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Error: That port is already in use. -
How to save pillow processed image in already existing Django object
I have created a object model as below from django.db import models # Create your models here. class ImageModel(models.Model): image = models.ImageField(upload_to='images/') editedImg = models.ImageField(upload_to='images/') def delete(self, *args, **kwargs): self.image.delete() self.editedImg.delete() super().delete(*args, **kwargs) And here is what i am trying to do in a function from django.shortcuts import render from EditorApp.forms import ImageForm from EditorApp.models import ImageModel from django.http import HttpResponseRedirect from PIL import Image def edit_column(request): codArr = request.POST.getlist('codArr[]') imgs = ImageModel.objects.first() orgImage = ImageModel.objects.first().image orgImage = Image.open(orgImage) croppedImg = orgImage.crop((int(codArr[0]), int(codArr[1]), int(codArr[2]), int(codArr[3]))) # croppedImg.show() # imgs.editedImg = croppedImg # imgs.save() return HttpResponseRedirect("/editing/") What i am trying to do is the codArr consists of coordinates of top(x, y) and bottom(x, y) in the array form(Which is not an issue and is tested(croppedImg.show() showed the desired cropped image) and handled and used to crop the image). Image crop is working fine. But what i am trying to do is to save the cropped image in editedImg of the model used above. The above commented one is what i tried but throw a error AttributeError: _committed As i have not used any name for image in model as its not required. Kindly help please, Would be very thankfull. -
how to calculate rate of sale percentage for sales of product in python?
hi does anyone have sales growth source code with python? -
Object of type function is not JSON serializable in Django
I have been trying to pass this data in json format but i keep getting this error. I am getting all the data and passing it to a payment getaway for processing. But anytime I pass the data i get the error message raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type function is not JSON serializable def paytes(request): amount = 10 desc = "USSD" category = 'Robert' phone = "233244491909" vote = text slug = "test" award = "test" url = 'https://api.pays.co/charge' transaction_id = random.randint(100000000000, 999999999999) data = json.dumps({ "reference": transaction_id, "amount": amount, "phone": phone, "email":"customer@gmail.com", "mobile_money": { "phone" : "0244496709", "provider" : "MTN" }, "label" : desc, "metadata":{ "custom_fields": [ { "value": desc, "nominee_name": slug, "transaction_id": transaction_id, "amount": amount, "award": award, "category": category, "email": email, "phone": phone, "vote": vote, } ] } }) headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer texk_002929992', 'Cache-Control': 'no-cache' } response = requests.post(url, data=data, headers=headers) return HttpResponse(response) -
How to determine what button was clicked in google chat bot
I can get event CardClicked but my buttons are generating on the fly, these names depend on data in db. How to get name of clicked button from request. class CardClickedEvent(Event): def __init__(self, request): super().__init__(request) self.message = request.get('message').get('text') self.space = request.get('space').get('name') @transaction.atomic def process(self): logger.info(self.request.get('type')['action']['actionMethodName']) -
Dinamic Form Validation - Django
I have a page with 3 forms, the forms are esentially the same in terms of fields but have different validation, I was wondering if instead of having multiple forms is there any way of having one form with dinamic validation, and then pass a keyword to the form to use one validation or another. Here is my forms.py: class FileTypeOneForm(forms.Form): statement = forms.FileField(label='') def clean_statement(self): statement_file = self.cleaned_data['statement_file'] # Check statement_file format and raise ValidationError in case of invalid format # ... return statement_file class FileTypeTwoForm(forms.Form): statement = forms.FileField(label='') def clean_statement(self): statement_file = self.cleaned_data['statement_file'] # Check statement_file format and raise ValidationError in case of invalid format ** required format is different than FileTypeOneForm and FileTypeThreeForm required format ** # ... return statement_file class FileTypeThreeForm(forms.Form): Options = [ ('', 'Select'), ('one', 'One'), ('two', 'Two') ] option = forms.ChoiceField(label='', choices=Options) statement = forms.FileField(label='') def clean_statement(self): statement_file = self.cleaned_data['statement_file'] # Check statement_file format and raise ValidationError in case of invalid format ** required format is different than FileTypeOneForm and FileTypeTwoForm required format ** # ... return statement_file All three forms have the same field statement_file, but with different validation, and the third form has a second field option. Currently these is views.py: … -
Django find duplicates in two tables
I am working on a database of public figures and their positions. I have the following models: class Person(models.Model): full_name = models.CharField() appointments = models.ManyToManyField('Appointment', through='PersonsNAppointments') class Appointment(models.Model): position = models.CharField() persons = models.ManyToManyField('Person', through='PersonsNAppointments') Names are not unique. So in situation when I have John Donne(id_1) and John Donne(id_2) and "John Donne" got appointed they both would get this appointment. I want to create an admin panel where only people with same names and same appointments are shown so the admin could handle these duplicates manually. I need help with writing get_queryset. So far I've figured out how to get duplicated names dup_names = Persons.objects.values('full_name')\ .annotate(name_count=Count('id'))\ .filter(name_count__gt=1).values('full_name') dup_objects = Persons.objects.filter(full_name__in=dupes_names) How to get only those persons who share same appointments? -
How can I join a thrid table to a queryset which already use select_related
I am working with Django and I need to create an API to retrieve the measures depending of three tables (image of the Schema of my tables) Measures contains all measures according to an ID of the sensors Sensors contains the sensor information and the type of the sensor sensor_types contains the information of the type (type name, unit, etc) I need to know the (at least) the sensor name and ID, the type of the sensor and the measures for the sensors. I first tried to retrieve the sensor information and the type the sensor belong to class TypeViewSet(viewsets.ReadOnlyModelViewSet): """ API: return the measures of several sensors according to a type of sensors and a date range. A type is generaly sensors with the same unit (°C, %, kPa) """ # See serializers.py serializer_class = TypesSerializer def get_queryset(self): # get the params idt = self.kwargs['idtype'] # get the date "from" start = self.request.query_params.get('start') # get the date "to" end = self.request.query_params.get('end') type = SensorTypes.objects.filter(id_sensor_type=idt) sensors = Sensors.objects.filter(sensor_types_id_sensor_type=idt)\ .select_related('sensor_types_id_sensor_type') print(sensors.query) return sensors my TypesSerializer file look like: class SensorTypeSerializer(ser.ModelSerializer): class Meta: fields = ("id_sensor_type","sensor_type_name","sensor_type_longname","measure_unit") model = SensorTypes class TypesSerializer(ser.ModelSerializer): sensor_types_id_sensor_type=SensorTypeSerializer( read_only=True ) #"sensor_type_name", "measure_unit", class Meta: fields = ("id_sensor","sensor_name","sensor_types_id_sensor_type") model … -
Why is my django-crispy AdminForm not able to resolve AdminSite url?
Setup I defined an new admin url: from django.contrib.admin import AdminSite from django.http import HttpResponse from django.urls import path class MyAdminSite(AdminSite): def get_urls(self): from django.urls import path urls = super().get_urls() urls += [ path( "generate", admin_site.admin_view(self.my_view), name="generate", ) ] return urls def my_view(self, request): print(request.data) return HttpResponse("Hello!") admin_site = MyAdminSite() The url is successfully registered: print(admin_site.get_urls()) [ ..., ..., <URLPattern 'generate' [name='generate']>] # <-- here! Now in my django-crispy-form, I need to add a form action for multiple submit buttons. The library does not allow multiple form actions to be set, so I had to disable the form tag and add a new one manually: class PromptForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() # django-crispy-forms self.helper.form_method = 'post' self.helper.form_tag = False # <-- disable form_tag # Form layout self.helper.layout = Layout( # Add new form_tag HTML("""<form action="{% url 'admin:generate' %}"><input type="submit" class="btn btn-success" value="generate"></form>"""), ) Issue Neither {% url 'generate' %} nor {% url 'admin:generate' %} are able to reverse match the new url: `django.urls.exceptions.NoReverseMatch: Reverse for 'generate' not found. 'generate' is not a valid view function or pattern name. -
Django can't acces media files, 404 Page not found
I recently started to learn Django but I'm still struggeling with accessing media files. My settings.py file includes the following: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/ My urls.py in the project directory contains the following. urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls')) ] if st.DEBUG: urlpatterns += django_Static(st.MEDIA_URL, document_root=st.MEDIA_ROOT) When I then try to load an image via a GET request I get the following message: " Page not found (404) ... Using the URLconf defined in ecommerce_project.urls, Django tried these URL patterns, in this order: admin/ [name='store_homepage'] ^media/(?P<path>.*)$ The current path, media/product_pictures/256132756_922283745365869_1303861998719790800_n.jpg, matched the last one. I really don't know what to do since I tried everything. Has someone also stumbled accross this problem? -
limit number of foreign key using Django CheckConstraint
I am using Django 4.1 and Postgresql and as stated in their documentation CheckConstraint accept Q object and Expression. Based on https://code.djangoproject.com/ticket/31646, I thought my solution would work, but when calling makemigrations nothing happens (Count inherit from Func). Goal: I would like to limit the number of Messages per Discussion. I did see a solution using a validators on the ForeignKey field but it is not robust (see Limit number of foreign keys). I would prefer not to have to create a SQL function and calling it (would like a Django solution only). from django.core.exceptions import ValidationError from django.db import models from django.db.models.lookups import IntegerLessThan class Discussion(models.Model): MAX_MESSAGES = 10 class Message(models.Model): discussion = models.ForeignKey( "discussion.Discussion", models.CASCADE, related_name="messages", ) constraints = [ models.CheckConstraint( name="limit_discussion_messages", check=IntegerLessThan( models.Count("discussion", filter=models.Q(discussion=models.F("discussion"))), models.Value(Discussion.MAX_MESSAGES), ), ), ] -
Getting null value in column "userId_id" of relation "pnrDB_run when sending a POST to django backend
Still very new to Django. I'm trying to send a post request to my backend from insomnia right now and I'm getting the error Getting null value when I'm passing in the ID value. Here is my seralizer: class RunSerialzer(serializers.HyperlinkedModelSerializer): gameId = GameSerialzer( read_only = True ) userId = UserSerialzer( read_only = True ) class Meta: model = Run fields=('id','name','isComplete','deaths','badges','userId','gameId') My view: class RunList(generics.ListCreateAPIView): queryset = Run.objects.all() serializer_class = RunSerialzer And my request I'm making: { "gameId":1, "userId": 1, "name":"testrun2", "deaths":0, "badges": 0, "isComplete": false } and the second one I tried { "gameId": { "id": 1, "name": "Vintage White", "photo": "https://archives.bulbagarden.net/media/upload/thumb/0/08/White_EN_boxart.png/250px-White_EN_boxart.png" }, "userId": { "id": 1, "name": "TestUser" }, "name":"testrun2", "isComplete": false, "deaths": 0, "badges": 0 } I feel like I need to create either a new Serailizer to get the instance I want in my Game model with the pk im passing in the request -
Django wrong imagefield.path
i have a model with an image field like this app_icon = models.ImageField(upload_to='icons/') the project has 'uploads' as media folder, which has subfolders, including 'icons'. The image is correctly uploaded to the 'icons' subfolder but when i try to access it using self.app_icon.path it returns .../uploads/imagename.jpg instead of .../uploads/icons/imagename.jpg so i get file not found error. Even the url doesn't include the 'icons' subfolder my settings: MEDIA_URL = '/uploads/' MEDIA_ROOT = BASE_DIR / 'uploads/' i can't find any answer to this problem, which seems so random to me. -
how to make models for user auth(use abstract user) for login and signup using django?
how to make models for user auth(use abstract user) for login and signup using Django? I want to make login OTP based for ecommerse website. from django.db import models class User(models.Model): first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) mobile = models.CharField(max_length=10) address = models.CharField(max_length=200) emailId = models.CharField(max_length=50) password = models.CharField(max_length=200) I tr above code. What should I have to add above? -
Count elements in Django
I am learning Django. I have a question about counting elements from tables. class Opinion(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) users = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) books = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) rate = models.IntegerField() description = models.TextField() def __str__(self): return self.user_id.username + ' ' + self.book_id.title My table Opinion is in relationship with built-in table User. I am wondering how can I count how many opinions each user has added? I would like to show information about users and the amount of opinions they have added on my website. Thanks for the help. -
I am trying check if user is authenticated navigate to dashboard . There is no error in console and network. How can I fix this?
I am developing a authentication system using Django, DRF and Djoser in backend and React, reduxtool kit in front end. Every thing works perfectly fine exept mapStatToProps which provide isAuthenticated const mapStateToProps = (state) => ({ isAuthenticated: state.auth?.isAuthenticated, } doesn't work when I use it as if (isAuthenticated) { return <Navigate to="/dashboard" />; } to redirect page to dashboard in login.jsx. I don't why. Please help me to fix this bug. redux state in redux devtool shows { rootReducer: { auth: { access: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjYyMjAwMTM4LCJqdGkiOiJjMjY1OGE5YjM2MTg0NjMxYTRhOTNlYzNiNjZmNDc1MSIsInVzZXJfaWQiOjR9.rpBooY2zuHQE7ttl8DFjR3XSam3B6f55ZYMF_jQeyJc', refresh: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTY2MjI4MjkzOCwianRpIjoiODM2ZTA1OGVmMTU4NDUxN2I5ZDViNWExMGU1YThkZmMiLCJ1c2VyX2lkIjo0fQ.MzEIvO6vmEhJZ2v3_TZCC4k3gBaKEVeES4OzAaq9DBI', isAuthenticated: true, user: { email: 'ripyschool@gmail.com', id: 4, username: 'ripyschool' } } } } #my loginpage import React, { useState } from "react"; import { Link, Navigate } from "react-router-dom"; import { connect } from "react-redux"; import { login } from "../actions/auth"; import axios from "axios"; import style from "../assets/styles/Login.module.css"; import { FaGoogle } from "react-icons/fa"; import { FaGithub } from "react-icons/fa"; import FormLayout from "../hocs/FormLayout"; const Login = ({ login, isAuthenticated }) => { const [formData, setFormData] = useState({ username: "", password: "", }); const { username, password } = formData; const onChange = (e) => setFormData({ ...formData, [e.target.name]: e.target.value }); const onSubmit = (e) => { e.preventDefault(); login(username, password); }; const continueWithGoogle … -
Django Pycharm Process finished with exit code -1
Recently when i run Django project server on 0.0.0.0 port 8000 (I should run on 0.0.0.0 instead of 127.0.0.1) randomly in some requests return this error and kill the process(completely random). Process finished with exit code -1 And after reload, on first request give save error I use window 10 and Pycharm v 2021.2.2 it seems it's bug of Pycharm. Because there is no problem when deploy on the server -
AttributeError: 'WSGIRequest' object has no attribute 'get' I got this error earlier and I didn't find my answer here
I am going through a django course and I got this error earlier but the tutor doesn't !!! what should I do ??? this is my code below views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponse from .models import Project from .forms import ProjectForm def projects(request): objs = Project.objects.all() context = {"projects": objs} return render(request, 'projects/project.html', context) def dynamic(request, text): obj = Project.objects.get(id=text) return render(request, 'projects/single-project.html', {'obj': obj}) def createproject(request): form = ProjectForm() context = {'form': form} return render(request, 'projectform.html', context) models.py from django.db import models import uuid class Project(models.Model): title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) demo_link = models.CharField(null=True, blank=True, max_length=2000) source_link = models.CharField(null=True, blank=True, max_length=2000) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) tag = models.ManyToManyField('Tag', blank=True) total_vote = models.IntegerField(default=0, null=True, blank=True) vote_ratio = models.IntegerField(default=0, null=True, blank=True) def __str__(self): return self.title class Review(models.Model): VOTE = ( ('up', 'Up Vote'), ('down', 'Down Vote'), ) project = models.ForeignKey(Project, on_delete=models.CASCADE) body = models.TextField(null=True, blank=True) value = models.CharField(max_length=200, choices=VOTE) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.value class Tag(models.Model): name = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.name forms.py from django.forms import ModelForm … -
GiltLab CI/CD Django tests failing
I want to run some tests on Gitlab with CI/CD with a Django project. The tests on my local pc work fine, my job test pipeline is always failing with those tests. I get a SyntaxError. Here the script failure I get in the pipeline when the tests failed : Running with gitlab-runner 15.3.0~beta.42.gdb7789ca (db7789ca) on blue-3.shared.runners-manager.gitlab.com/default zxwgkjAP Preparing the "docker+machine" executor 00:06 Using Docker executor with image ruby:2.5 ... Pulling docker image ruby:2.5 ... Using docker image sha256:27d049ce98db4e55ddfaec6cd98c7c9cfd195bc7e994493776959db33522383b for ruby:2.5 with digest ruby@sha256:ecc3e4f5da13d881a415c9692bb52d2b85b090f38f4ad99ae94f932b3598444b ... Preparing environment 00:01 Running on runner-zxwgkjap-project-39068925-concurrent-0 via runner-zxwgkjap-shared-1662191947-427cb239... Getting source from Git repository 00:02 $ eval "$CI_PRE_CLONE_SCRIPT" Fetching changes with git depth set to 20... Initialized empty Git repository in /builds/XXX/Deploy_django_application_to_server/.git/ Created fresh repository. Checking out 51c8456f as master... Skipping Git submodules setup Executing "step_script" stage of the job script 00:01 Using docker image sha256:27d049ce98db4e55ddfaec6cd98c7c9cfd195bc7e994493776959db33522383b for ruby:2.5 with digest ruby@sha256:ecc3e4f5da13d881a415c9692bb52d2b85b090f38f4ad99ae94f932b3598444b ... $ echo "Running unit tests..." Running unit tests... $ python manage.py test app_users.tests.CustomUserTests File "manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax Cleaning up project directory and file based variables 00:00 ERROR: Job failed: exit code 1 *the script of my .gitlab-ci.yml is : stages: # List of stages for jobs, and … -
How to integrate scikit-ExSTraCS with my Django application
I'd like to use https://github.com/UrbsLab/scikit-ExSTraCS's features in my application, but I've discovered that it lacks REST interfaces. This is okay because I can easily create Django REST APIs for scikit-ExSTraCS' classes, but I'm hoping someone here has some experience with this or knows of a package that already handles it. -
Enviroments variables and migrations not working in django
I have following problem. I, starting app with structure like this: In env_vasr.sh I want to keep all the credentials etc. I source this file and variables are in env. However, when I run django-admin migrate, I get the following problem: Can anyone tell me what is the problem please. ├── eMenue │ ├── eMenue │ │ ├── asgi.py │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-310.pyc │ │ │ └── settings.cpython-310.pyc │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── eMenueApp │ │ ├── admin.py │ │ ├── apps.py │ │ ├── __init__.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── tests.py │ │ └── views.py │ └── manage.py ├── env_vars.sh ├── global_settings.json ├── requirements.txt This the output from the django-admin migrate command: With hardcoded values it worked fine. However, I created ne project after to add env variables from file. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/michal/devel/eMenue/venv/bin/django-admin", line 8, in <module> sys.exit(execute_from_command_line()) File "/home/michal/devel/eMenue/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/michal/devel/eMenue/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/michal/devel/eMenue/venv/lib/python3.10/site-packages/django/core/management/base.py", line 415, in … -
saving value in session but not able to retreive in future api calls
I am not much ware about how django sessions works and how does it communicate with frontend technologies like vue.js I have a project setup in django from backend and vue.js for frontend request.session['session_user_id'] = serializer.entity.owner.id using this code I am saving the user_id in session and trying to retrieve the this session user_id in future API calls but I am getting None request.session['session_user_id'] giving None Can anyone help me or explain in doing this in a correct way or finding a better approach ?