Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with displaying and fitting requests in SelectMultiple, django forms
I'm having a problem displaying potential members in a select multiple select box. The usual logic is that the user submits an application for participation, and the admin approves his participation through select multiple. The problem is that in this field I have displayed all applications for all events, without any filter. I started trying other people's solutions, but even that doesn't work. These are the two forms involved class EventForm(forms.ModelForm): class Meta: model = Event fields = ('name', 'venue', 'event_date', 'participants', 'short_description', 'description') #"__all__"name widgets ={ 'name' : forms.TextInput(attrs={'class':'form-control'}), 'manager' : forms.Select(attrs={'class':'form-select'}), 'venue' : forms.Select(attrs={'class':'form-select'}), 'event_date' : forms.TextInput(attrs={'class':'form-control'}), #'participants': forms.SelectMultiple(attrs={'class':'form-control'}), 'participants' : forms.SelectMultiple( to_field_name="participants", queryset=Participant.objects.filter(attending__event=event_id, attending__is_attending=True), # error in "event_id" widget=forms.CheckboxSelectMultiple), 'short_description' : forms.Textarea(attrs={'class': 'form-control'}), 'description' : forms.Textarea(attrs={'class': 'form-control'}), } class ParticipantForm(forms.ModelForm): user = forms.ModelChoiceField(queryset=User.objects.all(), widget=forms.HiddenInput()) event = forms.ModelChoiceField(queryset=Event.objects.all(), widget=forms.HiddenInput()) class Meta: model = Participant fields = ['event', 'user'] and these are the functions def is_attending(request, event_id): """set user as attending an event.""" event = get_object_or_404(Event, id=event_id) attendance = Participant( participant = request.user, event = event, is_attending = True ) attendance.save() return redirect('show_event') in this function, one of the fields, the select multiply field, in which approval should occur only for those people whose event id matches def update_event(request, … -
Is there any way to prevent my bootsrap cards from getting nested by a django for loop?
The code is below: {% for task in tasks %} <div class="card text-center"> <div class="card-header"> <h5 class="card-title">{{ task.name }}</h5></div> <div class="card-body "> <h6 class="card-subtitle mb-2 text-muted"> Date due: {{ task.date }}. </h6> <p class="card-text"> {{ task.description }}</p> </div> {% empty %} <h4> Good to go!No tasks yet </h4> </div> <br/><br/> {% endfor %} When I run this, it nests the cards within each other as such: cards nested within each other -
Django Swagger integration not showing authenticated URls post clicking Authorize button
I am integrating Swagger with token based authentication for DRF APIs. Swagger displays documentation for all APIs when I use 'AllowAny' permission class for my API however once I start using 'IsAuthenticated' class, as expected, documentation for these APIs is not shown by default and I am presented with 'Authorize' button on UI. Once I click on it by adding valid 'Bearer JWT_Token' (which I get via calling token API via POSTMAN) it shows me 'Logout' and 'Close' button. With help of developer tools, I can see on clicking 'Authorize' button there is not server interaction, as a result of which I still unable to see documentation for these authenticated APIs. Below are settings I am using: SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { "api_key": { "type": "apiKey", "in": "header", "name": "Authorization" } } } # JWT Token Configuration SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } # REST Framework configurations REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 5, 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.AllowAny', ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', … -
Django run management command from python code and fetch exit status
I'm looking for a way to run a django management command and fetch its exit status, so if sys.exit(1) is called, then I'm looking for the 1 value. Secondly, if I could fetch the output of the management command (so not return values, but the result of the print statements), that'd be also a big hit. I tried to use StringIO, but unfortunately it's not capable - imho - to fetch the exit status, and not the print statements. It's a shame, but it's still python 2.7 and django==1.11.16 . -
Create a link based on input in django
<form action="player_profile/" method="GET"> <div class="row"> <div class="col-12 col-md-9 mb-2 mb-md-0"><input class="form-control" type="text" name="nickname" placeholder="Enter player's nickname..." style="height: 48px;background: var(--bs-body-color);border: 2px solid var(--bs-yellow);font-family: Alata, sans-serif;color: white;"></div> <div class="col-12 col-md-3"><button class="btn btn-primary btn-lg" type="submit" style="background: var(--bs-body-color);border: 2px solid var(--bs-yellow);font-family: Alata, sans-serif;">Search</button></div> </div> </form> I want to create link based on nickname input. I saw the way of using javascript but how should it be done in django? -
How to bring for whom the product is ordered to on front in Django
I am more of a beginner in Django and I need some help. I have adjusted that when every order product is ordered, every vendor(staff user) can see his/her own order product but no one else's. But as an Admin I want to see to whom the order product goes to. Here is my code. class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) #many to one relation with Category title = models.CharField(max_length=150) image = models.ImageField(null=False, upload_to='images/') price = models.DecimalField(max_digits=12, decimal_places=2,default=0) amount = models.IntegerField(default=0) detail = RichTextUploadingField() slug = models.SlugField(null=False, unique=True) def __str__(self): return self.title class OrderProduct(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() price = models.FloatField() amount = models.FloatField() def __str__(self): return self.product.title class OrderProductAdmin(admin.ModelAdmin): list_filter = ['user', 'product', 'status'] readonly_fields = ('user', 'code', 'product', 'price','quantity','amount') def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs return super().get_queryset(request).filter(product__user=request.user) def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "order": if request.user.is_superuser: kwargs["queryset"] = User.objects.all() else: kwargs["queryset"] = User.objects.filter(username=request.user.username) return super().formfield_for_foreignkey(db_field, request, **kwargs) -
submit button did not work after i click on that, if someone know the answer please answer me, I am actually new in django and want to solve this prob
The code i am using is on the git hub and i am trying to conver this website in django webapp. https://github.com/divanov11/StudyBud/tree/master/base facing a weird issue that after all why submit button did not work if any seniour here so please answer me... HTML Files: <div class="form__action"> <a class="btn btn--dark" href="{% url 'settings' %}">Cancel</a> <button class="btn btn--main" type="submit">Update</button> </div> This is the python file below and it looks like everythings is ok here PYTHON-models.py from django.db import models from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, ) image = models.ImageField( default='default.jpg', upload_to='profile_pics', ) class UserUpdateForm(forms.ModelForm): email = models.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): image = models.ImageField() class Meta: model = Profile fields = ['image'] This is another the python file below and it looks like everythings is ok here too PYTHON-views.py from django.shortcuts import render, redirect from .models import UserRegisterForm, UserUpdateForm, ProfileUpdateForm from django.contrib.auth.decorators import login_required @login_required def profile(request): return render(request, 'users/profile.html') @login_required def settings(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.settings) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() return redirect('profile') else: u_form = UserUpdateForm(request.user) p_form = ProfileUpdateForm(request.user.profile) … -
Django-HTML: Prompt Asking For Password When Pressing A Button
i would like to add a prompt everytime someone tries to press the button to 'Delete' and to 'Download' a file (in my project, you can upload files with passwords, so that if someone want to delete/download the file, he needs to enter a password). the password itself is saved in the models.py using django - how would i be able to to so in my code (listing my viwes.py to the html code, urls.py, models.py, forms.py, HTML CODE Itself) Thanks a lot. @login_required(login_url='login') def My_Files(request): files = File.objects.all() return render(request, 'home/My Files.html', {"files" : files}) path("MyFiles", views.My_Files, name="my_files"), path("MyFiles/<int:pk>/", views.delete_file, name="delete_file"), {% extends 'layouts/base.html' %} {% load static %} {% block title %} {% endblock title %} <!-- Specific CSS goes HERE --> {% block stylesheets %}{% endblock stylesheets %} {% block content %} {% include "includes/footer.html" %} <h2>My Files</h2> <table class="table"> <thead> <tr> <th>File Name</th> <th>File Description</th> <th>Uploaded By</th> <th>Download</th> <th>Delete</th> </tr> </thead> <tbody> {% for file in files %} <tr> <td> {{ file.File_Name }}</td> <td> {{ file.File_Type }}</td> <td> {{ file.Uploaded_By }}</td> <td> <a href="{{ file.File.url }}" class="btn btn-primary btn-sm" target="_blank"> Download File </a> </td> <td> <form method="post" action="{% url 'delete_file' file.pk %}"> {% csrf_token %} <button … -
Problème lors du deploiement d'un application django sur heroku
Bonjour a tout le monde, j'ai un probleme lorsque je deploie mon application les images qui ajouter dynamiquement don cceux qui se trouvent dans le dossier media s'afficher quand je les ajoutent via le site deja heberger ce qui est tout en fait normale. mais quand j'applique certaines modifications a local et je fais un git push pour une mise en jour de l'application les images qui etait entrain de bien s'afficher n'arrive plus à se charger. Je tenter de mettre en comantaire 'DATABASES['default'] = dj_database_url.config()' et la les images s'affiche sauf que d'autres donnes des autres tables sont maintenant aussi introuvable, comme les utilisateur de la table Users, .... Aider moi a trouver une solution. Merci d'avance ce une application Django -
Django Gunicorn web-app returns 500 error for new objects via form if being not connected to the server via SSH
The problem described in the title is quite strange: I deployed my Django web-app using gunicorn and nginx. When I set up my production webserver and then start my gunicorn workers and leave the command prompt open afterwards, everything works fine. However, when I close the command prompt, I always get a 500 Internal Server Error when trying to create a new object using the normal Django ModelForm handling. This only occurs: In production. When creating new objects directly using Djangos ModelForms. When the command prompt with ssh access to the webserver is closed. This also appears when stripe tries to call the webhook when the command prompt is closed. I implemented error handling for every single part of my view functions, so I can be sure that this has nothing to do with my code. I would strongly appreciate any ideas on what to check next or where the error could come from. Thanks in advance -
flutter future builder keeps loading one-to-many relationship
im tring to view tasks on alone screen from data using rest api dart django with project_id its one-to-many relationship project has many tasks so i want to dispay the tasks when i click on project widget using future builder here is usagae future builder and task list import 'package:flutter/material.dart'; import 'package:project/model/task_model.dart'; import 'package:project/project_dtetailForTest.dart'; import 'package:provider/provider.dart'; import 'new_project.dart'; import 'package:flutter/foundation.dart'; import 'package:http/http.dart' as http; class TaskById extends StatefulWidget { //const TaskById({ Key? key }) : super(key: key); final int project_id; //final Task task =Task(); TaskById({required this.project_id}):super(); @override State<TaskById> createState() => _TaskByIdState(); } class _TaskByIdState extends State<TaskById> { @override Widget build(BuildContext context) { final taskP= Provider.of<TaskProvider>(context); return Scaffold( backgroundColor: Colors.white, appBar: AppBar( elevation: 0, bottom: PreferredSize( child: Container( color: const Color(0xff94adb4), height: 2, width: 320, ), preferredSize: const Size.fromHeight(4.0)), centerTitle: true, backgroundColor:const Color(0xff076792), title: const Text( 'Project1', style: TextStyle(color: Colors.white, fontSize: 35, fontWeight:FontWeight.w700, shadows: [ Shadow( color: Color(0xa6A2B6D4), blurRadius:20), ] ), ), leading: IconButton( onPressed: () { Navigator.pop(context); }, icon: const Icon( Icons.arrow_back, size: 44, ), ), actions:[Container(padding: const EdgeInsets.fromLTRB(0, 0, 6, 3), child: IconButton( color:Colors.white , icon: const Icon( Icons.search, size: 44, ), onPressed: () {}, ), ),] ), //TaskProvider(){ // this.fetchTask(); // } body: FutureBuilder( future: TaskProvider().fetchTask(widget.project_id), builder: (context, … -
Django - why path is mentioned in different format for admin compared to our app
I am new to django , in urls.py why do we mention the path to our app as "path('appname/', include(appname.urls))" whereas for admin its mentioned as below "path('admin/', admin.site.urls)" Thanks. -
Access table in sqlite using django and query creation
I want to access data from table1, from my database and to make a query based on other table, using django. For example: access data from table1 (user, date, hour:minutes, city, check) and table 2 (user, date: hour:minute, latitude, longitudinal) and if the hour:minutes are the same in both table, I need to update the field check with the value True. I tried to access the data from table1 with objects.filter on user, date, but I think that it's not a good method, because it doesn't give me the values from the row. I read the documentation from https://docs.djangoproject.com/en/4.0/topics/db/queries/#copying-model-instances but I can not manage to do this correctly and finish it. And for the second part, I was thinking to make something with an if, but still not sure. In the beginning I need to access data from the table1. -
Best way to asynchronously send and receive using a socket with Django?
I've tried to use threading, background tasks, but neither work with sockets. I am looking into Django Channels but I can't find a tutorial where they use the sockets to connect to an external regular listening socket. What library should I use to use sockets asynchronously with Django? -
django app.models.VideoLibrary.DoesNotExist: VideoLibrary matching query does not exist
The problem is I can't type http://localhost:8000/1 to see spesific ViedoLibrary in my database. Can anyone help me to find the solution? urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('main/', views.main, name='main'), path('create_view/', views.create_view, name='create_view'), path('list_view/', views.list_view, name='list_view'), path('<id>', views.detail_view), ] views.py def detail_view(request, id): context = {} context['data'] = VideoLibrary.objects.get(shop_id=id) return render(request, 'app/detail_view.html', context) models.py class VideoLibrary(models.Model): shop_id = models.AutoField(primary_key=True, unique=True) shop_name = models.CharField(max_length=264) adress = models.TextField(max_length=264, default='') Also if I type id=id in views.py the next error pops up : Cannot resolve keyword 'id' into field. Choices are: adress, attendance, equipment, films, genre, income, shop_id, shop_name, staff. This are all my classes in models.py but there are also adress, shop_id and shop_name that are from specific model -
How do I create a 'couple' relationship in Django?
I've got a model called Couple. Couple describes the relationship between two Auth.User records. class Couple(models.Model): created = models.DateTimeField(auto_now_add=True) partner_one = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name='partner_one') partner_two = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name='partner_two') I'm having trouble referencing the partner in a reliable from their user model because now I need to know which is partner one, partner two. This is obviously not an elegant solution. Is there a better way to achieve what I'm trying to do here? -
Django development server not serving css files correctly (error : was blocked due to MIME type (“text/html”) mismatch)
I'm developing a Django webapp and have the issue with the following code in base.html: <!-- Theme CSS --> <link rel="stylesheet" type="text/css" href="{% static 'assets/css/style.css' %}"> The CSS get's blocked by the browser because of incorrect mimetype. Funny thing is that if I duplicate the line (so loading it twice), the css gets loaded properly. Already tried solutions: 1. Setting in main url the following code: if settings.DEBUG: urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 2. Adding the below code snippet to settings.py import mimetypes mimetypes.add_type("text/css", ".css", True) The rest of loading of static files works just fine. Thanks in advance. -
'This field is required" - Django Rest Auth registration via fetch request
I'm trying to setup dj rest auth but I keep getting a 400 error stating that 'This field is required' in regards to the username, password1 and password 2 fields. Registration works fine if I do it directly/manually from http://127.0.0.1:5000/dj-rest-auth/register/ URLs urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), path('dj-rest-auth/register/', include('dj_rest_auth.registration.urls')), path('dj-rest-auth/login/', LoginView.as_view()), path('dj-rest-auth/logout/', LogoutView.as_view()) ] Fetch const registerUser = async (body) => { const response = await fetch('http://127.0.0.1:5000/dj-rest-auth/register/', postRequestOptions(body)) console.log(response) } postRequestOptions: export const postRequestOptions = (body) => { return { method: "POST", headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', }, body: JSON.stringify({body}) } } I'm using React Hook Form so the data being passed is {"username":"test3","email":"test4@mail","password1":"tafasfss","password2":"tafasfss"} What am I missing here? -
how to submit html form data to django server and display output in real time using ajax
I need to be able to implement a form submit and display like this. My html form does not have a submit button, i'm using jquery to detect onchange event in each input fields then submit the form data. The goal is to have the output of the calculation updated in real time as the user types in the second form input field. Have done research however haven't found any article or similar implementation as this referenced in the link. Issues: My ajax code currently is able to submit form data, but it forces user to click somewhere else in the page in order for the form data to be submitted and output to display automatically.(Again not as expected behavior) The httpresponse from django view prints the raw output in a blank white html tab. The calculation is being handled by a python function back-end. How can i trick my code to have the same behavior as the one referenced in the link. my template and jquery ajax so far: {% extends "base.html" %} {% block title %}Two Way True Odd Finder{% endblock %} {% block content %} <script type="text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.js"></script> <script type="text/javascript"> $(document).ready(function () { $("#Odd1").on("change",function(){ if($("#Odd2").value … -
foreign key issue with my department model
I am getting the following error Cannot assign "u'167'": "Department.organization" must be a "Organization" instance. I have tried every way to send the Organization id but with no success. Request Method: POST Request URL: http://127.0.0.1:8081/profiles/api/createorganisation/ Django Version: 1.8.14 Exception Type: ValueError Exception Value: Cannot assign "u'167'": "Department.organization" must be a "Organization" instance. Exception Location: /usr/local/lib/python2.7/site-packages/django/db/models/fields/related.py in set, line 639 This is the model class Department(models.Model): """ Make department codes selectable and stuff """ organization = models.ForeignKey(Organization, related_name="departments") name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True, editable=False) users = models.ManyToManyField("CustomUser", related_name="departments", blank=True) enter code here Serializer class class DepartmentCreateSerializer(serializers.ModelSerializer): organization = serializers.CharField() name = serializers.CharField() slug = serializers.CharField() class Meta: model = Department fields = ('pk','organization','name','slug') This is my code org = Organization.objects.get(slug="tata5").id department = { "organization":org, "name" : "finance1", "slug" : "finance1" , } logging.warning(department) instance = DepartmentCreateSerializer(data=department) instance.organization = org instance.is_valid(raise_exception=True) instance.save() # createDepartment.is_valid() # createDepartment.save() return Response(instance, status=status.HTTP_200_OK) -
Invalid literal int() with base 10: '[' when doing a filter with request.body
def patch(self, request): Claim.objects.filter(id__in=request.body, presented_to_client=False).update(presented_to_client=True, presented_to_client_date=datetime.datetime.now()) return HttpResponse(status=200) I'm trying to update some of my objects this way. But I get invalid literal for int() with base 10: '[' so I thought I might need to cast my request.body to list, and I tried it this way: def patch(self, request): Claim.objects.filter(id__in=list(request.body), presented_to_client=False).update(presented_to_client=True, presented_to_client_date=datetime.datetime.now()) return HttpResponse(status=200) and I still get the same error. Why is this happening? If I hardcode it this way: id__in=[8] I don't get any errors. Thanks. -
How to read radio button value and use it from FORM in view.py file
This is the code that's in the <fieldset class="form-group"> <div class="row"> <div class="col-sm-10"> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="transaction" id="deposit" value="deposit" checked="checked"> <label class="form-check-label" for="deposit"> Deposit </label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="transaction" id="deduction" value="deduction"> <label class="form-check-label" for="deduction"> Deduction </label> </div> </div> </div> </fieldset> I'm trying to take the 'transaction' and use it view.py and the calculations would be something like this in view.py: def form_valid(self, form): if (#deposit is checked): newFinanceTotal = currentUserTotal + value else: newFinanceTotal = currentUserTotal - value form.save() return super().form_valid(form) And this is what I have in models.py: class Finance(models.Model): FINANCE_CHOICES = ( ('DP', 'Deposit'), ('DD', 'Deduction'), ) transaction = models.CharField(max_length=2, choices=FINANCE_CHOICES,)transaction = models.CharField(max_length=2, choices=FINANCE_CHOICES,) forms.py: class FinanceForm(forms.ModelForm): class Meta: model = Finance fields = ('entryName', 'entryDate', 'transaction', 'value') -
Object's ManyToMany relationship is not updated inside signals
I have this singal @receiver(post_save, sender=Organization) def save_tags(sender, instance, **kwargs): from .views import post text_input_tags = post.getlist('tags1')[0] text_input_tags = text_input_tags.strip() text_inputs_tags = text_input_tags.split(' ') for tag in text_inputs_tags: if not tag.startswith('#') : tag = '#' + tag tag_obj = Tag.objects.get_or_create(name = tag)[0]#.organization_set.set([obj,]) tag_obj.save() instance.tags.add(tag_obj) print(instance.tags.all()) from the views I am importing the post data to use inside the signal. There is a manytomany relationship between two models Organization and Tag. I am trying to get some attributes from the post request and create a Tag object from them, then after that add that Tag object into the ManyToMany relationship of the instance of the Organization. when I print the tags of the organization instance print(instance.tags.all()) I get the added instances in the QuerySet, but it's not saved in the organization instance and I don't understand why... -
Query in sqlite using django [duplicate]
I want to access data from table1, from my database and to make a query based on other table, using django. For example: access data from table1 (date, hour:minutes, city, check) and table 2 (date: hour:minute, latitude, longitudinal) and if the hour:minutes are the same in both table, I need to update the field check with the value True. I tried to access the data from table1 with objects.filter, but I think that it's not a good method, because it doesn't give me the values from the row. I read the documentation from https://docs.djangoproject.com/en/4.0/topics/db/queries/#copying-model-instances but I can not manage to do this correctly and finish it -
Django authenticate() command returns None
I am creating a user in django and i'm trying to log them in also. For some reason the authenticate() command returns None. I am using a custom user model. I am passing email and password paramaters to the authenticate() command (I have replaced username for email) and they both have values as I have checked this. Could I have any suggestions? Here is the code: views.py email = request.POST.get("email") password = request.POST.get("password") account_id = ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase + string.digits, k=500)) CustomUser.objects.create(email=email,password=password,account_id=account_id) if user is not None: login(request, user) else: # Stuff models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import gettext_lazy as _ class UserManager(BaseUserManager): def _create_user(self, email, password, **kwargs): if not email: raise ValueError("Email is required") email = self.normalize_email(email) user = self.model(email=email, **kwargs) user.set_password(password) user.save() return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **kwargs): kwargs.setdefault('is_staff', True) kwargs.setdefault('is_superuser', True) kwargs.setdefault('is_active', True) if kwargs.get('is_staff') is not True: raise ValueError("Superuser must have is_staff True") if kwargs.get('is_superuser') is not True: raise ValueError("Superuser must have is_superuser True") return self._create_user(email, password, **kwargs) class CustomUser(AbstractUser): username = None …