Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django dependent dropdown with ajax. Do I need to divide my model to 3 different models in order to implement dependant dropdown?
I have model in my django that describe cars. It have fields: make model price I want to let users to create queries for them through django forms and I wanted to implement dependent dropdown. When user selects "make" then available "models" change. I saw some tutorials but it seems that all of them would divide my model car into three different models but foreign keys. I suppose it would look something like this: Makes: - name Models: - make (foreign key) - name Car: - price - make (foreign key) - model (foreign key) I am wondering, is it possible to somehow implement this dependant dropdown in django forms while keeping only 1 cars model? And if so, what should I google? Thanks. -
custom validator for charfield do not raise any error
I have done a validator that is supposed to check the input from a charfield: def postnvali(value): if not value.isalnum(): raise ValidationError(_('postnummer måste vara siffror')) it is used in the following model: class Adress(Model): street=CharField(max_length=100) snumb=CharField(max_length=15) town=CharField(max_length=100) postn=CharField(max_length=5,validators=[postnvali]) def __str__(self): return 'city: ' + self.town class Meta: ordering=('street','town') but when using admin and entering the wrong format, nothing happens, no error message. why? -
Session data becomes null in second view in django
I do have session backend in my settings.py SESSION_ENGINE = "django.contrib.sessions.backends.db" how do i track of that my_car session variable in second view ? -
Get HTML form in Django fuction
I know there are explanations out there regarding this, but I didn't understand how to implement it in my code, so I am asking again. I get the following error ViewDoesNotExist at /answer_question/ 'False' is not a callable or a dot-notation path When I click the "Post your answer" button in my post.html form. It is like a Stack Overflow website. I have an URL called answer_question/ in urls.py path('answer_question/', views.answer_question, name="answer_question"), Then I made a function in views.py def answer_question(request): return render(request, 'store/homepage.html') def post(self, request): form = HomeForm(request.POST) if form.is_valid(): text = form.cleaned_data["post"] print("TEXT = " + str(text)) This has to make a new answer in the database. models.py class Answer(models.Model): title = models.CharField(max_length=200, null=True) context = models.TextField(max_length=1702, blank=True, validators=[MaxLengthValidator(1702)]) date = models.DateField(("Date"), default=date.today) author = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True) def __str__(self): return self.title As for the syntax I looked at: https://www.youtube.com/watch?v=wzZiONbtwiA and https://docs.djangoproject.com/en/3.1/topics/forms/ <form action="/answer_question/" method="post"> <div class="blogpost"><br><br> <textarea name="answer-title-input" cols="20" rows="1" class="answer-title" maxlength="20" placeholder="Write a title here..." id="id_context"></textarea> <br><br><hr><br> <div class="blogpost-content"> <textarea name="answer-context-input" cols="80" rows="10" class="answer-input" maxlength="300" placeholder="Write an answer here..." id="id_context"></textarea> <br> <br> <button type="submit" class="submit-answer-button">Post your answer</button> -
How can we identify wether the client is viewing my website from a mobile or a desktop?
wondering if any of you could help me out... My issue is that I need to adjust the size of an image and rearrange the positions of elements in HTML depending on wether the client is using a phone or a larger screen such as a laptop. I need a function which can detect if the user is viewing my website using a mobile or a desktop. I searched the internet and found very very long solutions to them and I feel there should be a shorter one. I am using django (python) for my server and HTML, CSS and JAVASCRIPT for the front end. If anyone could provide me a function to do so, I would be very thankful to you. Thanks in advance -
I want to make dynamic task scheduling chatbot system in flask python
I am making a dynamic task scheduling chatbot system in flask python. which actually helps managers to assign tasks to their employees. Now I want to know how to make responsive system between manager and employee and they both are going to interact with chatbot integration provided by facebook.Please help me by giving such kind of sample code. import os import sys import json import requests from flask import Flask, request app = Flask(__name__) TOKEN = Page_Access_token VERIFY_TOKEN = verification_token params = { "access_token": TOKEN } headers = { "Content-Type": "application/json" } @app.route('/webhook', methods=['GET']) def verification(): # Webhook Verification if request.args.get("hub.challenge"): if not request.args.get("hub.verify_token") == VERIFY_TOKEN: return "Verification token mismatch", 403 return request.args["hub.challenge"], 200 return "Hello", 200 @app.route('/webhook', methods=['POST']) def webhook(): # Messaging Events data = request.get_json() log(data) if data["object"] == "page": for entry in data["entry"]: for messaging_event in entry["messaging"]: if messaging_event.get("message"): #Messaging Event receiveMessage(messaging_event) else: # Unknown Event log("Webhook received unknown messaging_event: " + str(messaging_event)) return "ok", 200 def sendMessage(recipient_id, message_text): # Definition of sendMessage - A function to send Text Messages to user log("sending message to {recipient}: {text}".format(recipient=recipient_id, text=message_text.encode('utf-8'))) # encode('utf-8') included to log emojis to heroku logs message_data = json.dumps({ "recipient": { "id": recipient_id }, "message": { … -
The view mysiteapp.views.addpost didn't return an HttpResponse object. It returned None instead
my views.py file i just try to update form data form dashboard so i'm not getting what's going wrong to the code can someone please help me to solve def addpost(request): if request.user.is_authenticated: if request.method == 'POST': forms = addpostForm(request.POST) if is_valid(): forms.save() forms =addpostForm() else: forms = addpostForm() return render(request,"addpost.html",{'form':forms}) else: return HttpResponseRedirect('login') addpost.html file <form action ='' method='POST'> {% csrf_token %} {{form.as_p}} <input type='submit' class='btn btn-success btn-sm' value ='Add' > <input type='submit' class='btn btn-danger btn-sm' value ='Cancel' > </form> my forms.py class addpostForm(forms.ModelForm): class Meta: model = post fields = ['title','desc'] labels ={'title':'Title','desc':'Description'} widgets = {'title':forms.TextInput(attrs={"class":'form-control'}),'desc':forms.Textarea(attrs={"class":'form-control'}),} -
How to apply a migration operation in runtime?
Having a dynamically created instance of django.db.migrations.operations.base.Operation (CreateModel operation in particular) which is encapsulated in a SeparateDatabaseAndState as a database operation only (with no state operations to tamper with the normal migration system), how can I execute the operation in runtime (i.e., without using migration files)? The requirement is to be able to create and drop tables at runtime which are highly compatible with Django-defined models and database-DDL-independent at the time of creation. These tables will be named using a special prefix to not collide with normal Django tables, and they will be limited in numbers. (And yes, I am aware of possible design and performance issues; this may seem a bad-practice, there are alternative solutions, and so on!) If this is not possible, an alternative question will be: How to get the raw SQL statement from a dynamically created instance of django.db.migrations.operations.base.Operation? -
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module with MySQL installed
Hardware configuration I'm configuring my new MacBook Air with Apple silicon M1 chip and obviously mac os 11 Big Sur. Environment I have installed mysql@5.7 with homebrew and use python@3.6.5 installed with pyenv@1.2.21. The issue I work with Django framework and the last step for me is to configure the MySQL database on localhost. MySQL server is running and I can use it from the shell and access it by SequelPro. When I run python manage.py migrate I have this problem : django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? The database configuration is: DATABASE environment Does someone have the same problem? -
overriding save method to save ip address in django models
I am working on a Django project and I need to save the user's IP address in my database. I can get user's ip address with request.META.get("REMOTE_ADDR"). Currently, I have to provide an IP address in my save and edit views. I was looking for a clean solution so that I can override the models save() method and let models save IP address every time a new record is added or any record is updated. But Django models don't have access to request. Is there any workaround for this? or do I have to provide an IP address in my every saves and edits view. -
What is the right way to create .env file on remote machine(like AWS instance)?
I have a Django project where the settings file refers to a .env file(in root). The .env file contains all the sensitive data like Database password, Debug value. As a security measure, this .env file has been added to .gitignore and wouldn't be uploaded to GIT repository. Now, how do I add this file to the root of a remote host like AWS instance? -
Django AWS RDS environment variables not setting in Elastic Beanstalk
I'm using Amazon Linux 2 in an AWS Elastic Beanstalk instance to host my Django web server. When using SSHing into my environment, I cannot run manage.py commands because os.environ doesn't contain environment variables for my RDS db. So when in my settings.py file I try to access the database like so: if 'RDS_DB_NAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'home', 'USER': '', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '5432', } } It thinks I am still on localhost and it gives me an error. How do I get around this? Is there a way to load in my RDS environment variables via the /opt/elasticbeanstalk/bin/get-config environment command or is there another way that doesn't require SSH? -
message not showing in template
i am trying to make my new blog and as so many blogs there is a registration form so i added a login page and in the views.py of the login i added a message.error but when i use the for statement in the template it doesnt show views.py: from django.shortcuts import render from .forms import RegisterForm from django.shortcuts import redirect from django.contrib import messages def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username and password: user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request, 'Username or Password is Incorrect') else: messages.error(request, 'Fill out all the Fields Please') return render(request, 'register/login.html',{}) my template: <div class="form-floating mb-3"> <input type="text" class="form-control" id="floatingInput" placeholder="name@example.com" name="username"> <label for="floatingInput">Username</label> </div> <div class="form-floating"> <input type="password" class="form-control" id="floatingPassword" placeholder="Password" name="password"> <label for="floatingPassword">Password</label> </div> {% if messages %} {% for message in messages %} <h4 class="{{ message.tags }}" style="color: red;">{{ message }}</h4> {% endfor %} {% endif %} when i use the for loop it doesn't show any message on my page but when i only use {{ messages }} it show me this : ** <django.contrib.messages.storage.cookie.CookieStorage object at 0x0000014473D5C490> ** -
'post' object is not iterable in django and it is showing error but i'm not getting what's going wrong on code
TypeError at /dashboard 'post' object is not iterable i am just try to get data from db table and show on dashboard in dabel form my dashboard.html page {% if posts %} <table class="table table-dark table-hover"> <thead> <tr> <th scope="col" style="width:3%">ID</th> <th scope="col" style="width:30%">Title</th> <th scope="col" style="width:55%">Description</th> <th scope="col" style="width:15%">Action</th> </tr> </thead> <tbody> {% for post in posts %} <tr> <td>{{posts.id}} </td> <td>{{posts.title}}</td> <td>{{posts.desc}}</td> <td><a class="btn btn-primary" type="submit" value="Submit">Edit</a> <form action ='' , method ='POST' class='d-inline'> {% csrf_token %} <input type='submit' class='btn btn-danger btn-sm' value ='Delete' > </form> </td> </tr> {% endfor %} </tbody> </table> {% else %} <h4 class =' text-center alert alert-warning'>No Records </h4> {% endif %} </div> </div> {% endblock content %} my views.py def dashboard(request): if request.user.is_authenticated: posts= post.objects.all() return render(request,'dashboard.html',{'posts':post}) else: return HttpResponseRedirect('login') urls.py path('dashboard',views.dashboard,name='dashboard'), -
How to limit choices on the Django filter based on the request.user
I have a multi company setup. The user is logged into to a specific company. Every company has its own set of ledger accounts and transactions. On the transaction list I created filter options so that the user can filter based on "Description", "Transaction date" and "Ledger account". The problem with the Ledger Account is that the choices available is the accounts from all the companies. I ant to limit the choices to only show the Ledger Accounts from the current company that the user is logged into. User model: class custom_user(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) company_group = models.CharField(max_length=6, null=True) current_company = models.ForeignKey(tcompany, on_delete=models.CASCADE, null=True) Note the current_company as a ForeignKey. Leger Account Model: class tledger_account(models.Model): id = models.AutoField(primary_key=True) slug = models.SlugField(max_length=30, null=True) description = models.CharField(max_length=30, unique=False) gl_category = models.CharField(max_length=30, choices=category_choices, verbose_name='category', db_index=True) note = models.CharField(max_length=25, blank=True, default=None) active = models.BooleanField(default=True) company = models.ForeignKey(tcompany, on_delete=models.PROTECT) class Meta: indexes =[ models.Index(fields=['company', 'description']) ] unique_together = ['company', 'description'] Note the company as a ForeignKey. Views.py: class TransactionlistView(ListView): model = ttransactions template_name = 'accounting/transaction_list.html' def get_form_kwargs(self): … -
How to Query data from MySQL database with Django following model update
After updating posts model field in MySQL database using using Django framework, I'm unable to query posts from the Database. Whenever I run the command python manage.py runserver, all seems to be well with the server. However, when enter the post url to display the list of posts I uploaded on the database before updating the model field, I get 1054, "Uknown column 'start_post.author_id' in the 'field list' I have spent a couple of hours try to figure out why I'm getting the error but I still don't get it. In model.py I had: title = models.CharField() preamble= models.Charfield() body = models.TextField() createdAt = models.DateTimeField(auto_now_add=True, blank=True) I updated the above model to: title = models CharField() author = models.ForeignKey(User, on_delete=models.CASCADE) introduction = models.charfield () body = models.TextField() createdAt = models.DateTimeField(auto_now_add=True, blank=True) def get_absolute(self): return reverse ('post-details', kwarks={'pk': set.pk}) views.py •••• class PostListView(Listview): model = Post template_name = 'start/start.html' context_object_name = 'posts' ordering = ['createdAt'] start.html ••• {% for post in posts %} <h3>{{ post.title }}</h3> <i>{{ post.createdAt }} </I> <p>{{ post.introduction }}</p> <p>{{ post.body }}</p> {% endfor %} •••• before updating it everything was working appropriately. But after updating it I'm unable to access the list of posts on browser, … -
my images array is empty when I pass student to actions in redux but it is working in postman
I am trying to add image files to images array using React but I am getting an empty images array. My backend is written in Django. It is working fine when Im using postman to insert image files but I am getting an empty array when using react. AddNewStudent.js file const AddNewStudent = () => { const [Name, setName]= useState('') const [Enrollment_No, setEnrollmentNo]= useState('') const [Registration_No, setRegistrationNo]= useState('') const [Semester, setSemester]= useState('') const [Year, setYear]= useState('') const [Course_Name, setCourseName]= useState('') const [Course_Code, setCourseCode]= useState('') const [studentImages, setStudentImages]= useState([]) const dispatch= useDispatch() const submitForm= (e) => { e.preventDefault() const images=[] for (let image of studentImages){ images.push({ image }) } console.log(images) const student={ Name, Enrollment_No, Registration_No, Semester, Year, Course_Name, Course_Code, images } console.log(student) dispatch(addStudent(student)) } const handleStudentImages = (e) => { setStudentImages([ ...studentImages, e.target.files[0] ]) } return ( <CCard> <CCardHeader> Add New Student </CCardHeader> <CCardBody> <CForm action="" method="post" onSubmit={submitForm}> <CFormGroup> <CLabel htmlFor="nf-name">Name</CLabel> <CInput type="text" id="nf-name" name="nf-name" placeholder="Name" autoComplete="name" onChange={(e) => setName(e.target.value)}/> </CFormGroup> <CFormGroup row className="my-0"> <CCol xs="6"> <CFormGroup> <CLabel htmlFor="nf-enrollmentno">Enrollment No</CLabel> <CInput type="text" id="nf-enrollmentno" name="nf-enrollmentno" placeholder="Enrollment Number" autoComplete="enrollment_no" onChange={(e) => setEnrollmentNo(e.target.value)}/> </CFormGroup> </CCol> <CCol xs="6"> <CFormGroup> <CLabel htmlFor="nf-registrationno">Registration No</CLabel> <CInput type="text" id="nf-registrationno" name="nf-registrationno" placeholder="Registration Number" autoComplete="registration_no" onChange={(e) => setRegistrationNo(e.target.value)}/> </CFormGroup> </CCol> </CFormGroup> … -
How to sync my local database of my web app to database of my deployed web app?
So my project is a school distributed system based on django web framework. My web app will be deployed in every school on their local computers. And all of the data on those computer will by synced with a main server on my side. What I want is how to implement a solution that would help me sync files/data with my server such that if some file/data is changed on a local computer it'll replicate itself in our server and if I change some file/data on my server, it'll update on those local computers whenever they get an internet connection. -
How to route the value of editable table cell to another method using Django
I am using Django framework. Currently I have a table row whose cells are editable and the code is as follows: <td><p align="center" contenteditable='true'>ABC</p><button>Edit</button></td> Now my need is to edit the value of this cell to (say) "XYZ" from "ABC" and click on the button "Edit" and then it should redirect me to an api in the views.py file with the value of "XYZ". So how can I achieve that ? Please help me as I am not much thorough with Django. Should we use any javascript method or directly can I route the value "XYZ" to the api in views.py file? -
Python Django Ajax get request not working in def function
I'm trying to pass a variable from my JQuery Ajax object via get method to my views.py file (in django) I was using a class before and it was working just fine.. views.py working code: class AjaxHandlerView(View): def get(self, request): text = request.GET.get('button_text') print() print(text) print() if request.is_ajax(): return JsonResponse({'test': 'blah'}) return render(request,'home.html' , {'name': 'Handled by AHV'} ) app urls.py from django.urls import path from . import views from .views import * urlpatterns = [ path('', AjaxHandlerView.as_view() ), path('ajaxg' , views.ajaxgtest, name="ajaxg" ) ] jquery ajax functions (ignore the post method) var test_str = "[0,0]"; $(document).ready(function(){ var csrf = $('input[name=csrfmiddlewaretoken]').val() $('#jq_btn').click(function(){ $.ajax({ url: '', type: 'get', data: { button_text: test_str }, success: function(response) { $("#jq_btn").text(response.test + test_str); console.log(test_str); } }); }); $('#post_btn').click(function() { $.ajax({ url: '', type: 'post', data: { text: test_str, csrfmiddlewaretoken: csrf }, success: function(reponse) { test_str = reponse.postdata console.log(test_str); } }) }); }); However I wanted to use a specific function for specific methods.. so I tried using a def.. views.py that is not working: def ajaxgtest(self, request): text = request.GET.get('button_text') print(text + "deffer") if request.is_ajax(): return JsonResponse({'test': 'blah'}) return render(request,'home.html' , {'name': 'Handled by AHV'} ) As for the Jquery code, all I did was … -
showing results as 'Undefined', instead of expected output in text field
I want to populate values into 4 text fields based on the value given in the input field. when control comes out of the input field, a function getcredentials() is called which in turn calls a python code. python code retrieves the 4 required values from an excel sheet and returns the result as a dictionary. I have tried to set those 4 values from the result dictionary in the following way. please correct me. script : <script> function getcredentials() { var x = document.index.AWSID.value; console.log(x) var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.index.APPUSERNAME.value = this.responseText['AppUsername']; document.index.APPPASSWORD.value = this.responseText['AppPassword']; document.index.RDPUSERNAME.value = this.responseText['RdpUsername']; document.index.RDPPASSWORD.value = this.responseText['RdpPassword']; } }; xhttp.open('POST', 'getcredentials', true); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); /*xhttp.send(x);*/ xhttp.send("x="+encodeURIComponent(x)); } </script> python code : def getCredentials(request): AwsId = request.POST.get('x') result = {'RdpUsername' : 'Opsadmin', 'RdpPassword' : '--C0nt@1ns^Ph3n%l@l@n1n3--', 'AppUsername' : 'Admin', 'AppPassword' : 'M@St3r..CRM'} result['RdpPassword'] = result['RdpPassword'] + AwsId[-5:] result['AppPassword'] = result['AppPassword'] + AwsId[0:3] response = HttpResponse(result) return response -
Django rest framework social oauth2 causing unexpected error with Djongo for mongoDB conversion of django app
I am using Django rest framework social oauth2 for authentication in one Django app. For development purposes, I have used this package with Sqlite3 (SQL database) and it works perfectly. However, now I want to migrate this Django app to MongoDB (NoSQL database) via using [Djongo][1]. After implementing all the required changes it is showing this bizarre error. I have seen everywhere couldn't find a relevant solution python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, oauth2_provider, sessions, social_django Running migrations: Not implemented alter command for SQL ALTER TABLE "oauth2_provider_accesstoken" ADD COLUMN "source_refresh_token_id" long NULL UNIQUE Applying oauth2_provider.0001_initial...Traceback (most recent call last): File "/home/anakin/virtual_envs/js_backend/lib/python3.8/site-packages/djongo/cursor.py", line 51, in execute self.result = Query( File "/home/anakin/virtual_envs/js_backend/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 783, in _init_ self._query = self.parse() File "/home/anakin/virtual_envs/js_backend/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 875, in parse raise e File "/home/anakin/virtual_envs/js_backend/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 856, in parse return handler(self, statement) File "/home/anakin/virtual_envs/js_backend/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 888, in _alter query = AlterQuery(self.db, self.connection_properties, sm, self._params) File "/home/anakin/virtual_envs/js_backend/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 425, in _init_ super().__init__(*args) File "/home/anakin/virtual_envs/js_backend/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 84, in _init_ super().__init__(*args) File "/home/anakin/virtual_envs/js_backend/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 62, in _init_ self.parse() File "/home/anakin/virtual_envs/js_backend/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 435, in parse self._add(statement) File "/home/anakin/virtual_envs/js_backend/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 598, in _add raise SQLDecodeError(err_key=tok.value, djongo.exceptions.SQLDecodeError: Keyword: long Sub SQL: ALTER TABLE "oauth2_provider_accesstoken" ADD COLUMN "source_refresh_token_id" long … -
No Post matches the given query in django
So i have a project called star social project this project is similar to a socail media that you can post and create group but this project you can only post when you are in a group. So i get an error message that is not familiar to me which is on the title, i tried to search on google and get some result but when i implement it to my project it does not work. So why im getting this error is because i'm trying to create a comment section and when i click the add comment that's when i get the error message. So i'm here to ask someone to help me because i'm not really familiar on this error and i'm just learning django for about 2 months now. models.py ########################## ## POSTS MODELS.PY FILE ## ########################## from django.contrib.auth import get_user_model from django.db import models from groups.models import Group from misaka import html from django.urls import reverse from django.utils import timezone User = get_user_model() class Post(models.Model): user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group, related_name='posts', null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.message def save(self, *args, **kwargs): self.message_html = … -
Django Product object has no attribute author
hi i am not new to django but i can not find the error . may be a new pair of eyes can saw that i just import usertestmixin and wrote the function test_func() but it is not working i do not know why it gave me the error 'Product' object has no attribute 'author' my models for product is: class Product(models.Model): title = models.CharField(max_length=110) slug = models.SlugField(blank=True, unique=True) price = models.DecimalField(decimal_places=2, max_digits=6) discount_price=models.FloatField(blank=True, null=True) size = models.CharField(choices=SIZE_CHOICES, max_length=20) color = models.CharField(max_length=20, blank=True, null=True) image = models.ImageField(upload_to=upload_image_path) description = models.CharField(max_length=1000) featured = models.BooleanField(default=False) time_stamp = models.DateTimeField(auto_now_add=True) and my models.py for user is: class User(AbstractBaseUser): email = models.EmailField(max_length=255 ,unique=True) full_name = models.CharField(max_length=255, blank=True, null=True) active = models.BooleanField(default=True) #can login staff = models.BooleanField(default=False) #staff user non super user admin = models.BooleanField(default=False) #superuser time_stamp = models.DateTimeField(auto_now_add=True) and my views.py is: class ProductUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Product template_name = 'product-form.html' fields = ['title', 'price' , 'size' , 'color', 'image' , 'description'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): self.object = self.get_object() return self.request.user == self.object.author it gave me the error:enter image description here -
Getting 401 HTTP error during deployment only
I made a website using Django and Angular. I deployed the app using the instructions from this link: https://medium.com/saarthi-ai/ec2apachedjango-838e3f6014ab Problem When I ran the app locally it works fine. But, during deployment I am getting 401 error, I don't understand why. The deployment is done in the Amazon AWS EC2 instance using an Apache webserver. The authentication used is django-rest-knox P.S: I also checked the admin panel and the token of the user is added.