Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ensure one type of user cannot log in as another type of user django
In Django, how can I make sure that one type of user cannot log in as another type of user? For example, if there are two types of users on my website, teachers and students, teachers should not be able to use their credentials to log in as a student and vice versa. -
useEffect is causing an infinite loop but i cant find why. Also what can i improve in the code
I made basic blog like project with django rest api and react in frontend but useEffect is causing an infinite loop but i cant find why.I know its the useEffect because it happened few times before while making this project but i was able to fix it but now it has been a bit hard. Also a side question what do u guys think of the code any tip or advice will be appreciated, thanks. import React, { useState, useEffect } from 'react'; import './App.css'; const App = () => { const [posts, setPosts] = useState([]) const [editing, setEditing] = useState(false) const [editData, setEditData] = useState([]) const [create, setCreate] = useState({ title: "", description: "", completed: false }) const handleCreate = ((e) => { const newData = {...create} newData[e.target.id] = e.target.value setCreate(newData) }) const handleEdit = ((post) => { setCreate({ title: post.title, description: post.description, }) {setEditing(true)} {setEditData(post)} }) const handleDelete = ((post) => { fetch(`http://127.0.0.1:8000/api/post-delete/${post.id}`, { method: 'DELETE', headers: { 'Content-Type': 'application/json', } }) console.log(post.id) }) const handleSubmit = ((e) => { e.preventDefault() var url = 'http://127.0.0.1:8000/api/post-create/' if (editing == true) { url = `http://127.0.0.1:8000/api/post-update/${editData.id}` } fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(create) }) .then(setCreate({ title: … -
django ecommerce product db design
I designed a database for my django ecommerce project but it have some problems, the goal of the this design is to have products with different specifications for example a mobile cell has it's own properties and a television too, it is my models.py: ''' from django.db import models from mptt.models import MPTTModel, TreeForeignKey from django.shortcuts import reverse from model_utils import FieldTracker from . import uploaders class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') slug = models.SlugField(max_length=75, unique=True) tracker = FieldTracker(fields=['name']) class MPTTMeta: order_insertion_by = ['name'] def __str__(self): category_names = [self.name] node = self while node.parent: node = node.parent category_names.append(node.name) return ' / '.join(category_names[::-1]) def get_absolute_url(self): return reverse('product_by_category', args=(self.slug,)) class ProductType(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class ProductSpecifications(models.Model): name = models.CharField(max_length=50) product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE, related_name='specifications') class Meta: unique_together = ('name', 'product_type') def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=100, unique=True) product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE, related_name='products') category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products') price = models.PositiveBigIntegerField() discount_price = models.PositiveBigIntegerField(null=True, blank=True) description = models.TextField(null=True, blank=True) image = models.ImageField(upload_to=uploaders.product_img_uploader) slug = models.SlugField(max_length=150, unique=True) tracker = FieldTracker(fields=['slug', 'name', 'product_type']) def __str__(self): return self.name def set_discount(self, percentage): self.discount_price = self.price * (1 - percentage) self.save() @property def … -
Django Rest Framework - Serializer create_or_update giving IntegrityError: Unique Constraint Failed
I am having an issue when using the API to send an update to an existing record. When I send the API for a new record, it works perfectly. But when I send it for an existing record, I would like it to update the current record, but it just gives me an integrity error instead. My Serializers.py looks like this: class PartSerializer(serializers.ModelSerializer): part = serializers.CharField() class Meta: model = DocumentRef fields = ('part', 'field1', 'field2', 'field3') def create(self, validated_data): part = Part.objects.get(part_number=validated_data['part']) validated_data['part'] = part return DocumentRef.objects.create_or_update(**validated_data) I have tried changing create_or_update to just create or just update but it will still only work if the record does not exist yet. The model it should be referencing is DocumentRef, which looks like this: class DocumentRef(models.Model): part = models.OneToOneField(Part, on_delete=models.CASCADE) field1 = models.FileField(upload_to='mcp/') field2 = models.FileField(upload_to='qcp/') field3 = models.FileField(upload_to='cus/') The API View I am using is this: class APIDetailTest(APIView): def get_object(self, pk): try: return DocumentRef.objects.get(pk=pk) except DocumentRef.DoesNotExist: return HttpResponse(status=status.HTTP_404_NOT_FOUND) def get(self, request, pk): part = self.get_object(pk) serializer = PartSerializer(part) return Response(serializer.data) def put(self, request, pk): part = self.get_object(pk) serializer = PartSerializer(part, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django validators - selected check boxes
Here is my form in django: class CarPurchase(forms.Form): name = forms.CharField(label="Car name") brand = forms.CharField(label="Brand") color = forms.DateField(label="Color") payment_possibilities = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple ) The payment_possibilities is a group of checkboxes where user can choose the ways he is open to pay with. I want him to choose at least one option here, but he can also choose more of them. I want to validate this by django validators. Is there any way I can tell django to get the number of selected checkboxes? I was already thinking about this implementation: payment_possibilities = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple, validators=[validate_payment] ) def validate_payment(value): ... but this for the first didn't seem to be the right approach and I also left unsure about how to access that number of check boxes selected. -
Remove nesting from ModelSerializer
I'm trying to add routes to GET and PUT the status of a ticket. class ReturnLabelTicket(models.Model): status = models.CharField(choices=...) class ReturnLabelTicketStatusSerializer(serializers.ModelSerializer): """Serializer of a return label ticket status.""" status = serializers.ChoiceField(ReturnLabelTicket.StatusChoice.choices) def to_internal_value(self, data): """Take the whole data value as the status.""" return super().to_internal_value({'status': data}) def to_representation(self, instance): """Return the status string.""" return instance.status def update(self, instance, validated_data): """Update the ticket status.""" instance.status = validated_data.get('status', instance.status) instance.save() return instance class Meta: model = ReturnLabelTicket fields = ['status'] By default this serializer expects the JSON to be of the form { 'status': '...' }, but I want to remove the status key and use the value directly. My to_internal_value works fine, but when I remove the nested status in to_representation I end up with an error at ticketing-service | File "/opt/app-root/lib64/python3.9/site-packages/rest_framework/serializers.py", line 549, in data ticketing-service | return ReturnDict(ret, serializer=self) ticketing-service | File "/opt/app-root/lib64/python3.9/site-packages/rest_framework/utils/serializer_helpers.py", line 18, in __init__ ticketing-service | super().__init__(*args, **kwargs) ticketing-service | ValueError: need more than 1 value to unpack This is the relevant section of my ReturnLabelTicketViewSet. @action( detail=True, url_path='status', serializer_class=ReturnLabelTicketStatusSerializer ) def status(self, _request, ticket_id=None): """Retrieve the ticket status.""" ticket = self.get_object() serializer = self.get_serializer(ticket) return Response(serializer.data) -
Why does my django web application not load for my graphs that I have on kubernetes?
I have a Django web application that can display forecasts graphs using the machine learning library Sktime and the library plotly for graphs. It runs fine on my local machine. However, when I run it on kubernetes it doesn't load. The web page just stays forever loading. I have tried changing my yaml's resource files by increasing cpu and memory to "2000m" and "1000mi", respectively. Unfortunately that does not fix the problems. Right now the way I run my application is by using the minikube command, "minikube service --url mywebsite". I don't know whether its the way I run it or my yaml file. Does anyone know? My yaml file is provided. apiVersion: v1 kind: Service metadata: name: mywebsite spec: type: LoadBalancer selector: app: mywebsite ports: - protocol: TCP name: http port: 8743 targetPort: 8000 --- apiVersion: apps/v1 kind: Deployment metadata: name: mywebsite spec: selector: matchLabels: app: mywebsite template: metadata: labels: app: mywebsite spec: containers: - name: mywebsite image: mywebsite imagePullPolicy: Never ports: - containerPort: 8000 resources: requests: cpu: 200m memory: 100Mi limits: memory: "1Gi" cpu: "200m" -
How to prevent Django from making page history
Hello I have a problem I made sorting system in Django. The problem is this system takes the last input of user. When user go back to the previous page and use there sorting method, it sorts items which he has chosen lately, not these which he sees. Is there any way to prevent django from this? Like when i have /localhost/search when it returns it should return to the /localhost not to the previous /localhost/search? I would be pleased if you have any ideas to do it better in pure Django. search_history = [] def searchView(request): if request.method == "POST": context = request.POST.get('search') if not context: context = search_history[-1] search_history.append(context) items = Item.objects.all().filter(title__icontains=search_history[-1]) try: sorting_method = request.POST.get('select') if sorting_method == 'v1': items = items.order_by('price') return render(request, 'shop/search.html', {'items': items}) if sorting_method == 'v2': items = items.order_by('-price') return render(request, 'shop/search.html', {'items': items}) else: return render(request, 'shop/search.html', {'items': items}) except UnboundLocalError: return redirect('home-page') -
Got AttributeError when attempting to get a value for field `complex` on serializer `RegisterResidenceSerializer`
class Complex (models.Model): country = models.CharField(max_length=2, choices=COUNTRY_CHOICES, default='') city = models.CharField(max_length=100, default='') street = models.CharField(max_length=100) class Residence(models.Model): complex_id = models.ForeignKey(Complex, on_delete=models.DO_NOTHING, related_name='complex') house_number_extension_1 = models.CharField(max_length=100) I created two models Complex and Residence and I want to join them together serializers.py class RegisterComplexSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Complex fields = ['country', 'city', 'street'] class RegisterResidenceSerializer(serializers.HyperlinkedModelSerializer): complex = RegisterComplexSerializer() class Meta: model = Residence fields = ['house_number_extension_1', 'complex'] In the serializers.py, I wrote this code views.py class RegisterResidenceViewSet(viewsets.ModelViewSet): serializer_class = RegisterResidenceSerializer queryset = Residence.objects.all() In the serializers.py, I wrote this code but when I try to run my code I get this error: Got AttributeError when attempting to get a value for field complex on serializer RegisterResidenceSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Residence instance. Original exception text was: 'Residence' object has no attribute 'complex'. Can anyone help me? -
Creating staff users with a checkbox (booleanfield)
I am making a blog style website, and for the register form, I decided I want to add a checkbox that says 'I'm a staff member' so that if the form is submitted with this box checked said user is registered as a staff member instead of just a normal staff member. I know this isn't very secure but in my specific case it would work very well. I know I could do this by creating a different form only for staff members but I really want to do it with the checkbox. So, the checkbox is there, how can I make it check if it's checked or not to make a staff user? ANY kind of help is greatly appreciated. Here is my code: forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField( label= 'Correo Electrónico', required=True, ) username = forms.CharField(max_length=100, required=True, label='Nombre de Usuario') password1 = forms.CharField( label = "Contraseña", required=True ) password2 = forms.CharField( label = "Confirmar Contraseña", required=True ) is_teacher = forms.BooleanField( label='Soy profesor/a', required=True, ) class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'is_teacher'] views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Tu cuenta se ha … -
How to use CKEDITOR in Django template without Django form and save data
How to use CKEDITOR in Django template without modelform and save data. -
How to update form feild values based on condition in django
Here let us consider my batch number as 145789 if user is admin update the batch number and if user is not admin it should be readonly feild Let us consider my forms.py as class JobItemHorticlutureUpdateForm(BetterModelForm): image = forms.ImageField(label=('Image'),required=False, error_messages = {'invalid':("Image files only")}, widget=forms.FileInput) def __init__(self, *args, **kwargs): super(JobItemHorticlutureUpdateForm, self).__init__(*args, **kwargs) client = kwargs.get("initial", {}).get("client") user = kwargs.get("initial",{}).get("user") if not user.is_admin: self.fields["batch_number"].widget.attrs['readonly'] = True self.fields['quantity'].required = False self.fields['height'].required = False self.fields['girth'].required = False def clean_quantity(self): instance = getattr(self, 'instance', None) if instance and instance.pk: return instance.quantity else: return self.cleaned_data['quantity'] class Meta: model = JobItems exclude = ('created_by', 'client', 'is_deleted', 'is_checked', 'status') widgets = { "supplier_one": forms.TextInput, "supplier_two": forms.TextInput, "supplier_three": forms.TextInput, "supplier_four": forms.TextInput, "supplier_five": forms.TextInput, "supplier_six": forms.TextInput, "item_file":forms.FileInput, } fieldsets = [ ["main", { "fields": ['item_name', 'common_name','batch_number'], "legend": "Main details", }], ["extra", { "fields": ['girth','height', 'quantity'], "legend": "Additional details", }], ] let us consider my views.py as class JobItemUpdateView(CustomAuthMixin, UpdateView): model = JobItems form_class = JobItemHorticlutureUpdateForm context_object_name = "items" template_name = "jobs/jobitem_form.django.html" def get_initial(self): self.client = self.request.user.client self.user = self.request.user get_params = self.request.GET.copy() pricelist = get_params.pop('price_list', [0])[0] initial = super(JobItemUpdateView, self).get_initial() initial['client'] = self.request.user.client initial['created_by'] = self.request.user initial['user'] = self.request.user return initial def get_queryset(self): client = self.request.user.client return self.model.objects.filter(client_id=client).exclude(is_deleted=True) def … -
How can I run a local Django dev server with SSL using a .local domain?
I have a Django site that uses cross-site requests between subdomains. In order for this to work, I need FQDNs and SSL during local development. I'm using dnsmasq to resolve .local domains, and runserver_plus to run on HTTPS: ./manage.py runserver_plus --cert=/tmp/mysite.cert But when I go to https://mysite.local:8000, I get a certificate error in the browser: ERR_CERT_AUTHORITY_INVALID Is there any way to develop locally with a valid certificate? -
Getting an empty query set Django
I'm trying to develop a search functionality but only getting a empty query set every single time . class SearchView(TemplateView): template_name = "search.html" def get_context(self, **kwargs): context = super().get_context(**kwargs) kw = self.request.GET.get("search") results = Thread.objects.filter(Q(heading__icontains=kw) | Q(thread_content__icontains=kw)) print(results) context["results"] = results return context Template {% extends 'base.html' %} {% block title %}Search{% endblock %} {% block content %} <div class = "container"> <div class = "row"> <div class = "col-md-12"> <h3>Search results for <span class="text-info">"{{ request.GET.search }}"</span></h3> <h3>{{results}}</h3> <hr> {% for item in results %} <div class="col-md-4"> <img src = "{{item.image.url}}" class="img-fluid" alt = ""> </div> <div class="col-md-8"> <h4>{{item.heading}}</h4> <p>{{item.thread_content}}</p> </div> {%endfor%} </div> </div> </div> {% endblock %} request.GET.search is returning correctly , but the rest is not getting displayed -
Calling api by definition in django
I have an api setup to a url to be able to call with a bearer token {base_url}/iterations.json. I am wondering if I can somehow call a nested value from this that is not appearing on my original api. To explain more: My url links to a viewset. This viewset appears as: class ChannelViewSet(CustomViewset): filterset_class = ChannelFilterSet def get_serializer_class(self): if self.action == 'list': return ChannelListItemSerializer elif self.action == 'retrieve': return ChannelSerializer raise ValueError(self.action) def get_queryset(self): if not self.request: return ChannelModel.objects.none() qs = ChannelModel.objects.available_for_user(self.request.user).order_by( *telegram_conf.CHANNEL_ORDERING_DEFAULT ) # user subscription date filter subscription_datetime = self.request.user.get_api_subscription_time() if subscription_datetime is not None: qs = qs.filter(created__gte=subscription_datetime.timestamp()) return qs The Channel model does not contain the data I want, but the channel serializer does as a function, which then returns a value 'links' def get_links(self, obj): return [ self.link_serializer.to_representation(link) for link in ChannelLink.objects.filter(channel=obj.pk) ] When I am calling my api I cannot see the links field, but is there a way to somehow call the links item from the serializer through the api? This is for our clients who don't have access to the website code directly, so it needs a URL. Will we have to change the code to add the field to the final … -
Sequential celery task execution
I have a heavy celery task that parses data from XML files to the DB and sometimes I'm having troubles with media files because of celery tasks running multiple parsers, which I don't need. So I want to know is there any way to do this sequentially? I mean I need some kind of delay after every successful parsing or something like that. -
How to refresh cached queryset for specific situations
I have a django application using redis as a cache, everything works fine, except in my views where I use some kind of filter, my logic is: I have a form for filter fields, when the user fills them in and clicks a submit button I I process the filters in the post method, in this case I get the return of the cached query and not the applied filter. How can I force refresh or correctly use the logic for filtering in these cases? -
Pycharm $python3 manage.py runserver issue
I'm trying to learn about the Django framework and I've started by running a project. I seem to have some trouble on Pycharm: PyShop1 % $python3 manage.py runserver When I input this it outputs: zsh: command not found: manage.py Can someone help me rectify the issue, as I can't seem to find the solution to this anywhere. I definitely have a manage.py file, as I can see it on the Project section of PyCharm. Also If it helps I'm using MacOS -
First setting Session in POST request Django, but not able to see session id in GET request for same project
def funcpost(request,format=None): if request.method=="POST": y=request.POST[" FirstName"] x=request.FILES['LastName'] request.session['name'] = y def funcget(request,format=None): if request.method=="GET": x1=request.session.get("name") print(x1) -
Django Watchtower connection refused when running server localhost
I am using Django [watchtower][1] to log events to Cloudwatch and have configured my logging in my settings file. development.py boto3_session = Session( aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, region_name=AWS_REGION) LOGGING = { 'version': 1, 'disable_existing_loggers': False, # 'root': { # 'level': 'INFO', # 'handlers': ['console'], # }, 'formatters': { 'simple': { 'format': "%(asctime)s [%(levelname)-8s] %(message)s", 'datefmt': "%Y-%m-%d %H:%M:%S" }, 'aws': { # you can add specific format for aws here 'format': "%(asctime)s [%(levelname)-8s] %(message)s", 'datefmt': "%Y-%m-%d %H:%M:%S" }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'watchtower': { 'level': 'INFO', 'class': 'watchtower.CloudWatchLogHandler', 'boto3_session': boto3_session, 'log_group': 'StagingBeagleApi', 'stream_name': 'ApplicationLogStream', 'formatter': 'aws', }, }, 'loggers': { 'django': { 'level': 'INFO', 'handlers': ['watchtower'], 'propagate': True, }, }, } However when I run my server, I don't get any error in the console but my site is not accessible anymore via locahost:3000, I get an ERR_CONNECTION_REFUSED Please help! [1]: https://pypi.org/project/watchtower/ -
Get user object from token string in DRF Token In Django using Knox Token
I have question related with Django . I am using Knox Token Authentication to generate tokens for every user when he log in on the page. Now I want to use that token for every request that will send so I can get the corresponding user for the token. Also I am using custom function example def dashboard(request) in Django for every URL route. I have see on youtube that there are option to get user from token but is not with functions class UserAPI(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserSerializer def get_object(self): return self.request.user So is there a whey to get the corresponding user from a token within a custom function -
Django model string representation
I know that a model object string representation can be achieved by adding class Company(models.Model): name = models.CharField() email = models.EmailField(unique=True) def __str__(self): return self.name But this is the representation of an object of Company but not the model class itself. Meaning if I create an object obj = Company(name='string_repr', email='example@example.com') print(obj) would result in 'string_repr' which is as expected since Im getting the string representation of the object, not the class/ model. However I noticed that during a CreateView form validation in case if there already is an object of the model with the same email Django returns an error message that the there already is a Company with such an email (picture is not in English but the underlined section is the only relevant part). I suppose the error message is taking the class name and inputting it in the message, but is there a way how to alter the string representation of the model (class) name? Its needed for translation purposes. I guess I could just rename the class names to local language but that doesn't seem right. -
How to effficiently get count of foreign keys in Django model?
I have three models like this: class House(models.Model): name = models.CharField(max_length=150) def get_house_count(self): fetchs = 0 for fetch in self.fetchs.all(): fetchs += 1 return fetchs class Person(models.Model): house = models.ForeignKey(House, related_name="persons", on_delete=models.PROTECT) first_name = models.CharField(max_length=150) def get_person_count(self): person_fetchs = 0 for fetch in self.person_fetchs.all(): person_fetchs += 1 return person_fetchs class Fetch(models.Model): number = models.CharField(max_length=150) house = models.ForeignKey(Hourse, related_name="fetchs") person = models.ForeignKey(Person, related_name="person_fetchs") What I want to achieve is to get the total number of each model instance in the Fetch class. But this operation is very expensive(over 500 duplicates) as it creates multiple SQL duplicates when I use the django_debug_tool library. Is there an efficient way to do this? My view.py file is like this: class HomeView(ListView): queryset = Fetch.objects.select_related( 'house', 'person', ) template_name = "index.html" paginate_by = 100 And in my template I have something like this: {% for obj in object_list %} <tr> <td>{{ obj.company.name }}</td> <td>{{ obj.house.get_house_count }}</td> <td>{{ obj.person.get_person_count }}</td> I have also tried to use the django's annotate method like this: queryset = Fetch.objects.select_related( 'house', 'person', ).annotate( get_count=Count('house', distinct=True), get_contact_count=Count('person', distinct=True) ) while making changes to my template using {{obj.get_count}} and {{obj.get_contact.count}} respectively. But it returns a count of 1 which is wrong. Any help … -
How can I add translate attribute in the below code. I am gonna provide translation in .po file
<th rowspan="2" class="text-center">a1</th> <th rowspan="2" class="text-center"> a2</th> <th rowspan="2" class="text-left">a3</th> <th rowspan="2" class="text-center">a4</th> How can I add translate attribute in the below code. I am gonna provide translation in .po file. -
I keep getting this error ModuleNotFoundError: No module named 'template'
I keep getting the error ModuleNotFoundError: No module named 'template'. I have no idea what to do or where this error is coming from. I think it might be coming from the setting file but I do not know what to change. If anyone knows how to fix this your help would be much appreciated. I have the error and my settings file down below. Error: Traceback (most recent call last): File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\commands\runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\conf\__init__.py", line 82, in __getattr__ self._setup(name) File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\conf\__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\conf\__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2032.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\conf\__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\conf\__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2032.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, …