Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to match time range if to_date can be Null in Django?
I have two date, let's say from_date and to_date, and I have column with prices for that range. It looks like this in my models: class PriceList(models.Model): from_date = models.DateField(verbose_name="Start date") to_date = models.DateField(verbose_name="End_date", null=True) product = models.ForeignKey(Models, on_delete=models.CASCADE) price = models.DecimalField(verbose_name="EUR/h", max_digits=10, decimal_places=5) I know how to get record for the correct product in a period if a to_date is available, but I am not sure how to fetch it if it is Null, that means from from_date to forever (until changed). And, obviously, would like to have query that will work in both scenarios - if ther is a to_date and if it Null. -
Display user image ({{ userprofile.image.url }}) on my base.html
I hope you're well? I'm beginner with Django. I'm using a profile for my users (witch belongs to "User" field. I'd like to display the image on my base.html (witch belongs to "Nutriscore" "templates" field). How I can do it? {{ userprofile.image.url }} only works on my update_profile.html page (witch belongs to the user templates field). MonProjetDjango Nutriscore -- templates -- urls.py User -- templates -- views.py -- models.py User > views.py @method_decorator(login_required(login_url='login/'),name="dispatch") class UserProfileUpdateView(UpdateView): model = UserProfile template_name = 'profile-update.html' form_class = UserProfileForm success_message = "Profile updated" def form_valid(self, form): form.instance.user = self.request.user form.save() return super(UserProfileUpdateView, self).form_valid(form) def get_success_url(self): return reverse('update_profile',kwargs={'slug':self.object.slug}) def get(self,request,*args,**kwargs): self.object = self.get_object() if self.object.user != request.user: return HttpResponseRedirect('/') return super(UserProfileUpdateView, self).get(request,*args,**kwargs) User > models.py class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) street = models.CharField(null=True,blank=True,max_length=300) number_street = models.CharField(null=True,blank=True,max_length=20) street_detail = models.CharField(null=True,blank=True,max_length=300) town = models.CharField(null=True,blank=True,max_length=60) zipcode = models.CharField(null=True,blank=True,max_length=20) country = models.CharField(null=True,blank=True,max_length=60) image = models.ImageField(null=True,blank=True,default='user/user-128.png', upload_to='user/') slug = models.SlugField(editable=False) def save(self, *args,**kwargs): self.slug = slugify(self.user.username) super(UserProfile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 200 or img.width > 200: new_size = (200, 200) img.thumbnail(new_size) img.save(self.image.path) def __str__(self): return self.user.username def create_user_profile(sender,instance,created,**kwargs): if created: UserProfile.objects.create(user=instance) post_save.connect(create_user_profile,sender=settings.AUTH_USER_MODEL) Nutriscore > urls.py path('profile/<slug:slug>/', UserProfileUpdateView.as_view(), name="update_profile"), -
How do I put extrenal link on blog title in Wagtail?
I made Blog-Index-Page on models.py, however I couldn't list it up in other pages, because Blog-Index-Page is a sheet of page so they cannot show on same page. and I want to put external links (URLs) on titles without my Blog-Detail-page. following is the BlogIndexPage on models.py☟ class BlogIndexPage(Page): template = "articles/blog_index.html" blog_title = models.CharField(max_length=100, blank=False, null=True) blog_url = models.URLField(max_length=200, default='DEFAULT VALUE') blog_thumbnail = models.ForeignKey("wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+") blog_caption = models.CharField(max_length=100, blank=True, null=True) content_panels = Page.content_panels +[ FieldPanel("blog_title"), FieldPanel("blog_url"), ImageChooserPanel("blog_thumbnail"), FieldPanel("blog_caption"), ] def get_context(self, request, *args, **kwargs): context = super().get_context(request, *args, **kwargs) context["posts"] = BlogIndexPage.objects.live().public() return context I want to apply this class as a listing page, not as detail page. Can I help me to make listing page and give me some idea. -
Fullcalendar cannot display event after event has been created (Django and Javascript)
currently I cannot display event after event has been created. In fact, I cannot display event at all from database. Previously, I made something like this and it worked. views.py def calendar(request): all_events = Events.objects.all() context = { "events":all_events, } return render(request,'fullcalendar/calendar.html',context) calendar.html events: [ {% for event in events %} { title: "{{ event.title}}", start: '{{ event.start|date:"Y-m-d" }}', end: '{{ event.end|date:"Y-m-d" }}', id: '{{ event.id }}', }, {% endfor %} ], But right now, I wanted to insert the part which is in the calendar.html to script.js and I tried to use EventSources but I failed to make events display on fullcalendar. Does anyone know how to convert the part which is in calendar.html to script.js? The reason why I decided to use script.js is because if I put everything in HTML, it will get really long. Currently, my EventSources of script.js looks like this. script.js eventSources:[{ url: '/fullcalendar/calendar', method: 'GET', success: function(){ alert("GOT IT!!"); }, failure: function(){ alert("PROBLEM!!!"); }, } ], it seems I have done nothing but trust me I have searched all over the place and tried so many things but I still fail to make the event display on the fullcalendar. I got the feeling … -
python script .sh is running or not check in portal
guys is it possible to check continuously if .sh (any script) file is running or not. with portal that monitor .sh services for example sample test backup.sh service running every 15 minute that take backup in cronjob. mkdir "/dev/my backup directory" mv /var/log/*2007* "/dev/my backup directory/" sed -i '/:[0-9][0-5]:/ {d}' "/dev/my backup directory/*" this is simple test script but is it possible that we can check throw portal that show if service is running or not that send alert if it is stop or started in web-application if it is possible in python or another language than where i can find useful information. -
Django: ValueError: Missing staticfiles manifest entry for 'jquery.twbsPaginationAlt.min.js'
Before marking as duplicate, note that I've checked all the similar questions that have been asked and it has not fixed my problem. I've deployed my Django App on Heroku in in one template where I reference a min.js file, it throws this error in question. My basic directory structure is this: myapp mysite dictionary static jquery.twbsPaginationAlt.min.js staticfiles settings.py: STATIC_URL = '/static/' # STATIC_ROOT = [os.path.join(BASE_DIR, 'staticfiles'), os.path.join(BASE_DIR, 'static/fonts')] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') if DEBUG: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'mysite/static'), os.path.join(BASE_DIR, 'static/')] import django_heroku # handles staticfiles, database url, and secret key, can be overwritten as needed django_heroku.settings(locals(), secret_key=False, logging=False) So originally if STATICFILES_DIRS had any value, I would get an error of FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_6f3eb879/mysite/static' when running collectstatic on heroku. However, if it is not set, than the fonts I have in my dev environment do not load in properly (I also have fonts inside the base level static folder). This is how I reference the js file in my problem template, it works fine on dev: <script src='{% static 'jquery.twbsPaginationAlt.min.js' %}'></script> For convenience, here is what django-heroku does in terms of staticfiles: logger.info('Applying Heroku Staticfiles configuration to Django settings.') config['STATIC_ROOT'] = os.path.join(config['BASE_DIR'], 'staticfiles') … -
django - template IF tag - how to do IF variable <= current date
In my models.py I have a end_date variable. In my template, I'd like to show certain stuff only if that end_date is passed. Is there a way to do that in the template? {% if end_date <= now %} ... {% else %} ... {% endif %} That doesn't work... Any pointers? Thanks! -
UniqueValidator with case sensitive char field
In serializer I have defined a name filed like this name = serializers.CharField(max_length=255,validators=[UniqueValidator(queryset=Names.objects.all())]) But on insertion I is letting add a same name with case sensitive name , Like Helo and helo both are inserting -
Error in following Django message warning code
I am getting error in the code below: {% if messages %} {% for message in messages %} x {{ message }} {% endif %} {% block content %} {% endblock %} The error message is as follow: Django Version: 3.0.8 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 53: 'endif', expected 'empty' or 'endfor'. Did you forget to register or load this tag? Exception Location: C:\hashimcapital\venv\lib\site-packages\django\template\base.py in invalid_block_tag, line 521 Line 53 is {% endif %} -
How to serve Multilingual URLs in Django DMS?
I'm trying to internationalize my site with Django CMS 3.7. Ref: http://docs.django-cms.org/en/latest/how_to/languages.html[![enter image description here]1]1 the language code and content are all setup ok. but I couldn't setup the URL with multilingual. when I tried to set URL with other language(ie. Chinese), error message: Slug must not be empty. only English is ok, screenshot attached. any ideas to fix it? thanks all -
How to set the maximum image size to upload image in django-ckeditor?
I am using django-ckeditor for my project to upload image along with text content. I used body = RichTextUploadingField(blank=True, null=True) in model. Now I want to restrict the user to upload large size images in content or larger than predefined maximum height/width. I want the uploaded images in content of particular height/weight and size like less then 1mb. How can I predefine maximum image height and width as well as maximum image size limit? Is there any way to define it from django-ckeditor configuration? Or How to resize the uploaded images from content at backend after user submitted the form? Here is my models.py: class Post(models.Model): STATUS_CHOICES = { ('draft', 'Draft'), ('published', 'Published'), } title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextUploadingField(blank=True, null=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') I tried a lot to solve it but failed.Any suggetion to solve the issue? Thanks in advance. -
Django and ngnix login problem Reload login
I'm a bit of a novice, not to mention a lot in django and ngnix, I have a django server called backend-for-frontend-ms, it runs on port 8083, the problem is that when I start ngninx, it redirects me to the login I want, but when I start session the page simply reloads I do not understand very well why this happens but I suppose it is something from the host but I do not know what to configure or add This is my code the ngninx SERVER_NAME = mydomain.co upstream django_server { server $DJANGO_HOST:$DJANGO_PORT; } server { listen 80; server_name $SERVER_NAME; try_files $uri @django_server; location @django_server{ proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://django_server; } } This is my settings.py from the service django SERVICE_NAME = os.environ.get( 'POSTGRES_BACKEND_FOR_FRONTEND_MS_DATABASE_NAME', '') ALLOWED_HOSTS = ['manto.c-pyme.co'] if DEBUG: ALLOWED_HOSTS.append( '{}.localhost.com'.format(SERVICE_NAME).replace('_','-')) #else: # ALLOWED_HOSTS.append( # '{}.c-pyme.co'.format(SERVICE_NAME).replace('_','-')) # Application definition ------------------------------------------------------ INSTALLED_APPS.extend([ 'backend_for_frontend_MS', 'user_MS', 'manto_MS' ]) MIDDLEWARE.insert( 4, '{}.middleware.MultipleProxyMiddleware'.format(SERVICE_NAME)) MIDDLEWARE.insert( 5, '{}.middleware.TimezoneMiddleware'.format(SERVICE_NAME)) MIDDLEWARE.insert( 11, '{}.middleware.SetOautClientCredentials'.format(SERVICE_NAME)) MIDDLEWARE.insert( 12, '{}.middleware.CompanyHostMiddleware'.format(SERVICE_NAME)) ROOT_URLCONF = '{}.urls'.format(SERVICE_NAME) # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://example.com/media/", "http://media.example.com/" MEDIA_URL = '/{}/media/'.format(SERVICE_NAME) WSGI_APPLICATION = '{}.wsgi.application'.format(SERVICE_NAME) TEMPLATES = [ { 'BACKEND': … -
Issues upgrading python social auth django (psycopg2.IntegrityError)
I am working on a codebase using Django 1.9, I am busy getting everything ready to upgrade to 1.10. I have run into an issue after migrating from python social auth to python social auth app django. I have used the steps found here After updating my settings and url files, I ran into the below error. Does anyone know how I can get around this? Running migrations: Rendering model states... DONE Applying social_django.0006_partial... OK Applying social_django.0007_code_timestamp... OK Applying social_django.0008_partial_timestamp... OK Applying social_django.0009_auto_20191118_0520...Traceback (most recent call last): File "/home/brendan/venvs/social/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: column "modified" contains null values The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/brendan/venvs/social/lib/python3.6/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/home/brendan/venvs/social/lib/python3.6/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/brendan/venvs/social/lib/python3.6/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/home/brendan/venvs/social/lib/python3.6/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/home/brendan/venvs/social/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/home/brendan/venvs/social/lib/python3.6/site-packages/django/db/migrations/executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/brendan/venvs/social/lib/python3.6/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/brendan/venvs/social/lib/python3.6/site-packages/django/db/migrations/executor.py", line 198, in apply_migration state = migration.apply(state, schema_editor) File … -
Django not loading database after Heroku plan upgrade
I recently updated my Postgresql plan on Heroku and migrated the data from the old database to the new one, i destroyed the old database with which worked fine. After the migration my app stoped working and i got this error: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Is there something else that i need to change in my app so that i connect to a new database i created, the new database has a different attached as name is that a factor? Thank you -
Optimize Serializer Performance in Django Rest Framework
I'm developing a web app using Django and Django Rest Framework and struggling with slow API responses which appear to be based on fetching data from related tables. Test case 1 runs very quickly because the fields are directly tied to the Host model. As soon as I introduce a many-to-many field, it slows down dramatically. Test case 1 - takes 250ms serializers.py class HostSerializer(serializers.Serializer): created = serializers.DateTimeField() last_updated = serializers.DateTimeField() name = serializers.CharField(); Test case 2 - takes 30s serializers.py class HostSerializer(serializers.Serializer): created = serializers.DateTimeField() last_updated = serializers.DateTimeField() name = serializers.CharField(); applications = serializers.SerializerMethodField(read_only=True) def get_applications(self, instance): return [item.name for item in instance.applications.all()] models.py class Host(models.Model): created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) name = models.CharField(unique=True, max_length=settings.MAX_CHAR_COUNT) ip_addresses = models.ManyToManyField(IPAddress, blank=True) open_ports = models.ManyToManyField(Port, blank=True) domain = models.ForeignKey('Domain', on_delete=models.CASCADE) applications = models.ManyToManyField(Application, blank=True) tls = models.ForeignKey(TLS, on_delete=models.CASCADE, blank=True, null=True) class Meta: ordering = ['name'] def __str__(self): return self.name def __repr__(self): return self.name def __eq__(self, other): if isinstance(other, Host): return self.name == other.name return False def __hash__(self) -> int: return hash(self.name) def __lt__(self, other): return self.name < other.name views.py class HostList(generics.ListAPIView): """ List all hosts for a given domain """ host_service = HostService() def get(self, request, domain_name, format=None): hosts = self.host_service.find_hosts_by_domain_name(domain_name) … -
Im getting error object of type 'NoneType' has no len()
im getting this Nonetype error.im stuck at it all day. first i was getting MultiDictError after changing it to filetitle = request.POST.get('bob') contentitle = request.POST.get('pop') it seems to work and now this error. views.py def add(request): filetitle = request.POST.get('bob') contentitle = request.POST.get('pop') return render(request, "add/add.html"),{ "entries":util.save_entry(filetitle,contentitle) } utills.py def save_entry(title, content): """ Saves an encyclopedia entry, given its title and Markdown content. If an existing entry with the same title already exists, it is replaced. """ filename = f"entries/{title}.md" if default_storage.exists(filename): default_storage.delete(filename) default_storage.save(filename, ContentFile(content)) add.html {% block body %} <h1>Create New Page</h1> <form action="encyclopedia:add" method="post"> {%csrf_token%} <input name="bob" type="text" placeholder="Enter the Markdown content " id="abz"> <textarea name="pop" rows="20" cols="25" value="content"></textarea> <input type="submit" value="submit" /> </form> {% endblock %} i tried several things but none of them seems to work. thanx in advance -
I am trying to save a record in table two of one to many relationship and retrieve it for specific user in Django
I have two tables one user and one MyGoal with one to many relationship between them in this order only. I am unable to save the record in table though i am able yo create form from model, secondly i want to display goals of a particular user in the my goal temple it will be of the user who has logged in ,i have written code for these two tasks but am unable to complete them please help. Models.py file class MyGoal(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) Goal_subject=models.CharField(max_length=50) Goal_Url=models.URLField() Forms.py class UserForm(forms.ModelForm): password=forms.CharField(max_length=10) class Meta(): model=User fields=('username','email','password') class MyGoalForm(forms.ModelForm): class Meta: model=MyGoal fields="__all__" Url.py applications url(r'^MyGoal/$',views.MyGoalView,name='MyGoal'), Url.py project url(r'^FirstApp/',include('FirstApp.url')), Views.py @login_required def MyGoalView(request): My_goal= MyGoal.objects.filter(user=request.user) form=MyGoalForm() if request.method=="POST": form=MyGoalForm(request.POST) if form.is_valid(): form.save(commit=True) return index(request) else: print("Invalid form") return render(request,'FirstApp/MyGoal.html',{'forms':form,'goal':My_goal}) Template {%for p in My_goal%} {{p.Goal_Url}} {%endfor%} <form> {{forms.as_p}} {%csrf_token%} <input type="submit" value="Submit"> </form> -
Django automatic Logout and and after login it stays on same page
I am new to Django and using Django 3.0.2. Sometimes Django automatically logout and when I try to log in on my website then it stays on the login page but creates a session(I mean, I can see all the buttons which a user will see after login in header and footer). I am not experiencing this issue when I am manually logging out and logging in. Please help if someone else is also experiencing the same issue. Thanks in advance. -
What is the best way to implement a REST API based payment gateway for a Django web app
Should i make the payment requests from views.py or from them templates using javascript. Currently i am sending http requests from views.py to the REST API and the problem is how do i send the product price to the template and when the user confirms payment, how do i fetch the amount to be paid. The rest of the payment details like credit card number i collect from a checkout form. -
How to test LAMP stack application performance using Codespeed?
We are planning to use Codespeed ( https://github.com/tobami/codespeed ) for analysing and monitoring code of LAMP stack web application (Linux,Apache,MySQL, PHP). Went through documentation, but I couldn't find any reference for using it for LAMP application. Where are we supposed to do linking of Codespeed with our application? Or in which folder our application needs to be placed? -
How do I revoke JWT everytime a new token generated using django-graphql-jwt?
I am using django-graphql-jwt (https://django-graphql-jwt.domake.io/en/latest/index.html) to handle authentication for my Django Python Graphene application. Currently, everytime a new JWT generated, the previous JWT is still active as long as it does not pass its expiry time. I want to revoke/prevent access to previously generated JWT (even if the JWT is not expired yet) whenever I generate a new JWT. What I am thinking is utilizing the origIat inside the JWT payload and comparing it with something like a last_login attribute from the User model. I noticed though, that User.last_login is not updated whenever I am authenticating using JWT. Still finding how to do this problem properly and wondering if there is any of you already solving this problem before. Thanks! -
Can't see removal flags
Django 3.0.8 django-comments-xtd==2.6.2 I'm studyint this section of the tutorial: https://django-comments-xtd.readthedocs.io/en/latest/tutorial.html#removal-suggestion post_detail.html {% extends "base.html" %} {% load comments %} {% load comments_xtd %} {% block title %}{{ object.title }}{% endblock %} {% block content %} <div class="pb-3"> <h1 class="text-center">{{ object.title }}</h1> <p class="small text-center">{{ object.publish|date:"l, j F Y" }}</p> </div> <div> {{ object.body|linebreaks }} </div> {% get_comment_count for object as comment_count %} <div class="py-4 text-center"> <a href="{% url 'blog:post-list' %}">Back to the post list</a> &nbsp;&sdot;&nbsp; {{ comment_count }} comment{{ comment_count|pluralize }} ha{{ comment_count|pluralize:"s,ve" }} been posted. </div> {% if object.allow_comments %} <div class="card card-block mb-5"> <div class="card-body"> <h4 class="card-title text-center pb-3">Post your comment</h4> {% render_comment_form for object %} </div> </div> {% endif %} {% if comment_count %} <ul class="media-list"> {% render_xtdcomment_tree for object allow_flagging allow_feedback %} </ul> {% endif %} {% endblock %} settings.py COMMENTS_XTD_APP_MODEL_OPTIONS = { 'blog.post': { 'allow_flagging': True, 'allow_feedback': False, 'show_feedback': False, } } Problem I have loged in. But I can't see any flag at the right side of every comment’s header. Could you give me a hint where the problem may be hiding? -
Django not creating a testdatabase when testing
I am running tests in my newly created Django project. Normally I would expect to see a test database created for when tests are running. All tests are running fine, but I am seeing that my local database (for runserver use) is beeing used when running the tests. A lot of excess data is beeing created in the wrong database. How can I get my test setup to use the normal test_dabasename setup again? Im not sure what I have changed to make this happen and am totally stumped. -
Django how to correctly acces the context variable in javascript
My question is similar to the these previous questions, however I can't seem to make my code work: How can I pass my context variables to a javascript file in Django? How to use the context variables passed from Django in javascript? I have a list of lists, containing data of the form: data = [[1, 2, 3, 4, ...] [210, 346, 331, 402, ...] [...] ...] where the first list represents the number of each taken sample. I'm passing this data to my HTML file using a class that looks like: class IndexView_charts(generic.TemplateView): """ IndexView: """ module = 'IndexView' template_name = charts_temp_name #variable for the template data = ##extra code here to fetch data def get_queryset(self): log(self.module, 'get_queryset', file=__file__) return self.data def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['data'] = self.data return context And in the template, I can access the variable data as follows for example and it shows up on the webpage: <h1> {{data.0}} </h1> now, I'd like to access it in my script. In the same file I have the following code: var chartData = {{ data }}; ... some more code here ... data:chartData[1] but I don't get the charts that I would like. If i … -
"User already exist" Custom Django Authentication Backend
I'm coding a custom django authentication, the code works fine for user creation but when I try to login, it is like if I were signing up again, so there is no way of accessing my user account because every time I try to login, I get an error because a user with that credentials already exist (I'm that user). The output is: <ul class="errorlist"><li>address<ul class="errorlist"><li>User with this Address already exists.</li></ul></li></ul> Models.py: class AppUser(AbstractUser): username = models.TextField(unique=True) address = models.CharField(max_length=34, unique=True) key = models.CharField(max_length=34) def __str__(self): return self.username Forms.py: class NewUserForm(forms.ModelForm): class Meta: model = AppUser fields = ("username", "address", "key") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.address = self.cleaned_data["address"] user.key = self.cleaned_data['key'] if commit: user.save() return user class LoginUserForm(forms.ModelForm): class Meta: model = AppUser fields = ("address", "key") def __init__(self, request=None, *args, **kwargs): self.request = request super().__init__(*args, **kwargs) Backends.py: class AppUserBackend(ModelBackend): def authenticate(self, request, **kwargs): address = kwargs['address'] key = kwargs['key'] try: customer = AppUser.objects.get(address=address) if customer.key == key: return customer.user else: print("Error") except AppUser.DoesNotExist: pass Views.py: def login_request(request): if request.method == 'POST': form = LoginUserForm(request=request, data=request.POST) if form.is_valid(): address = form.cleaned_data.get('address') key = form.cleaned_data.get('key') user = authenticate(request=request, address=address, key=key) if user is not None: login(request, user, backend='main.backends.AppUserBackend') …