Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problems adapting multiple form wizard with a formset
I have a question, what happens is that I am using 3 formsets in a multiple way that appear on the same page. But I don't know how to save the data of each form. I've seen them recommend django-multipleformwizard and django-formtools-addons but at no time do I see them use them for a formset. I'm going to add my view to know how I can adapt it. views.py def create_Presupuestos(request): extra_forms = 1 ParteFormSet = formset_factory(PresupuestosParteForm, extra=extra_forms, max_num=20) ManoObraFormSet = formset_factory(PresupuestosManoObraForm, extra=extra_forms, max_num=20) PagosFormSet = formset_factory(PresupuestosPagosForm, extra=extra_forms, max_num=20) presupuestosclientesform=PresupuestosClientesForm(request.POST or None) presupuestosvehiculosform=PresupuestosVehiculosForm(request.POST or None) presupuestosparteform=PresupuestosParteForm(request.POST or None) presupuestosmanoobraform=PresupuestosManoObraForm(request.POST or None) presupuestospagosform=PresupuestosPagosForm(request.POST or None) presupuestosfotosform=PresupuestosFotosForm(request.POST or None) if request.method == 'POST': formset = ParteFormSet(request.POST, request.FILES) manoObra_formset = ManoObraFormSet(request.POST, request.FILES,prefix='manoobra') pagos_formset = PagosFormSet(request.POST, request.FILES, prefix='pagos') #formset = ParteFormSet(request.POST, request.FILES,prefix='__form') if formset.is_valid() and manoObra_formset.is_valid() and pagos_formset.is_valid(): presupuestosclientesform.save() return redirect('presupuestos:index') else: formset = ParteFormSet() manoObra_formset = ManoObraFormSet(prefix='manoobra') pagos_formset = PagosFormSet(prefix='pagos') presupuestosfotosform = PresupuestosFotosForm(request.POST or None) return render(request,'Presupuestos/new-customer.html',{ 'presupuestosclientesform':presupuestosclientesform, 'presupuestosvehiculosform':presupuestosvehiculosform, 'presupuestosparteform':presupuestosparteform, 'presupuestosmanoobraform':presupuestosmanoobraform, 'presupuestospagosform':presupuestospagosform, 'presupuestosfotosform':presupuestosfotosform, 'formset':formset, 'manoObra_formset':manoObra_formset, 'pagos_formset':pagos_formset }) -
Getting request.data as an empty dictionary
I have a viewset like the follwing class DummyViewSet: def create(self, request, *args, **kwargs): variable_a = 5 return another_api_end_point(request, variable_a) ---> request.data: {"a":"value1", "b": "value2"} @api_view(['POST']) another_api_end_point(request, variable_a) print(request.data) ---> request.data: {} print(variable_a) ---> variable_a: 5 return "Some Response" Why I can able to see variable_a's value as it is but request.data as empty? Debugging it from hours now. If anyone knows the reason for it, please revert. It would be a great help. -
Change the rows with the same cell value in the same color in HTML table - Django project
I created a table in my html file for my Django project, and the raw data is based on the following list (It's a very long list, so I only list a few lines): mylist=[{'StartDate': '2021-10-02', 'ID': 11773, 'Receiver': Mike, 'Days':66 },{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Jane, 'Days':65}, ... {'StartDate': '2021-10-5', 'ID': 34653, 'Receiver': Jack, 'Days':63}] My Html file: <table class="table table-striped" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>StartDate</th> <th>ID</th> <th>Name</th> <th>Days</th> </thead> <body> {% for element in mylist %} <tr> <td>{{ element.StartDate}}</td> <td>{{ element.ID }}</td> <td>{{ element.Receiver }}</td> <td>{{ element.Days }}</td> </tr> {% endfor %} </tbody> </table> I want to make all the rows with the same ID value the same color. Please advise what I should add into the <td>{{ element.ID }}</td>. Thank you! -
dajngo qrcode FileNotFoundError
I am trying to save qrcode image in django mode but when i save am getting the error saying Errno 2] No such file or directory: '/home/mecatheclau/django/ines_campus/main/static/media/degree/qrcode/2.png' Django code def save(self, *args, **kwargs): if not self.qrcode: import qrcode from django.core.files import File from django.conf import settings as appsettings from django.core.files.uploadedfile import InMemoryUploadedFile qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=2, border=0, ) qr.add_data("https://digitalsnatch.ines.ac.rw/degree/%s/preview/"%(self.pk)) qr.make(fit=True) img = qr.make_image() filename = "degree/qrcode/"+str(self.pk)+".png" imagepath = appsettings.MEDIA_ROOT+"/degree/qrcode/"+str(self.pk)+".png" img.save(imagepath) # self.qrcode.save(filename, imagepath, save=True) self.qrcode = filename super().save(*args, **kwargs) img.save(imagepath) returning can't proccess file what am doing wrong -
How to start wirh custom result backend in celery?
In advance im sorry if I'm not so specific with my question. I want to create a custom result backend but I don't know how to start and the documentation that I found is not very clear to me, does any of you know of any example or document that can guide me? I was thinking on create a class and assignt it in my celery.py like this RESULT_BACKEND='my_class' But I doubt this works, any advice will be really helpful. Thanks -
Django rest API make sure email is verified before giving API token
I'm making a Django REST framework for a JSON API, and I want to authenticate Users with a token (so, API request will be something like .../api/dosomething/{user} Token: ...). Django REST documentation shows how to expose an endpoint for token generation with username/password - however, I'd like to make sure that the email is verified before giving out the token. I don't want to send the token itself to the email, email verification should either be a link or a 6-digit code. Is there a default way of doing this in Django? I was thinking of doing the following - on registering at api/register, user provides username/email and password, account gets created (but no token so they can't use the API). To get the token, a user needs to hit api/generate_token endpoint with username and password. This will generate a random 6-digit code in the backend, store/update the user/code/created_at in the custom model, send an email with the code, and return a message "please verify your email with 6 digit code". There will be an endpoint api/verify_email_token which takes username and verification code. If user/code pair is in the DB and created in the last 30min, it'll create and return … -
how to delete a session in django through python shell?
As we know we can delete cache through python shell by typing python manage.py shell from django.core.cache import cache cache.clear() is there any way to delete django sessions through shell? -
How to change the validation error color and position in Django?
I am new to Django. I am trying to make a simple form to match the password. However, when I enter different passwords and press the Save button I get a black validation error above the form. I want to change the error color and position to appear in red color beside or below the control. Here newuser.html: {% block content %} <form method="POST"> {% csrf_token %} <table> {{frmNewUser.as_table}} {% for error in frmNewUser.password.errors %} {% comment %} I tried frmNewUser.non_field_errors too {% endcomment %} <p>{{error}}</p> {% endfor %} </table> <input type="submit" name="Save" value="Save" colspan=2> </form> {% endblock content %} Here forms.py: class NewUserFrom(forms.Form): username = forms.CharField(max_length=50, widget=forms.TextInput) password = forms.CharField(widget=forms.PasswordInput) confirm_password = forms.CharField(label="Confirm password", widget=forms.PasswordInput) name = forms.CharField(max_length=50, widget=forms.TextInput) email = forms.EmailField(max_length=50, widget=forms.EmailInput) def clean(self): cleaned_data = super().clean() pwd = cleaned_data.get('password') cof_pwd = cleaned_data.get('confirm_password') if pwd and cof_pwd: if pwd != cof_pwd: raise forms.ValidationError('Password is not match.') return super().clean() Here views.py: from django.shortcuts import render from django.http import HttpResponse, request from django.db import connection from django.contrib.auth.decorators import login_required import pyodbc from .forms import NewUserFrom def newUser(request): form = NewUserFrom(request.POST) if not form.is_valid(): context = {'frmNewUser':from} return render(request,'login/newuser.html', context) return render(request, "login/welcome.html") -
Python django how i can prevent the duplicate entry of studnumber,email,username(unmae) in registration
Python django how i can prevent the duplicate entry of studnumber,email,username(unmae) in registration? i use this code before when it us one full name its work but when I divide it to (nmane),(mname),(nnmae), it always saying duplicate record. even their is no similar record on db MODELS.py from django import forms from django.db import models class newacc(models.Model): studnumber=models.IntegerField() fname=models.CharField(max_length=150) mname=models.CharField(max_length=150) lname=models.CharField(max_length=150) age=models.IntegerField() gender=models.CharField(max_length=1) uname=models.CharField(max_length=150) email=models.CharField(max_length=150) pwd=models.CharField(max_length=150) contact=models.IntegerField() class Meta: unique_together = ('studnumber','email','uname') class NewACCForm(forms.ModelForm): class Meta: model = newacc fields = "__all__" Views.py from django.shortcuts import redirect, render from register.models import newacc from django.contrib import messages from django.db.models import Q#disjunction sa email and uname: from register.models import NewACCForm def Unreg(request): if request.method=='POST': form = NewACCForm(request.POST) if form.is_valid(): form.save() messages.success(request,"The New User is save !") else: messages.error(request, "Duplicate Reccord.") return render(request,'Registration.html') -
DJANGO 3.2 wont load images from declared media folder 404 error
#urs.py urlpatterns = [ ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #setting.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = 'media/' #model images = models.ImageField(upload_to='BonusVilla/image/', blank=True) #tempalte {%for i in images%} <img src="{{ i.images.url }}" /> {%endfor%} #the browser it renders this <img src="/media/BonusVilla/image/apple_3H8ByYb.jpg"> -
Django: Eccomerce website. When I proceed the checkout it's saving the order if person is not logged in, but when it's not AnonymousUser error
I am working on ecommerce website and it's time to make checkout. In my website, when to order product without an account it's saving the order, but if it's with an account, it's going to another page, but not erasing a cart and isn't saving the order. What is the problem? Can you please help me to solve this problem. It's not working only when client is logged in an account. views.py def processOrder(request): transaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) tel = data['shipping']['number'], address=data['shipping']['address'], city=data['shipping']['city'], state=data['shipping']['state'], if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) else: customer, order = guestOrder(request, data) total = float(data['form']['total']) order.transaction_id = transaction_id order.tel= tel order.address=address order.city=city order.state=state if total == order.get_cart_total: order.complete = False order.save() return JsonResponse('Payment submitted..', safe=False) html <form class="form" method="POST" action="#" id="form"> <div class="row"> <div class="col-lg-6 col-md-6 col-12" id="user-info"> <div class="form-group"> <label>Имя<span>*</span></label> <div> <input type="text" name="name" placeholder="" required="required"></div> </div> </div> <div class="col-lg-6 col-md-6 col-12" id="user-info"> <div class="form-group"> <label>Фамилия<span>*</span></label><div> <input type="text" name="surname" placeholder="" required="required"></div> </div> </div> <div class="col-lg-6 col-md-6 col-12" id="user-info"> <div class="form-group"> <label>Email<span>*</span></label><div> <input type="email" name="email" placeholder="" required="required"></div> </div> </div> <div class="col-lg-6 col-md-6 col-12" id="user-info shipping-info"> <div class="form-group"> <label>Номер телефона<span>*</span></label><div> <input type="number" name="number" placeholder="" required="required"></div> </div> </div> <div class="col-lg-6 col-md-6 col-12" … -
What is used where and how in Django 2022?
!Complete Beginner! I went into Django with the background of building Sass web apps. CSS, HTML, Django and you have something working, I thought. After some weeks now you also have the basics, but there you quickly reach your limits if you want to create "useful/modern" web apps Today I was thrown off with terms like "Ajax XMLHttpRequest needed" "django without javascript does not work" htmx? or javascript? Or both? json files, is this like a model in django? Random people talking about outdated Django features I have enough time to deal with everything, but for that I would have to know with what. Can someone explain to me, using a "modern" site like Twitter/YouTube/a web app, what is needed where now? Django tutorials may tell you how to create 1000 forms and create a To Do list, but that's as far as it goes. Down voting questions on stackoverflow, keep it. You knew everything from the beginning, you are so successful ^^ -
Uncaught SyntaxError: redeclaration of const check
I am working in django and i have written a simple code for dark and light theme, it is working perfectly, but when i inspect my page, it shows an error 'Uncaught SyntaxError: redeclaration of const check', so this is my js code, please tell me how i get rid of this error. const check=document.getElementById("check") if (localStorage.getItem('darkMode')===null){ localStorage.setItem('darkMode', "false"); } const link = document.createElement('link'); link.rel = 'stylesheet'; document.getElementsByTagName('HEAD')[0].appendChild(link); checkStatus() function checkStatus(){ if (localStorage.getItem('darkMode')==="true"){ check.checked = true; link.href = './static/css/modes/dark-mode.css'; }else{ check.checked = false; link.href = './static/css/modes/light-mode.css'; } } function changeStatus(){ if (localStorage.getItem('darkMode')==="true"){ localStorage.setItem('darkMode', "false"); link.href = './static/css/modes/light-mode.css'; } else{ localStorage.setItem('darkMode', "true"); link.href = './static/css/modes/dark-mode.css'; } } please help me -
How to change the chart data in bootstrap template for Django Project
I'm using the "start bootstrap" template for my Django project. I want to edit my own data in the sample chart. I think I need to change it in the "chart-pie-demo.js" file. However, the chart doesn't change when I edit any data. The code that is related to my chart in the "chart.html" is: <!-- Donut Chart --> <div class="col-xl-4 col-lg-5"> <div class="card shadow mb-4"> <!-- Card Header - Dropdown --> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">Donut Chart</h6> </div> <!-- Card Body --> <div class="card-body"> <div class="chart-pie pt-4"> <canvas id="myPieChart"></canvas> </div> <hr>Styling for the donut chart can be found in the <code>/js/demo/chart-pie-demo.js</code> file. </div> </div> </div> <!-- Page level plugins --> <script src="{% static 'Chart.min.js' %}"></script> <!-- Page level custom scripts --> <script src="{% static 'chart-area-demo.js' %}"></script> <script src="{% static 'chart-pie-demo.js' %}"></script> <script src="{% static 'chart-bar-demo.js' %}"></script> My "chart-pie-demo.js" which is under "static" is: var ctx = document.getElementById("myPieChart"); var myPieChart = new Chart(ctx, { type: 'doughnut', data: { labels: ["Direct", "Referral", "Social"], datasets: [{ data: [55, 30, 15], backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc'], hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf'], hoverBorderColor: "rgba(234, 236, 244, 1)", }], }, options: { maintainAspectRatio: false, tooltips: { backgroundColor: "rgb(255,255,255)", bodyFontColor: "#858796", borderColor: '#dddfeb', borderWidth: 1, xPadding: 15, … -
How do i query children fields belonging to a parent class. Django
Navigation menu in real site do have dropdown menu when neccessary. That's exactly what i want to achieve here. The NavMenu class is the title you see in NavBar i.e Services. The Item class is the submenu under a NavMenu i.e List of services that appear under the service tab In my code i want to call the submenu that are under a particular title i.e Submenus under Service My Model: class NavMenu(models.Model): title = models.CharField(max_length=50) def __str__(self): return self.title class Item(models.Model): category = models.ForeignKey(NavMenu, on_delete=models.CASCADE) title = models.CharField(max_length=50) def __str__(self): return self.title class ItemMedia(models.Model): category = models.ForeignKey(NavMenu, on_delete=models.CASCADE, null=True) menu_item_p = models.ImageField() description = models.CharField(max_length=100) My views.py: class IndexPageView(TemplateView): model = NavMenu, Item, ItemMedia, template_name = 'index.html' extra_context = { 'navmenu': NavMenu.objects.order_by('title'), 'submenu': NavMenu.category_set.all(), 'media_items': NavMenu.category_set.all(), } -
How to perform 'SELECT a or b < c FROM Table' on Django QuerySet?
I have the following model: class DiscountCoupon(models.Model): is_used = models.BooleanField(default=False) expiration_date = models.DateField() def is_available(self): if self.used or self.expiration_date <= date.today(): return False return True Instead of calling the is_available method iterating through a QuerySet, I want to do this operation into the QuerySet to perform better, like this: SELECT (used OR (expiration_date < Now())) AS is_available FROM randomapp_discountcoupon; Is this possible? -
Image Upload from a different modal's view
So I have two models and in the update method of the first modal' viewset,(using model viewset) I'm trying to add an image to my second model but facing issues. def update(self, request, *args, **kwargs): data = request.data instance = self.get_object() serializer = self.get_serializer(instance, data=data) # partial=partial) if serializer.is_valid(raise_exception=True): # get image from recieved data # profileImage = data["profileImage"] profileImage = request.data.get("profileImage", None) ## update first modal self.perform_update(serializer) ## add an image to second modal, secondModel.objects.filter(user=request.user.id).update(profileImage=profileImage) I can see the url of image getting added but there is no image in the media directory. Actually I'm updating other field also, thats working fine but having issue in this image field. While direct updating in the views of the second models there is no issue. Sending formData from the frontend. So is there a different way dealing with file objects ? -
Add user's email when sending email in Django Rest Framework
I've got this working serializer: class ReportAnswerSerializer(serializers.ModelSerializer): complain_by = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) answer = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = ModerateAnswer fields = ('answer', 'moderate_reason', 'moderate_comment', 'complain_by') extra_kwargs = {'moderate_reason': {'required': True}} def create(self, validated_data): instance = super(ReportAnswerSerializer, self).create(validated_data) send_mail( 'Dziękujemy za zgłoszenie', 'Zgłosiłeś odpowiedź: {}. Team Deor zajmie się teraz tą wiadomością'.format(instance.answer), 'info@deor.pl', [mail@mail.com], fail_silently=False, ) return instance But i don't want to statically send email. Everytime a user reports an answer i want to send them a mail "Thanks for reporting the answer" But i dont know how to format the [mail@mail.com] dynamically. I am using a custom user model. class CustomUser(AbstractUser): first_name = models.CharField(max_length=50, null=True) last_name = models.CharField(max_length=50, null=True) slug = models.SlugField(max_length=30, unique=True, null=True, blank=True, editable=False) email = models.EmailField(blank=False, unique=True) number_of_points = models.IntegerField(default=0) facebook_profile = models.CharField(max_length=128, null=True, blank=True) instagram_profile = models.CharField(max_length=128, null=True, blank=True) twitter_profile = models.CharField(max_length=128, null=True, blank=True) package = models.CharField(max_length=128, null=False, default='L') paid_till = models.DateField(null=True, blank=True) package_downgraded = models.CharField(max_length=128, null=True, blank=True) sex = models.CharField(max_length=128, null=True, blank=True) location = models.ForeignKey(City, on_delete=models.CASCADE, null=True, blank=True) badges = models.ManyToManyField('users.Badge', blank=True) Do you have any idea how to do it? -
similarity word with Trigram
how i make a function for word similarity in search result. For example if i write in my search form "ugo" or "hugo". i try this : ("contenue" is my txt files in db postgresql) views.py class SearchResultsList(ListView): ... ... ... def get_queryset(self): query = self.request.GET.get("q") vector_column = SearchVector("contenue", weight="A", config='french') search_query = SearchQuery(query) search_headline = SearchHeadline("contenue", search_query) result1 = Q(contenue__search=query) result2 = Q(SearchVector("contenue")) return Actes.objects.filter(result1).annotate(headline=search_headline) .annotate(similarity=TrigramSimilarity('contenue', query),) .filter(similarity__gte=0.6).order_by('-similarity') when i don't add trigram i have a result but not work if i write "ugo" instead of "hugo" or "higo" instead of "hugo". Thank and sorry for my bad english -
mock django.core.mail.send_mail in another function
I want to mock django's send_mail() so that it throws an Exception. My approach is as below, but mails are still being sent, and no Exceptions being thrown. It works if I call send_mail() directly within the context manager, but not if I call a function that imports and then uses send_mail() # test.py import handle_alerts from unittest import mock class MailTest(TestCase): def test_handle_alerts(self): with mock.patch("django.core.mail.send_mail") as mocked_mail: mocked_mail.side_effect = Exception("OH NOES") handle_alerts() # ends up using send_mail # handle_alerts.py from django.core.mail import send_mail def handle_alerts(): send_mail(....) # valid call goes here -
Method not allowed when I do a get request from flutter web to Django server( both in same host)
I've hosted my Django backend server on VPS and used apache2 to run it, when I do requests from my flutter app running locally as debug it works perfectly, then I hosted the flutter web application in the same server under Django itself by creating a directory inside Django root and added a redirect to it from the Django URLs. I've used this method to add flutter web to Django it works normally and opened the flutter app but when the application sends a request to the django it saves this error in the apcahe2 errors.log [Fri Feb 04 14:06:08.154190 2022] [wsgi:error] [pid 17002:tid 140068315830016] [remote 156.194.221.19:59776] Method Not Allowed: /static-pages/api/on_boarding/ -
Python dictionary in jQuery
I've an ajax call in my html of a django application. How can I handle the returned object in javaScript if my python backend returns a list that includes python dictionary: html: $.ajax({ type: "GET", url: '/api/check_variable/?name='+$("#foo").val()+'&stat='+stat_id, data: "check", success: function(response){ alert("response[2]); } )} urls.py: urlpatterns = [ path("check_variable/", views.api_for_class_checking, name="check_variable"), ] views.py: def api_for_class_checking(request, **kwargs): return ['id1', 'id2',{'filabel': 'label F', 'svlabel': 'labelS', 'enlabel': 'labelEn'}] In this case my html page alerts just Object as response[2]. How can I get the attributes of the returned object, like the value of 'filabel' e.g. ? -
Create a new model in Django linked tothe User table
I'm new to Django and I've correctly created my first web app where I can register and login as an user. I'm using the standard from django.contrib.auth.models import User and UserCreationFormto manage this thing. Now, I would like to create a new table in the database to add new fields to the user. I'm already using the standard one such as email, first name, second name, email, username, etc but I would like to extend it by adding the possibility to store the latest time the email has been changed and other info. All those info are not added via the form but are computed by the backend (for instance, every time I want to edit my email on my profile, the relative field on my new table, linked to my profile, change value) To do that I have added on my models.py file the current code from django.db import models from django.contrib.auth.models import User class UserAddInformation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) last_time_email_change = models.TimeField('Last email changed', auto_now_add=True, blank=True) def __str__(self): return self.user.username And on my admin.py from django.contrib import admin from .models import UserAddInformation admin.site.register(UserAddInformation) The form to edit the email and the view can be found below forms.py class … -
CSS overflow not working with flex-grow or width/height in per cent
I am facing a problem that I don't really understand with the overflow of CSS. css: * { margin: 0; padding: 0; } html { height: 100%; } body { display: flex; flex-direction: column; font-weight: 400; font-family: 'Arial'; } .simulations { display: flex; width: 80%; margin: auto; padding: 5px 10px; margin-top: 50px; border-radius: 20px; box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px; } .waiting-list { flex-grow: 1; } .waiting-list h3 { text-align: center; } .waiting-list .list { display: flex; margin-top: 10px; padding: 0px 5px 5px 5px; overflow-x: scroll; } .waiting-list .list .element { width: 200px; text-align: center; border-radius: 20px; border: 2px solid black; } .button { display: flex; margin-left: 10px; } .button img { margin: auto; width: 30px; cursor: pointer; } HTML (I am using Django): {% load static %} <!DOCTYPE html> <html> <head> <title>Test</title> <link rel="stylesheet" type="text/css" href="{% static 'css/test.css' %}"> </head> <body> <div class="simulations"> <div class="waiting-list"> <h3>Waiting list</h3> <div class="list"> {% for i in "x"|rjust:"10" %} <div> <div class="element"> <h4>Title</h4> <p>size</p> </div> </div> {% endfor %} </div> </div> <div class="button"> <img src="https://img.icons8.com/external-prettycons-lineal-prettycons/49/000000/external-enter-essentials-prettycons-lineal-prettycons.png"/> </div> </div> </body> </html> Visual of this code As you can see on the picture, the waiting list class is going over the button instead of … -
UserManager.create_user() missing 1 required positional argument: 'username' error while logging in with python-social-auth
I have created a custom AbstractUser user model and I am using python-social-auth to log in the user via Steam. But when I try to log in the user I will get this error. I have tried adding username to REQUIRED_FIELDS but both ways I get the same error. models.py from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): username = models.CharField(max_length=200, null=True) name = models.CharField(max_length=200, unique=True) steam_name = models.CharField(max_length=32, blank=True) steam_id = models.CharField(max_length=17, unique=True, blank=True, null=True) extra_data = models.TextField(null=True) is_active = models.BooleanField(default=True, db_column='status') is_staff = models.BooleanField(default=False, db_column='isstaff') is_superuser = models.BooleanField(default=False, db_column='issuperuser') USERNAME_FIELD = "name" REQUIRED_FIELDS = ["username"] pipeline.py from .models import CustomUser def save_profile(backend, user, details, response, *args, **kwargs): CustomUser.objects.get_or_create( steam_name = user, steam_id = details['player']['steamid'], extra_data = details['player'], ) settings.py AUTH_USER_MODEL = 'main.CustomUser' SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'main.pipeline.save_profile', )