Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change user password not in a separated view?
I want to let user change his password and edit his profile on the same page. I scrolled through Internet and it turns out, that for some reason, everyone creates separated view for changing password. So, here's my Profile model if that makes sense: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to=user_directory_path_ppic) bio = models.TextField(max_length=255, blank=True, null=True) How do I let user change his password and edit profile on the same page? -
OperationalError at /admin/auctions/listings/ no such column: auctions_listings.category_id
I'm trying to create categories for my listings but it shows the above error. I also tried adding the id column manually but then it shows this error: AssertionError: Model auctions.Category can't have more than one auto-generated field. models.py from django.db import models from django.contrib.auth.models import AbstractUser,BaseUserManager from django.utils.translation import ugettext_lazy as _ from django.conf import settings # Create your models here. class myUserManager(BaseUserManager): """ custom user model manager where email is unique indentifiers for authenticaton instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_superuser',True) extra_fields.setdefault('is_active',True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff= True')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email,password, **extra_fields) class myUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = myUserManager() def __str__(self): return f'{self.email}' class Category(models.Model): category = models.CharField(max_length=50, default="No Category") def __str__(self): return f'{self.category}' class Listings(models.Model): listing_name … -
Django channels: send and receive data from users in list
Hi I am very new to Django channels. I am trying to create a doctor consultation app. I am using drf to get details like speciality,date,patient info etc based on which I filter out the eligible doctors. I am trying to use channels to send request to each doctor in a list one at a time until he accepts/rejects or times out. Here is a flow chart My doubts I have the id list in my views.py how should I pass it to consumers.py? How do i send and get reponse serially? Is there a better way? -
Upload file using jQuery ajax with Django
I am learning ajax and JQuery with Django. I created a basic app to update the text field but now I added the file field. But unable to make it work. The is model class class TextModel(models.Model): text=models.CharField(max_length=200) file=models.FileField(upload_to='files') This is my template <div class='col-8 mt-5'> <form method='POST' id='formCreated' data-url="{% url 'home' %}" enctype="multipart/form-data"> <!-- data-url is used in ajax function --> {% csrf_token %} {{ form.as_p }} <button type="button" id="btn_submit">Upload</button> </form> </div> <div class='col-5 mt-5' id='resultid'> </div> Here is my views function def home(request): if request.method=='POST': form = TextForm(request.POST,request.FILES) if form.is_valid(): out=form.save() return JsonResponse({'text':model_to_dict(out)},status=200) else: return render(request,'home.html',{'form':form}) else: form = TextForm() return render(request,'home.html',{'form':form}) Here is my code in js file $(document).ready(function(){ $('#btn_submit').click(function() { var serializedData=$('#formCreated').serialize(); console.log(serializedData) $.ajax({ url:$("formCreated").data('url'), data:serializedData, type:'POST', success:function(response){ // reponse recieved from views recieved here and sent to div with resultid in home.html console.log(response) $('#resultid').append(response.text.text) // first text is key of response and second text is the text object } }) $('#formCreated')[0].reset(); }); }); This is the error I am getting file.js:16 Uncaught TypeError: Cannot read property 'text' of undefined at Object.success (file.js:16) at c (jquery.min.js:3) at Object.fireWith [as resolveWith] (jquery.min.js:3) at k (jquery.min.js:5) at XMLHttpRequest.r (jquery.min.js:5) -
File csv does not downloaded but instead open inside browser
I have two files that a user can download from my django app. The files have different formats xls and csv. The first one is downloaded as expected, but the problem is with csv, it is not downloaded, but opens inside the browser like a normal html. how can this be fixed? I think I need to change the title from text/html to file/csv. But i don't know how i can do it. -
Fields error messages like "This field is required" are not displayed
I am working on a eCRF using Django and do not use forms and views as usual In few words, forms are displayed using ajax and submit the form using ajax as well. View ajax_form return selected form. I have only one view create_or_update that test for existing form and submit data. All is working quite well. I have followed [this tutorial][1] to sumit forms using ajax but even if not valid forms are not submitted, fields errors messages are not displayed: unvalid field is highlighted in "red" and an help text "Please complete this field" (server-side validation?) is displayed. I use django-crispy for render. view.py # Ajax view to render form in patient view def ajax_form(request): if request.is_ajax() and request.method == "POST": # If form already exist, update form is displayed if already_exist(): form = InclusionForm(patient=patient, data=data or None, instance = obj) # Else, creating form is displayed else: form = InclusionForm(patient=patient) return JsonResponse({'html_inclusion': render_to_string('ecrf/inclusion.html',{'form': form,},request=request),},status=200) @json_view def create_or_update(request,pk): if Inclusion.objects.filter(pat = Patient.objects.get(pat_ide = pk).pat).exists(): obj = get_object_or_404(Inclusion, pat = Patient.objects.get(pat_ide = pk).pat) form = InclusionForm(patient = pk, data=request.POST or None, instance = obj) else: form = InclusionForm(patient = pk, data=request.POST or None) if form.is_valid(): form.save() return { 'success' … -
Django: getting image URL when saving in Models
In my Django app I upload an Image, resize it and save copies to another fileds. Everything works fine. What I want to do is save the URL of the original uploaded file to a CharField (to avoid n+1 lookups from the usual .url image attribute). As the file is not actually saved until "super" I can´t get the file url. Any clues on how can I achieve this? Thanks in advance! The model class ProductosBase(models.Model): foto_1_original = models.ImageField(upload_to='', default="", blank=True, null=True) foto_1 = models.ImageField(upload_to='', default="", blank=True, null=True) foto_1_M = models.ImageField(upload_to='', default="", blank=True, null=True) foto_1_L = models.ImageField(upload_to='', default="", blank=True, null=True) foto_1_url = models.CharField(max_length=750, help_text="max 30 char", blank=True, null=True) def __str__(self): return str(self.producto) def save(self, *args, **kwargs): if self.foto_1_original: pil_image_obj = Image.open(self.foto_1_original) if pil_image_obj.format == 'TIFF': new_name = str(self.foto_1_original.name).replace('.tiff', '.jpg') pil_image_obj = pil_image_obj.convert('RGB') elif pil_image_obj.format == 'PNG': new_name = str(self.foto_1_original.name).replace('.tiff', '.jpg') pil_image_obj = pil_image_obj.convert('RGB') else: new_name = str(self.foto_1_original.name) if pil_image_obj.mode == 'CMYK': pil_image_obj = pil_image_obj.convert('RGB') new_image = resizeimage.resize_width(pil_image_obj, 200) new_image_io = BytesIO() new_image.save(new_image_io, format='JPEG') temp_name = new_name.split('.')[0] + '_200.' + new_name.split('.')[1] self.foto_1_L.save(temp_name, content=ContentFile(new_image_io.getvalue()), save=False) new_image = resizeimage.resize_width(pil_image_obj, 400) new_image_io = BytesIO() new_image.save(new_image_io, format='JPEG') temp_name = new_name.split('.')[0] + '_400.' + new_name.split('.')[1] self.foto_1_M.save(temp_name, content=ContentFile(new_image_io.getvalue()), save=False) new_image_d = resizeimage.resize_width(pil_image_obj, 400) new_image_io_d = BytesIO() new_image_d.save(new_image_io_d, … -
Can't insert data, Django primary key doesn't have a default
In Django 3.0, I have a set of Models consisting of an abstract BaseData, a Model Data that extends it, and a Model of underlying data FKData that Data foreign-keys to: # models.py from django.db import models class BaseData(models.Model): class Meta: abstract = True class Data(BaseData): data = models.ForeignKey( FKData, on_delete=models.CASCADE, blank=True, null=True, default=None ) class FKData(models.Model): text = models.CharField( help_text='underlying data' ) The error occurs when I try to INSERT into Data. For example, mysql> INSERT INTO appname_data (data_id) SELECT data_id FROM appname_othertable ERROR 1364 (HY000): Field 'basedata_ptr_id' doesn't have a default value basedata_ptr_id is a primary key field that Data has due to being a subclass of BaseData: mysql> DESCRIBE appname_data; +-----------------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------------+---------+------+-----+---------+-------+ | basedata_ptr_id | int(11) | NO | PRI | NULL | | | data_id | int(11) | YES | MUL | NULL | | +-----------------+---------+------+-----+---------+-------+ 2 rows in set (0.00 sec) The error sounds like it isn't being set to AUTO INCREMENT the way normal primary keys are? If I try filling the Data table using the Django shell, I get the same error but with a bigger stack trace that might … -
How to connect Django with Azure Cosmos DB
I want to connect Django with Azure Cosmos DB. Either with Core SQL Or Gremlin. Do we have any existing libraries we can use to achieve it? -
Django dropdown menu/form based on model entries
I have got created a drop down menu where I can show the values of a model data called "Items". However, I trying to change this into a Django form in order to be more flexible. However, I have some problems in understanding how to adapt this? Here is the relevant code: models.py class Items(models.Model): item_name = models.CharField(max_length=200) views.py def details(request): template = loader.get_template('news/details.html') items = Items.objects.all() context = {'items': items} return HttpResponse(template.render(context, request)) details.html <form method="POST" action = ""> {% csrf_token %} <select name = "wwww"> {% for n in prod %} <option value ="{{ n.product_name }}"} name ="val">{{ n.product_name }} </option> {% endfor %} </select> <input type="hidden" name="speichern1" value="1"/> </form> Maybe someone could help me out or point me to a help page for this? Thanks, Andi -
Forward ForeignKey querying in Django
Let's say I have the following two models: class Post(models.Model): ... class Keyword(models.Model): value = models.CharField(...) post = models.ForeignKey('posts.Post', related_name="keywords") Now lets say I want to return a list of all posts for a given keyword.value. I usually do this: keywords = Keyword.object.filter(value="something").values_list(id, flat=True)`. Posts.keywords.filter(id__in=keywords) To return a <QuerySet[]> of Posts. I'm not sure if I am missing something in the documentation, but can I return a QuerySet of Posts in one query and can I do it on the Keyword model? Something similar to a related name set ... ? -
urlshort.models.Linkurl.DoesNotExist: Linkurl matching query does not exist
I found a lot of SO solutions like that answer. But still getting stuck on matching query does not exist. The issue is the line url_details = Linkurl.objects.get(uuid=pk) My model.py is from django.db import models # Create your models here. class Linkurl(models.Model): link = models.CharField(max_length=10000, blank=False) uuid = models.CharField(max_length=10) def __str__(self): return self.link[:40]+" - "+self.uuid Views.py is from django.shortcuts import render, redirect import uuid from .models import Linkurl from django.http import HttpResponse # Create your views here. def index(request): return render(request, 'urlshort/index.html') def create(request): if request.method == 'POST': link = request.POST['link'] uid = str(uuid.uuid4())[:5] new_url = Linkurl(link=link, uuid=uid) new_url.save() return HttpResponse(uid) def go(request, pk): url_details = Linkurl.objects.get(uuid=pk) return redirect(url_details.link) and urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('create', views.create, name='create'), path('<str:pk>', views.go, name='go') ] I found many solutions but didn't work for my issues and saying raise self.model.DoesNotExist( urlshort.models.Linkurl.DoesNotExist: Linkurl matching query does not exist. -
Django Validate Form As Per Database Entry ID
Hello Wonderful people, I have made a form in Django which has some serial numbers stored in Django-admin database. I am now creating another app and similar form, However I want is that the new Form should accept the serial number which is valid and checked as per the serial number got entered in the first form which is in app 1. I am pasting a bit of my code for you to understand it more clearly with some screenshots. <form method="POST" action="/reservation/home/"> {% csrf_token %} <div class="form-group"> <label for="exampleFormControlInput1">Radio Serial Number</label> <input type="text" class="form-control" id="exampleFormControlInput1" name= "sno" placeholder="S/N123ABC123" required > </div> <button type="submit" class="btn btn-primary"> Submit </button> </form> views.py of new app. def reserve(request): if request.method == "POST": sno = request.POST.get('sno') date_req = request.POST.get('date_req') reserve = Reserve( sno=sno, date_req=date_req ) reserve.save() return render(request, 'home.html') models.py of new app. from django.db import models # Create your models here. class Reserve(models.Model): sno = models.CharField(max_length=100) date_req = models.DateField() def __str__(self): return self.sno I want it to accept the serial number which got input by another form and validate it. If the new serial number is not same as the database entry in previous form , It should display some error message that … -
(mismatching_state) CSRF Warning! State not equal in request and response
I know that it's duplicate question. I am getting same error. So please help me. Here my code crd = "path\\client_secret.json" scopes = "https://www.googleapis.com/auth/androidmanagement" current_url = request.get_full_path() parsed = urlparse.urlparse(current_url) state_get = parse_qs(parsed.query)['state'] flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(crd, scopes=scopes, state=state_get) flow.redirect_uri = "http://127.0.0.1:8000/google-class/oauth2callback/" print("flow.redirect_uri", flow.redirect_uri) authorization_response = request.get_full_path() print('authorization_response', authorization_response) flow.fetch_token(authorization_response=authorization_response) credentials = flow.credentials print("credentials", credentials) androidmanagement = build('androidmanagement', 'v1', credentials=credentials) print(androidmanagement) -
Errors when running Celery: AttributeError: '_thread._local' object has no attribute 'backend'
I'm using Celery with Django and RabbitMQ to scrape a website. Starting a Django project and RabbitMQ goes well, but when trying to start Celery, I get the following message: AttributeError: '_thread._local' object has no attribute 'backend' During handling of the above exception, another exception occurred: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'celery.backends.amqp' Here's my Celery config: from __future__ import absolute_import import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_api.settings') app = Celery('django_api') app.conf.timezone = 'UTC' app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() and here are Celery variables in settings.py: CELERY_BROKER_URL = 'amqp://localhost:5672' CELERY_RESULT_BACKEND = 'amqp://localhost:5672' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC' I'm running celery in pipenv with the following command celery -A django_barcode_api worker -B -l INFO Following this tutorial: https://github.com/mattdood/django_web_scraping_example/ Any ideas how can I resolve this error when running celery? -
The page is not displayed correctly in Django prodject, maybe because of uncorrect views
So, I did a Django project according to the Django textbook. And when I typed python manage.py runserver I saw this page: It's not what I wanted to see. There should be a list of latest questions, because I type it in index file( I think taht the problem is in views or in html files. polls/views.py: from django.http import HttpResponseRedirect from django.template import loader from django.shortcuts import get_object_or_404, render from django.shortcuts import redirect from django.shortcuts import render from django.http import Http404 from django.views import generic from django.utils import timezone from . models import Answer, Question class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): return Question.objects.filter( pub_date__lte=timezone.now() ).order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()) class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_answer = question.answer_set.get(pk=request.POST['answer']) except (KeyError, Answer.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a answer.", }) else: selected_answer.votes += 1 selected_answer.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) polls/index.html {% … -
Adding & updating users from django admin to Auth0
I am trying to use Auth0 authentication in my django application. I am able to see the users added from auth0 in my django custom user table. Is it possible to add and update users from django application to Auth0. So far my code is mostly from the auth0 django tutorial. Can we add users from django admin site with Abstract Base User model and show them in Auth0? Below is code for authentcation that I am using. But is it possible to do 2-way? If I update a user in django admin site, it is not reflecting in Auth0 users. I couldn't get a clear picture of the AUth0 management API to update users from django side.. especially from admin site. Any inputs would be of great help. auth0.py class Auth0(BaseOAuth2): """Auth0 OAuth authentication backend""" name = 'auth0' SCOPE_SEPARATOR = ' ' ACCESS_TOKEN_METHOD = 'POST' REDIRECT_STATE = False EXTRA_DATA = [ ('email', 'email') ] def authorization_url(self): return 'https://' + self.setting('DOMAIN') + '/authorize' def access_token_url(self): return 'https://' + self.setting('DOMAIN') + '/oauth/token' def get_user_id(self, details, response): """Return current user id.""" return details['user_id'] def get_user_details(self, response): # Obtain JWT and the keys to validate the signature id_token = response.get('id_token') jwks = request.urlopen('https://' … -
How to access a dictionary value in a for [django, python, html]
I pass the context to html and I need to display the values in a for - by key. is not displayed. how to refer to the value of a dictionary in a loop? print context context = {'tag': 'fast', 'view': <orders.views.OrderAddView object at 0x0000000005AB30A0>, 1: <class 'clients.forms.RelatedAddForm'>, 2: <class 'clients.forms.RelatedAddForm2'>, 'count_form': range(1, 3)} html <form action="{% url 'order_add' tag %}" method="post"> {% csrf_token %} {% for x in count_form %} {{ x.as_p }} - this does not work {% endfor %} {{ 1.as_p }} - it works <button type="submit" class="btn btn-primary btn-block">Add order</button> </form> that is, how to access the values 1,2, etc. in a loop - 1: <class 'clients.forms.RelatedAddForm'>? perhaps it is necessary to specify {{context [x] .as_p}} in the loop? how to do it? -
save Django2.2 404 request in database using middelware
i write a custom middilware to save all request in my database. this is my code: class TestMiddleware(MiddlewareMixin): def process_response(self, request, response): .... # save my request attr in database HttpRequestLog.objects.create(**params) ... i have a problem. when user call a wrong url apis , Django return 404 status but this code save nothing to my database and i have n't any error!!! HttpRequestLog.objects.create(**params) my code is worked when api returned 200 or 204 or 201 status. -
Django Rest Framework Path working for one link, but not for other with same setup
I am trying to access my mysql database through the django rest backend. My frontend uses Vue with Axios. More specifically, I have a junction table TeacherSubjectJunction, which I want to access through the following path to get all subjects for a teacherid. app/urls.py path('teacherssubjects/<int:teacherid>/', TeacherSubjectJunctionList.as_view()) views.py: class TeacherSubjectJunctionList(generics.ListAPIView): queryset = TeacherSubjectJunction.objects.all() serializer_class = TeacherSubjectJunctionDeepSerializer filterset_class = TeacherSubjectJunctionFilter serializer.py: class TeacherSubjectJunctionDeepSerializer(serializers.ModelSerializer): class Meta: model = TeacherSubjectJunction fields = ['teacherid', 'subjectid'] depth = 3 For Filtering i am using the third party library django-filter filters.py class TeacherSubjectJunctionFilter(filters.FilterSet): class Meta: model = TeacherSubjectJunction fields = ['teacherid', 'subjectid'] models.py class TeacherSubjectJunction(models.Model): pk_teachersubject = models.AutoField(primary_key=True) teacherid = models.ForeignKey(Teachers, models.CASCADE, db_column='TeacherID') subjectid = models.ForeignKey(Subjects, models.CASCADE, db_column='SubjectID') class Meta: db_table = 'teacher_subject_junction' In my Vue file I am trying to access this path with the following code: async getSubjectsforTeacher(teacher){ await getAPI.get('/teacherssubjects/?teacherid='+teacher) .then(response =>{ this.SubjectsforTeacherData[teacher] = response.data console.log(this.SubjectsforTeacherData) }).catch(error =>{ if (error.response){ console.log( error.response ) }else if(error.request){ console.log( error.request ) }else if(error.message){ console.log( error.message ) } }) } The above setup gives me the following error: GET http://127.0.0.1:8000/teacherssubjects/?teacherid=3 404 (Not Found) Since I am only a few months into drf, I figured that something about my url setup was wrong. But here is where it gets interesting. … -
How to calculate total amt of different Models using multiple @property Django
class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return "Ordered by "+str(self.customer) @property #meaning add property see cart.html def get_cart_total(self): #get total value of one Model with their respective quantity orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): #get items total orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total @property #meaning add property see cart.html def get_energy_total(self): #get total value of another Model with their respective quantity orderenergies = self.orderenergie_set.all() total = sum([item.get_total for item in orderenergies]) return total @property def get_energy_items(self): #get items total orderenergies = self.orderenergie_set.all() total = sum([item.quantity for item in orderenergies]) return total @property def get_total_items(self): #get items total #how to get total value of two different model class OrderItem(models.Model): #make more orderitem product = models.ForeignKey(Paidproduct, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.CASCADE, blank=True, null=True) addtodpage = models.ForeignKey(Downloaddisplay, on_delete=models.CASCADE, blank=True, null=True) category=models.CharField(max_length=20, choices=CATEGORY_CHOICES,null=True) quantity = models.IntegerField(default=0, null=True, blank=True) data_added = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.product) @property def get_total(self): #to get total items of a certain product in cart.html total = self.product.price * self.quantity #+self.product1.price * self.quantity return total -
django site Admin shows 500 after login
I am new to Django, current site after login shows the 500 request not found but it login me as credentials are correct Django hosted in IIS and Django is 1.10 -
Django: list User details and Group for every User-Group (Many-To-Many) relationship in template
How to query and show User info and their Group for every User-Group (Many-To-Many) relationship in Django template? The result should look like: | User username | User email | Group name | | ------------- | -------------- | ----------- | | user1 | user1@mail.com | groupA | | user1 | user1@mail.com | groupB | | user2 | user2@mail.com | groupA | | user2 | user2@mail.com | groupC | | user3 | user3@mail.com | groupA | My question is similar to Vanilla Django Query to show 'flattened' User/Group (ManyToMany) Listing, but would like show more user details on the table. I naively thought something like this would have worked, but didn't. {% for group in groups %} {% for user in group.users.all %} <tr> <td>{{user.username}}</td> <td>{{user.email}}</td> <td>{{group.name}}</td> </tr> {% endfor %} {% endfor %} Using the raw SQL query has solved my problem: https://stackoverflow.com/a/38780451/991505 , but I am looking for better answers in the Django/Python way. -
Django App - auto creating & printing pdfs
Is there any way to autogenerate pdf and autoprint it? Let's say - i've got a list with 0 orders, server refreshes itself for every 5 minutes, and after that - there is an order in a list. App is creating pdf and print it by itself. Is this possible? -
Django custom login issue
I have created custom authenticate method because instead of username i want logged in through email for that i have written backends.py backends.py from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError UserModel = get_user_model() class EmailBackend(object): def authenticate(username=None,password=None): try: user = UserModel.objects.get(email=username) if user.check_password(password): return user else: return None except UserModel.DoesNotExist: raise ValidationError('Invalid Credentials') def get_user(self,user_id): try: return UserModel.objects.get(pk=user_id) except UserModel.DoesNotExist: return None After authenticating i want user to be logged in.For that i am using login method as below: login(request,user,backend='django.contrib.auth.backends.ModelBackend') views.py from django.shortcuts import render,redirect from users.forms import RegisterForm,LoginForm from users.backends import EmailBackend as em from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth import login def register(request): if request.method=='POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() print('Successfully Created') else: form = RegisterForm() return render(request,'users/register.html',{'form':form}) def user_login(request): if request.method == 'POST': form = LoginForm(request.POST) uname = request.POST['username'] pwd = request.POST['password'] user = em.authenticate(username=uname,password=pwd) if user is not None: if user.is_active==True: k=login(request,user,backend='django.contrib.auth.backends.ModelBackend') print(user,k) print('Successfull login') else: print('Unsuccessfull login') else: form = LoginForm() return render(request,'users/login.html',{'form':form}) In my console i am trying to get the value returned by login function but that is returning None . k=login(request,user,backend='django.contrib.auth.backends.ModelBackend') print(user,k) Output in my console: [16/Mar/2021 16:02:34] "POST /register/ HTTP/1.1" 200 881 [16/Mar/2021 16:02:52] "GET …