Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form request method is always GEatedT, even method=“POST” is mentioned in HTML template
Views.py Html filepng please help with this question!!! Thanks!! -
Get unique outputs from combining more than one Django filters
So, I am trying to create a search engine on my website where the user enters a query and I display those results where the query exists inside the product name or description. My product model is as follows:- '''Product model to store the details of all the products''' class Product(models.Model): # Define the fields of the product model name = models.CharField(max_length=100) price = models.IntegerField(default=0) quantity = models.IntegerField(default=0) description = models.CharField(max_length=200, default='', null=True, blank=True) image = models.ImageField(upload_to='uploads/images/products') category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1) # Foriegn key with Category Model store = models.ForeignKey(Store, on_delete=models.CASCADE, default=1) Now, I have created a search filter where I filter by name and then by description and then combine the results to return a queryset. The issue is that sometimes the query can be found in names and in descriptions so I get repeated entries like this My filtering code is mentioned below:- names = queryset.filter(name__icontains=search_query) descriptions = queryset.filter(description__icontains=search_query) queryset = list(chain(names, descriptions)) return Response(ProductSerializer(queryset, many = True).data) I want to be able to only get one result since it's the same product. Is there a way I can only save the distinct results in query set. I made a loop which checks the results in descriptions … -
Python+Django : Bug in code looking for a 2nd insight
I have a function with the following code: if request.method == 'POST': company_id = request.POST.get('company_id') choice_list = request.POST.getlist('info[]') response = read_csv_lines(choice_list,company_id) print(response) choice list contains numbers selected in a list. For example [2,3] and the ID of a dropdown box This one goes to the following function (read_csv_lines) def read_csv_lines(my_list,company_id): test_file = './upload.csv' company = Company.objects.get(id=company_id) with open(test_file) as csv_file: file_reader = list(csv.reader(csv_file, delimiter=';')) for i in my_list: i = int(i) deviceinf = file_reader[i] status = add_device(deviceinf,company.auth_token,company.company_name) I get the info from the company cause i need these to make an api call in a seperate function i open the file read every line but all lines in a list and for the value i I read the line in the list of read lines. And pass this trough to my API call. What happens next is the bug. When i launch a POST the following thing happens: It enters the read_csv_lines. jumps right back out and print as response "None" but the other calls keep on going and the api call in the background executes Could someone look into this as a 2nd opinion ? -
Django Authentication Pblm
Eg : If A user append in his/her list then it is reflecting in B user as well from django import forms from django.forms import ModelForm,TextInput from .models import * class TaskForm(forms.ModelForm): title= forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Task title...'}), label=False) due= forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Due date...'}), label=False) class Meta: model = task fields = ['title', 'due'] class UpdateForm(forms.ModelForm): title= forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Task title...'})) class Meta: model = task fields = ['title', 'due', 'complete'] -
How do i show a form list inside a form list
Front End <Form.List name='question_parts' key='question_parts'> {(fields, { add, remove }, { errors }) => ( <> {fields.map((field, index) => ( <Space key={field.key} direction='vertical' style={{ width: '450px' }} > <Form.Item key={`QuestionPart${index}`} > <Form.Item {...field} label={`Question Part ${index + 1} Description`} fieldKey={[field.fieldKey, 'part_desc']} name={[field.name, 'part_desc']} key={`part_desc${index}`} > <Input.TextArea rows={4} placeholder='Question Part Description' style={{ border: '1px solid black', width: 450 }} /> </Form.Item> <Form.List name='guided_answer' key='guided_answer' > {(fields, { add, remove }, { errors }) => ( <> {fields.map((field, index) => ( <Space key={field.key} direction='vertical' style={{ width: '450px' }} > <Form.Item key={`QuestionPart${index}`}> <Form.Item {...field} label={`Guided Answer ${index + 1}`} fieldKey={[field.fieldKey, 'model_ans']} name={[field.name, 'model_ans']} key={`model_ans${index}`} > <Input.TextArea rows={4} style={{ border: '1px solid black', width: 450, }} /> </Form.Item> <Form.Item {...field} label={`Guided Answer ${index + 1} Marks`} fieldKey={[ field.fieldKey, 'answer_mark', ]} name={[field.name, 'answer_mark']} key={`answer_mark${index}`} > <Input style={{ border: '1px solid black', width: 450, }} /> </Form.Item> <MinusCircleOutlined className='dynamic-delete-button' style={{ paddingLeft: '10px', position: 'absolute', top: '0%', right: '-5%', }} onClick={() => remove(field.name)} /> </Form.Item> </Space> ))} <Form.Item> <Button type='dashed' onClick={() => add()} icon={<PlusOutlined />} style={{ border: '1px solid black', width: '95%', }} > Add Guided Answers </Button> <Form.ErrorList errors={errors} /> </Form.Item> </> )} </Form.List> <Form.Item {...field} label={`Question Part ${index + 1} Marks`} fieldKey={[field.fieldKey, 'part_total_marks']} name={[field.name, 'part_total_marks']} … -
How do I create a model dynamically with introspection in django?
Hi want to create a database model using introspection. When I run introspection.get_table_description(cursor, 'someModeLName') the TableDoesNotExist(table) error is raised. Is this how to create a model or I got it completely wrong? -
Trouble in passing ManyToMany Queryset data via Ajax call to django template
I have two Models classes class Dishes(models.Model): dishName=models.CharField() class Hotels(models.Model): hotelname=models.CharField() dishes = models.ManyToManyField('Dishes') In views.py def check_dishes(request): HotelId = request.GET.get('Id', None) hotelObj = Hotels.objects.get(pk=HotelId ) dishesObj= hotelObj.dishes.all() data = { 'HotelName': hotelObj.hotelname } Dlist=[] for dish in dishesObj: Dlist.append(dish.dishName) data.update([ ('dishes_list', Dlist), ]) print(data) *** output as below {'HotelName': 'DeMart', 'dishes_list': ['pizza','burger']}*** return JsonResponse(data,safe=False) In hotels.html we have an ajax call like $("#getHotelDishes").keyup(function () { $.ajax({ url: "{% url 'check_dishes' %}", dataType: 'json', data: { "hotelId": Id }, // on success success: function (data) { {% for dishes in data.dishes_list%} //print dish Names of this Hotel {% endfor %} }, // on error error: function (response) { console.log(response.responseJSON.errors) } }) }); Is this the right way to pass Queryset data via Ajax call,I could not get any result in for loop -
AttributeError: module 'accounts.serializers' has no attribute 'TokenSerializer'
This code I used in my previous projects and this works fine but now I am using this in my another project and this giving me this error on terminal while running AttributeError: module 'accounts.serializers' has no attribute 'TokenSerializer' If I comment out this line from settings.py REST_AUTH_SERIALIZERS = {"TOKEN_SERIALIZER": "accounts.serializers.TokenSerializer"} then there is no error and everything works fine. Now I am confused why this happening in current project while in previous project I was using the same version of django and rest framework with same backend code .... Is that going to be problem in the future if I kept commented out from settings.py ? requirements.txt ... dj-rest-auth==2.1.4 django-allauth==0.44.0 Django==3.2.3 django-cors-headers==3.7.0 django-environ==0.4.5 django-filter==2.4.0 djangorestframework==3.12.4 django_extensions==3.1.3 ... my code in settings... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.sites', ... 'accounts', 'frontend', 'rest_framework', #https://www.django-rest-framework.org/ 'rest_framework.authtoken', 'corsheaders', # To Connect API with React App if required in seprate apps 'allauth', #https://django-allauth.readthedocs.io/en/latest/installation.html 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth', 'dj_rest_auth.registration', 'django_extensions', 'debug_toolbar', #local usage ] # Auth user Settings AUTH_USER_MODEL = "accounts.User" # Configure django-rest-framework REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework.authentication.TokenAuthentication", "rest_framework.authentication.SessionAuthentication", ), "TEST_REQUEST_DEFAULT_FORMAT": "json", } REST_AUTH_SERIALIZERS = {"TOKEN_SERIALIZER": "accounts.serializers.TokenSerializer"} REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema' } # For django.contrib.sites SITE_ID = 1 # Configure django-allauth ACCOUNT_EMAIL_REQUIRED = True … -
ORDER BY not allowed in subqueries of compound statements; union queryset
I'm trying to create a listing page of all the questions posted that share the same type of tags a single user has used in their own questions. In other words, if a User has only posted questions about Python and OOP, they would only see questions that shared either one or both of those tags. Upon trying to implement this, I tried to use the .union() queryset to add the different filtered querysets together. However the following error is raised: ORDER BY not allowed in subqueries of compound statements. I found a similar issue raised here and it mentions how the method may be incompatible with SQLite which is the database I'm using: error "ORDER BY not allowed in subqueries of compound statements". In django while using Union function Is there another means of trying to overcome this error and getting the expected result that doesn't user the .union() queryset? models.py class Question(models.Model): title = models.CharField(max_length=50) body = models.TextField() dated = models.DateField(default=date.today) vote_tally = models.IntegerField(default=0) user_account = models.ForeignKey( 'users.UserAccount', on_delete=models.SET_NULL, null=True, blank=True, related_name="questions" ) tags = models.ManyToManyField(Tag, related_name='questions') objects = models.Manager() dateranges = DateRangeQuerySet.as_manager() status = QuestionStatusQuerySet.as_manager() class Meta: ordering = ['-dated'] default_manager_name = "objects" def __str__(self): return self.title … -
How to check for ACCESS_KEY_SECRET AND ACCESS_KEY_ID sent by an application and these credentials are also stored in the Application table
An application is sending an api post request with ACCESS_KEY_SECRET and ACCESS_KEY_ID in headers and other information in request body as i am not using any other authentication of DRF what i am doing is just simply matching the ACCESS_KEY_SECRET and ACCESS_KEY_ID of the api header to the ACCESS_KEY_SECRET and ACCESS_KEY_ID stored in Applicaion table, as i am new to python and django just want to check if i am doing it right. views.py @api_view(['POST']) def orderdetails(request): try: ACCESS_KEY_ID = request.META.get('HTTP_ACCESS_KEY_ID') ACCESS_KEY_SECRET = request.META.get('HTTP_ACCESS_KEY_SECRET') applications = Applications.objects.all() id=0 for e in applications: if(e.ACCESS_KEY_ID==ACCESS_KEY_ID and e.ACCESS_KEY_SECRET==ACCESS_KEY_SECRET ): id = e.id+id print(id) break else: return Response({"Message":"Enter Valid Credentials"}) except ValueError: return Response({"ACCESS":"DENIED"}) if request.method == 'POST': data=request.data print(data) orders = Orders(applications=Applications.objects.get(id=id), purpose_code = data['purpose_code'], amount=data['amount'], currency=data['currency'], note=data['note'], payer_name=data['payer_name'], payer_email=data['payer_email'], payer_phone_country_code=data['payer_phone_country_code'], payer_phone_number=data['payer_phone_number']) try: orders.full_clean() except ValidationError: return Response({"Error message":"invalid request body"}) else: orders.save() serializer = OrderSerializer(orders) order_id = serializer.data['id'] access_token = serializer.data['access_token'] content = {"orderId":order_id,"accessToken":access_token} return Response(content, status=status.HTTP_200_OK) else: content = {"Error message":"invalid request body"} return Response(content, status=status.HTTP_400_BAD_REQUEST) models.py class Applications(models.Model): id= models.AutoField(primary_key=True) code = models.CharField(max_length=100) name = models.CharField(max_length=100) ACCESS_KEY_ID = models.CharField(max_length=100) ACCESS_KEY_SECRET = models.CharField(max_length=100) webhook_Auth_Token = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True,auto_now=False) updated_at = models.DateTimeField(auto_now_add=False,auto_now=True) isActive = models.BooleanField(default=False) def __str__(self): return self.name -
What is the correct way to implement Django password history?
I have implemented a solution for checking a new password against the last 5 passwords like so: Created 5 fields in a user profile table to store the encrypted passwords On creating a new user, I stored the initial password in encrypted form in all the 5 fields On reset, I changed the views.py from Lib>django>contrib>auth directory from my virtual environment like so: def form_valid(self, form): #all initial code to get the keys etc goes here newpwd = form.cleaned_data['new_password2'] #get the unencrypted passwords from history p1 = cipher.decrypt(b64decode(user.pwd1)) p2 = cipher.decrypt(b64decode(user.pwd2)) p3 = cipher.decrypt(b64decode(user.pwd3)) p4 = cipher.decrypt(b64decode(user.pwd4)) p5 = cipher.decrypt(b64decode(user.pwd5)) #check if the password is already used and redirect with error message if newpwd == p1 or newpwd == p2 or newpwd == p3 or newpwd == p4 or newpwd == p5: messages.error(self.request, _('New Password should be different from old password')) return redirect('password_change') else: #store the password in the password history user.pwd5=user.pwd4 user.pwd4=user.pwd3 user.pwd3=user.pwd2 user.pwd2=user.pwd1 user.pwd1=newpwd user.save() form.save() messages.error(self.request,'Password Changed Successfully') return redirect('/user/login') form.save() # Updating the password logs out all other sessions for the user # except the current one. update_session_auth_hash(self.request, form.user) return super().form_valid(form) This works fine. But it feels incorrect editing the existing contrib>auth files like this. Is … -
How do I properly type annotate ForeignKey for Django Mixins?
I would like to use this solution to annotate mixins for models. So I need ForeignKey: from django.db import models class MultiplicatorMixin(models.Model): foo: models.ForeignKey def multiply(self, m: int) -> int: return self.foo.value * m Please note that foo: models.ForeignKey works. However, I want the type of the foreign key as well. So I need something like foo: models.ForeignKey[Foo]. Is it possible to also give the information to which type the foreign key belongs? -
django.db.utils.OperationalError: could not connect to server: Connection
I found a Django project and failed to get it running in Docker container in the following way: git clone https://github.com/hotdogee/django-blast.git $ cat requirements.txt in this files the below dependencies had to be updated: kombu==3.0.30 psycopg2==2.8.6 I have the following Dockerfile: FROM python:2 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ For docker-compose.yml I use: version: "3" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres dbi5k: image: postgres volumes: - ./data/dbi5k:/var/lib/postgresql/data environment: - POSTGRES_DB=django_i5k - POSTGRES_USER=django - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db links: - db I had to change: $ vim i5k/settings_prod.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } and $ vim i5k/settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'django_i5k', 'USER': 'django', 'PASSWORD': 'postgres', 'HOST': 'dbi5k', 'PORT': '5432', } } Unfortunately, I got this error: web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). web_1 | Unhandled exception in thread started by <function wrapper at 0x7f80449f4850> web_1 | Traceback (most recent call last): … -
Migrating Django app to use online media storage
I have a Django app running on a server. Currently user uploads are stored on the server filesystem. I already know how to set up S3 storage. What is the best way to migrate existing uploads to S3 without breaking the API and having existing uploads still available? These files are served to the front end in two ways: Directly through a /media/path/to/upload endpoint: /media/<path> django.views.static.serve Through a viewset: /api/v1/users/<user_pk>/items/<item_pk>/attachments/<pk>/ project.app.views.ItemAttachmentsViewSet Does the following make sense: Change the storage backend Go through all model objects Save each model object to get the files uploaded Have /media/path go to a new view that will serve the files similar to how ItemAttachmentsViewSet does it. ? Or is there a better way? -
Want to create unique and autofill the value of the model whenever user fill the form
here is my model.py class Product(models.Model): user = models.ForeignKey(User, null=True, blank=True,on_delete=models.CASCADE) coinid = models.CharField(max_length=255, unique = True, null=True) digit = models.CharField(max_length=18, unique = True, null=True) ctp = models.FloatField(max_length=100, null=True) transection_id = models.IntegerField(null=True, default=0) slug = models.SlugField(max_length=250, null=True, blank=True) date_created = models.DateField(auto_now_add=True, null=True) when the user fills the form which includes = coinid and ctp. I want Django to automatically fill Digit(unique) and user(logged in) fields for me when updated to the products table. here is my form.py class CreateProduct(ModelForm): class Meta: model = Product fields = ['user','coinid', 'ctp'] exclude = ['user'] views.py def createProduct(request): user_id = request.user.customer form = CreateProduct(instance=user_id) if request.method == 'POST': form = CreateProduct(request.POST) if form.is_valid(): form.save() return redirect('/products/') context = {'form': form} return render(request, 'accounts/newcoin.html', context) Also, I want to validate the product's ctp value whenever a user types in the unique digit to another form. -
django async support - not fully understanding the main concept
which is main concept of django asgi? when there are multiple tasks to be done inside a view, handle those multiple tasks concurrently thus reduce view's response time. when there are multiple requests from multiple users at same time, hendle those requests concurrently thus users wait less in queue. Channels? Web Socket? I'm trying to understand and use the asgi concept but feeling so lost. Thanks. -
Got error when tried to restore postgresql data from docker in windows
i'm using windows and got this error when tried to restore PostgreSQL data from docker. The problem seem like because docker can't find that file but there is file exist in postgresql_backups folder. I tried searching but no result, can anyone help? (by the way, macos seem run fine without problem) -
how to handling IST timeZOne to UTC timeZone i Django?
How do i convert IST timeZone to UTC timeZone , as i have made an api and an application is making a post request and there is a transaction_time which is in IST format but i need to store transaction_time in database in UTC timeZone format. models.py class Payments(models.Model): datetime = models.DateTimeField(auto_now=False,auto_now_add=False) views.py @api_view(['POST']) def cashfree_request(request): if request.method == 'POST': data=request.POST.dict() datetime = data['txTime'] print(datetime) #datetime sent by the application in '2021-05-17 14:26:33' #it should be changed in UTC timeZone and then save into database -
Why do my entries don't get saved in the Database in Django?
The post requests from the frontend do not get saved in the database, without any error shown. However, when I manually add entries from the admin panel, it shows on the frontend. My index.html(form part): <form class="main__input--form" method="POST"> {% csrf_token %} <p class="main__input--text"> <textarea name="content" id="content" class="main__input--content" cols="35" rows="8" aria-label="Entry content" placeholder="Enter text here..."></textarea> </p> <button class="main__input--submit" type="submit">Vent</button> </form> My extension of index which loops through the database entries: {% for obj in all_vents %} <div> <h1>{{obj.vent}}</h1> </div> <br /> {% endfor %} My models.py: class Vents(models.Model): vent = models.CharField(max_length=10000) def __str__(self): return self.vent My forms.py: from django import forms from .models import Vents class VentForm(forms.ModelForm): class Meta: model = Vents fields = ['vent'] My views.py: from django.shortcuts import render, redirect from .forms import VentForm from .models import Vents def ventout(request): if request.method == "POST": form = VentForm(request.POST or None) if form.is_valid(): form.save() return redirect("ventout") else: all_vents = Vents.objects.all() return render(request, "ventout.html", {"all_vents": all_vents}) -
Django signals: Check if the data inside of ManyToManyField is change/updated
how can I check if the objects inside of ManyToManyField is change or updated while still accessing the main Model where the manytomanyfield is placed. Here is the example of code: class Student: name = models.CharField(max_length=255, null=True, blank=False) age = models.IntegerField(default=0, null=True, blank=False) class Room: students = models.ManyToManyField(Student, related_name="list_of_students") I tried the m2m_changed but it only recieve those signals when there's a Newly added/updated/deleted on students field. I want to get the Room model where the student is selected at students field. s1 = Student.objects.first() s1.name = "John Doe" s1.save() '''prints the data with Room model on it.''' -
Is there a way to iterate through all the fields in a Django database object and display them through a template HTML?
I have this HTML code for my template HTML file: name : {{object.name}} age : {{object.age}} gender : {{object.gender}} name, age, gender etc are stored in a MySQL database. Instead of listing every field, which is a lot, I want to generalize the code like this: {% for field in object %} {{field.field_name}} : {{field.field_value}} {% endfor %} My problem is that I have multiple tables and each table has lots of fields. I cannot generalize the table. How do I generalize my template the way I've shown in the latter code snippet? -
Sending Email via Crontab in Django Not working
This is my first time to use crontab, I have a cron task and set every 1 minute to run the task but nothing happen. My sending email script is 100% working if I run manually via Django view but in crontab task not working. Can you please help me if whats wrong with my task? No error found via terminal and application. Im using: django-cronjobs==0.2.3, django-crontab==0.7.1 cron.py This Django sending email script is 100% working via Django views. class request_cron_email(): sent_status = table.objects.all(), cstatus = table.objects.filter(Deadline__date = datetime.datetime.today(), sent_email="No") plate = "" for carreg in cstatus: plate = carreg.plate_no print(plate) if plate != "": for item in cstatus: subject = 'FMS Automated Email' html_message = render_to_string('vr/pms_email.html',{'content':item.plate_no}) plain_message = item.plate_no recipient_list = [item.email] from_email = 'FMS <test@gmail.com>' mail.send_mail(subject, plain_message, from_email, recipient_list, html_message=html_message, fail_silently=False) car_status.update(sent_email="Yes") setting.py CRONJOBS = [ ('*/1 * * * *', 'request.cron.request_cron_email') ] INSTALLED_APPS = [ 'django_crontab' ] -
Kubectl. No environment variables are found in the service
I built an API with django, celery and redis. I deployed the API in minikube an add some secrets to the cluster with: kubectl create secret generic my-secret-storage \ --from-literal=AZURE-STORAGE-ACCOUNT-NAME='account_name' \ --from-literal=AZURE-STORAGE-ACCOUNT-KEY='account_key' \ --from-literal=AZURE-STORAGE-CONTAINER-NAME='container_name' And I build the deployd and the service in this way: apiVersion: apps/v1 kind: Deployment metadata: name: api-consulta-acciones labels: app: api-consulta-acciones spec: replicas: 1 selector: matchLabels: app: api-consulta-acciones template: metadata: labels: app: api-consulta-acciones spec: containers: - name: api-consulta image: my_image args: - sh - -c - |- python3 ./manage.py runserver 0.0.0.0:8000 ports: - containerPort: 8000 env: - name: AZURE-STORAGE-ACCOUNT-NAME valueFrom: secretKeyRef: name: my-secret-storage key: AZURE-STORAGE-ACCOUNT-NAME - name: AZURE-STORAGE-ACCOUNT-KEY valueFrom: secretKeyRef: name: my-secret-storage key: AZURE-STORAGE-ACCOUNT-KEY - name: AZURE-STORAGE-CONTAINER-NAME valueFrom: secretKeyRef: name: my-secret-storage key: AZURE-STORAGE-CONTAINER-NAME - name: celery # Celery deployd - name: celery-beat # Celery-beat deployd --- apiVersion: v1 kind: Service metadata: name: api-consulta-svc labels: app: api-consulta-svc spec: type: LoadBalancer ports: - name: "8000" port: 8000 targetPort: 8000 selector: app: api-consulta-acciones If I get into the container api-consulta-acciones -c api-consulta, I can confirm that the secret variables were created: # Inside the pod >>> import os >>> os.environ environ({'AZURE-STORAGE-ACCOUNT-NAME': 'account_name', 'AZURE-STORAGE-CONTAINER-NAME': 'container_name', 'AZURE-STORAGE-ACCOUNT-KEY': 'account_key', ..... }) However, the problem is when I use the API in the … -
For login, request provides user details in Django
I am trying to create a Django todo app by using the Django rest framework where I ran into this problem. I am authenticating the user via the rest framework so that I am able to get an authentication token, for the user. My views.py... def login(request): print("\n\n", request, "\n\n") if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: login(user) response = requests.post("http://127.0.0.1:8000/api/login/", data={"username":username, "password":password}) token = json.loads(response.text).get("token") request.session["token"] = f"Token {token}" request.session.modified = True # r = requests.get("http://127.0.0.1:8000/api/", headers={"Authorization":request.session["token"]}) return redirect("home") else: return render(request, "todo/login.html", {"message":"Your entered credentials are wrong"}) else: return render(request, "todo/login.html") In which I have figured that when my user input is invalid, the request parameter carries the value <WSGIRequest: POST '/login'>. But when the user input is valid the request parameter carries my user details (the value najaaz - my username). This output was figured out using the print statement in line 2. Since it carries my user details I get the following error 'User' object has no attribute 'method', since the line if request.method == "POST": would be invalid then. This is something new for me, and I am a bit unsure of how … -
TemplateDoesNotExist: personal/home.html
I am trying to access home.html, the relative path looks like this hub/templates/hub/home.html. However, I want to access all the template folders, I am trying to accomplish that through the code provided in settings.py. It looks different than other people's post ( there is no 'os' option) Here is my settings.py: from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # My apps 'hub', # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [Path(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True …