Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How is data returned from form.clean_data() ? How does Django filter the input and on what basis is the dictionary created wrt keys and values?
Add a new task: def add(request): # Check if method is POST if request.method == "POST": # Take in the data the user submitted and save it as form form = NewTaskForm(request.POST) # Check if form data is valid (server-side) if form.is_valid(): # Isolate the task from the 'cleaned' version of form data task = form.cleaned_data["task"] # Add the new task to our list of tasks tasks.append(task) # Redirect user to list of tasks return HttpResponseRedirect(reverse("tasks:index")) I have a question about the data that is returned from form.cleaned_data , I read that it is a dictionary but what keys are used in that dictionary? In the code above, it is quite clear that data is being accessed from a key called "task" but where does Django look for these keys from since it is django which returned the dictionary and they are not keys the code writer defined. -
ModuleNotFoundError: No module named 'foodncups'
I get this error when I try to open the site that I hosted on pythonanywhre ModuleNotFoundError: No module named 'foodncups' here is my Django WSGI: # +++++++++++ DJANGO +++++++++++ # To use your own django app use code like this: import os import sys # ## assuming your django settings file is at '/home/yazedraed20/mysite/mysite/settings.py' ## and your manage.py is is at '/home/yazedraed20/mysite/manage.py' path = '/home/yazedraed20/foodncups' if path not in sys.path: sys.path.append(path) os.chdir(path) os.environ.setdefault("DJANGO_SETTINGS_MODULE","foodncups.project.settings") import django django.setup() # #os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' # ## then: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() -
Django fullstack: How do I display two videos that play simultaneously using only 1 controller?
I'm a complete beginner, so excuse me if this is something naive. I have this project that I'm working on for a job. I want to make two videos (the same lengths exactly) to display next to each other with only 1 controller (pause, play, forward, etc) to control both of them at the same time. How do I go about that? -
How can I iterate over submitted django forms in a formset?
I'm trying to make a questionnaire that will be dynamic. All questions' answers are only 1 to 5. On the webpage, all looks great but when the HTML form is submitted, even the loop finishes well but it seems like only one form is being submitted (3 displayed and filled in in total). When I try to iterate over submitted forms in the formset, I can access only the last item/form from the formset. I have tried to use the zip function too but with no success. my views.py def questionnaire(request, questionnaire_id): the_questionnaire = Questionnaire.objects.get(id=questionnaire_id) related_questions = QuestionnaireQuestion.objects.filter(questionnaire__id=questionnaire_id) formset = QuestionnaireAnswerFormSet() combined = zip(related_questions, formset) form = QuestionnaireQuestionForm() if request.method == 'POST': submited_formset = QuestionnaireQuestionFormSet(request.POST) if submited_formset.is_valid(): print(submited_formset) print("ok1") for form in submited_formset: print("ok2") if form.is_valid(): obj = QuestionnaireQuestionForm() obj.option_one = form.cleaned_data['option_one'] print("ok3") print(obj.option_one) # messages.success(request, 'Hotovo') # return HttpResponseRedirect('/questionnaires') else: return render(request, 'questionnaire_1.html', {'formset': formset}) context = { "the_questionnaire": the_questionnaire, "related_questions": related_questions, "formset": formset, "combined": combined, "the_form": form, } return render(request, 'questionnaire_1.html', context) template.html <form method="POST" style="text-align: center"> {% csrf_token %} {% for question in related_questions %} <div class="col-lg-12"> <h2>{{ question.question }}</h2> </div> <div class="col-lg-12"> <h2>{{ formset }}</h2> </div> {% if forloop.last %} <button type="submit" class="btn btn-info"> Submit </button> … -
Where do I apply my client certificate for mutual TLS in a Django environment?
My application needs to send a request to get some information from another server. This server has locked down its endpoints using Mutual TLS - meaning it inherently trusts no-one unless explicitly authorised. My application has been explicitly authorised to access this server/API and I have been issued with a client certificate to send with my requests. I have successfully hit the server endpoint via Postman - sending my client certificate with the request and getting a 200 back. I would now like to make the same request inside my Django/Ember application. My problem is I can't find documentation or a library that will let me send my client certificate. https://github.com/drGrove/mtls-cli looks promising but doesn't work with Windows. All other libraries seem to be for someone hosting the API that is locked down with mutual TLS - not the consumer of the API. Is Django the correct place to be adding this certificate or does it need to be added higher up, for example in AWS? -
Use Class Field Other than ID or Slug in URL
I want to access an object by an field other then ID or Slug for Django's DetailView, like so: http://example.com/product/name My model is like so: class Product (models.Model): name = models.CharField(max_length=50, help_text="Full name") View: class ProductDetail(DetailView): model = Product URLConf: urlpatterns = [ path('product/<name>', ProductDetail.as_view(), name='product-detail'), ] I'm not sure what should go in the URLConf. Note that my templates are working and I can access the object by ID as usual: http://example.com/product/1 -
Sending Email From My Server Causes 500 Error, But In Development Is Okay
I am sending emails from my Django website. In development this works fine, however when it's ran from my production server msg.send() causes it to crash. I don't know why as all related settings are the exact same on both development and server versions (other code such as db changes, but I've isolated this other code and it's not the issue). DEFAULT_FROM_EMAIL = '####@####.####' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp-mail.outlook.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '####@####.####' EMAIL_HOST_PASSWORD = '####' msg = EmailMessage(subject, body, '####@####.####', [to_email]) msg.send() Thank you. -
how to get sum of every objects by queryset (object by object )
i have no expernce with 'aggregation' and 'annotate' and talk with exemple better i have this object : mediasec = MediaSec.objects.filter(date__range=[primary1, primary2], degraycomany__in=degraycompsec) if i print it after convert it to list and loop will get this dict : {'id': 5, 'degraycomany_id': 5, 'nomberhisas': 3, 'date': datetime.date(2020, 9, 25)} {'id': 8, 'degraycomany_id': 5, 'nomberhisas': 1, 'date': datetime.date(2020, 9, 27)} {'id': 9, 'degraycomany_id': 5, 'nomberhisas': 1, 'date': datetime.date(2020, 9, 27)} {'id': 10, 'degraycomany_id': 5, 'nomberhisas': 1, 'date': datetime.date(2020, 9, 27)} {'id': 13, 'degraycomany_id': 5, 'nomberhisas': 3, 'date': datetime.date(2020, 9, 28)} {'id': 7, 'degraycomany_id': 6, 'nomberhisas': 2, 'date': datetime.date(2020, 9, 27)} {'id': 11, 'degraycomany_id': 6, 'nomberhisas': 1, 'date': datetime.date(2020, 9, 27)} {'id': 6, 'degraycomany_id': 7, 'nomberhisas': 1, 'date': datetime.date(2020, 9, 27)} {'id': 12, 'degraycomany_id': 7, 'nomberhisas': 1, 'date': datetime.date(2020, 9, 28)} {'id': 14, 'degraycomany_id': 7, 'nomberhisas': 3, 'date': datetime.date(2020, 9, 28)} {'id': 15, 'degraycomany_id': 8, 'nomberhisas': 1, 'date': datetime.date(2020, 9, 28)} so now i want to get sum of every degraycomany_id so i use this queryset: test1 = MediaSec.objects.filter(date__range=[primary1, primary2], degraycomany__in=degraycompsec).aggregate(Sum("nomberhisas")) the rusult come : {'nomberhisas__sum': 18} i want reslt like this : {'id': 13, 'degraycomany_id': 5, 'nomberhisas': 9, 'date': datetime.date(2020, 9, 28)} {'id': 11, 'degraycomany_id': 6, 'nomberhisas': 3, 'date': datetime.date(2020, 9, … -
How to apply multiple filters on a Django template when i use django-ckeditor without error?
i am using django-ckeditor as a app_contect field in models so How to apply multiple filters on a Django template , when i add multiple filters in html page it show error in my design my code in html page : <p class="card-text" id="font_control_for_all_pages">{{ android.app_contect|truncatechars:153|safe }}</p> this photo without ( |safe ) and this with (|safe) -
Can you pull from an API and create your own Tables with Django Rest Framework?
I am very new to Django and haven't had a lot of practice with it yet. I was reading and watching videos on their framework Django Rest Framework. I was wondering with the Model Serializer how could I use an existing API and copy that information into my own database. It is just a normal Json format and has a lot of information in it. The reason I am doing this is the project we want to get away from using a 3rd party database and create our own. If this framework isn't the way to go what other ways can I do this? Thanks for any help in advance. -
Newly registered users are not being reflected in the database in 'Django Administration' page after I login as an admin
I am trying to build a user login/signup page using Django. Everything works fine except when I try to register new users by clicking on the register button, the newly registered users are not being reflected in the database in 'Django Administration' page after I login as an admin. Please help. Here's my code: urls.py-login from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')) ] urls.py-accounts from django.urls import path from . import views urlpatterns = [ path('', views.indexView, name = "home"), path('dashboard/', views.dashboardView, name = "dashboard"), # path('login/',), path('register/',views.registerView, name = "register_url"), # path('logout,'), ] views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm # Create your views here. def indexView(request): return render(request, 'index.html') def dashboardView(request): return render(request, 'dashboard.html') def registerView(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('login_url') else: form = UserCreationForm() return render(request, 'registration/register.html', {'form':form}) index.html <!DOCTYPE html> <html> <head> <title>Petrol Pump Management System</title> </head> <body> {% block content %} <h1>User Authentication</h1> {% endblock %} </body> </html> register.html {% extends 'index.html'%} {% block content %} <h1>Create new account</h1> <form method = "POST"> {% csrf_token %} {{form.as_p}} <button type="submit">Register</button> </form> {% endblock %} -
Transferring Django project deployed on Heroku to new computer
I have recently purchased a new computer and from now on I will be working on that computer. However, I have a relatively big project on my older computer that id like to move all files and folders from the older computer to a new computer. I have different Github branches as well as the Heroku repositories set for this project. Now, what is m best option as I want to avoid cloning my own git repository? If I simply copy and paste my files and folder can that cause issues? -
upload image in django
#`this is my settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #this is urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('laxmi.urls')), ] + static(settings.MEDIA_URL, documents_root=settings.MEDIA_ROOT) #This is model class Services(models.Model): title = models.CharField(max_length=250) desc = models.TextField() img = models.ImageField(upload_to='img') def __str__(self): return self.title #This is views def index(request): why_choose_uss = why_choose_us.objects.all() servicess = Services.objects.all() return render(request, 'laxmi/index.html', {'servicess': servicess, 'why_choose_uss': why_choose_uss}) #This is template {% for services in servicess %} <div class="col mb-4"> <div class="card"> <img src="{{services.img.url}}"class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{services.title}}</h5> <p class="card-text">{{services.desc}}</p> <a href="#" class="btn btn-primary">Lern More</a> </div> </div> </div> {% endfor %} #this is image upload from admin pannel but its not shwoing in template enter image description here -
How do I integrate my ReactJs with django website to RazorPay?
I want to create a payment gateway for a competition but I don't know how to add a rozarpay payment gateway on my django+reactjs app? -
How should I return usernames instead of id inside Django Rest Framework API?
This is my model. class FollowerModelSerializer(ModelSerializer): user = CharField(source='slug') class Meta: model = Profile fields = ['user', 'followers'] This is the serializer. class FollowerModelViewSet(ModelViewSet): queryset = Profile.objects.all() serializer_class = FollowerModelSerializer allowed_methods = ('GET', 'HEAD', 'OPTIONS') def list(self, request, *args, **kwargs): self.queryset = self.queryset.filter(id=request.user.id) return super(FollowerModelViewSet, self).list(request, *args, **kwargs) And this is the API. This is the response : HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "user": "pop", "followers": [ 1, 4 ] } ] Problem: It's returning the IDs of the followers. How should I make it return the usernames of the followers instead? -
ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'accounts.user', but app 'accounts' isn't installed version3.1.1
django version 3.1.1: hey there, I just created a new project, then I create a new app called "pages" then added to the installed apps. but when I run either makemigrations or migrate I got the error: I didn't do anything except adding the app to the installed app. maybe the error is b/c the Django version or maybe not. I didn't even create an app called accounts, so I really confuse about the error. no code, just a new project setup. The full error log is below Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Python37\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Python37\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python37\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python37\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Python37\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Python37\lib\site-packages\django\core\management\commands\makemigrations.py", line 168, in handle migration_name=self.migration_name, File "C:\Python37\lib\site-packages\django\db\migrations\autodetector.py", line 43, in changes changes = self._detect_changes(convert_apps, graph) File "C:\Python37\lib\site-packages\django\db\migrations\autodetector.py", line 128, in _detect_changes self.old_apps = self.from_state.concrete_apps File "C:\Python37\lib\site-packages\django\db\migrations\state.py", line 212, in concrete_apps self.apps = StateApps(self.real_apps, self.models, ignore_swappable=True) File "C:\Python37\lib\site-packages\django\db\migrations\state.py", line 278, in __init__ raise ValueError("\n".join(error.msg for error in errors)) ValueError: The … -
create a signal in django
Good afternoon, I must pass on to my method of creating the signal if I want to create a notification. from django.contrib.auth.models import User from django.db.models import signals from django.dispatch import receiver from .models import Notification, Follower def new_follower(sender, instance, created, **kwargs): if created: Notification.objects.create(notification__user = instance) signals.post_save.connect(new_follower, sender=Follower, dispatch_uid=" user_new_follower") -
Pass hits from django-hitcount to model serializer
I am using django-hitcount to track hits on my model. I would like to pass the data from the hits to an API through a serializer. This is how i am doing it currently on my serializer using serializer method field but i am getting nulls hotel_hits = serializers.SerializerMethodField() "policies", 'hotel_type_id', 'hotel_hits', def get_hotel_hits(self, obj): try: return obj.hit_count.hits except: pass What could i be doing wrong? -
Trying to Runserver (w/GDAL) and GDAL ERROR Preventing Site From RUNNING
I hope you all are having a good day. I have been doing this tutorial on RealPython https://realpython.com/courses/make-location-based-web-app-django-and-geodjango/ The TUtorial includes running a virtual environment and installing QGIS, as this app is 'location-based' I am at the 'Create the "nearby shops" App' section of the tutorial, and it asks for me to 'runserver' However when I runserver, I am getting in response<: PS C:\Users\Jamal Ford\desktop\geoshops> python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Jamal Ford\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\Jamal Ford\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\Jamal Ford\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Jamal Ford\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\Jamal Ford\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\Jamal Ford\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\Jamal Ford\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Jamal Ford\AppData\Local\Programs\Python\Python36\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Jamal Ford\AppData\Local\Programs\Python\Python36\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\Jamal Ford\AppData\Local\Programs\Python\Python36\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Jamal Ford\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in … -
send a email after user data is saved Django
i want to send email to user after data is saved how do i pass the data like "first_name" to the email function how do i pass the data without data i have able call the email function its working. from Email import views as em @api_view(['GET', 'POST']) @permission_classes((IsAuthenticated, )) def CustomerAPI(request): if request.method == 'GET': snippets = Customer.objects.all() serializer = CustomerSerializer(snippets, many=True) return Response({"Customer_List": serializer.data}) elif request.method == 'POST': serializer = CustomerSerializer(data=request.data) if serializer.is_valid(): serializer.save() #em.email_send1(request, first_name='SOURABH', middle_name='k', last_name='SAIKIA') #response = em.email_send1(request=request._request).data response = em.email_send1(request=request._request.POST["first_name"]="sourabh").data return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
django.db.utils.IntegrityError: UNIQUE constraint failed: main_produit.exposition_sante_id (Django)
Bonjour, j'essaie de creer un script qui charge des données d'un fichier csv vers mes modèles de Données sur Django. voici une partie de mes classes de données class Exposition_Sante(models.Model): Note_Sante = models.DecimalField(max_digits=4, decimal_places=2, null=True) Avis_Expert = models.TextField(null=True) class Exposition_Environement(models.Model): Note_Env = models.DecimalField(max_digits=4, decimal_places=2, null=True) Avis_Expert = models.TextField(null=True) class Produit(models.Model): Sans_NGS = models.CharField(max_length=50) Taux = models.CharField(max_length=50, null=True) Famille = models.CharField(max_length=50) Nom_Commercial_FDS = models.CharField(max_length=50) MPE = models.DecimalField(max_digits=5, decimal_places=2) Achete_sur_les_3_dernieres_années = models.CharField(max_length=50, null=True) NIP = models.CharField(max_length=50) NGS = models.CharField(max_length=5, null=True) CAS_des_ingredients_du_NGS = models.CharField(max_length=50, null=True) Nom_du_CAS = models.CharField(max_length=50, null=True) Substance_Impurete_ou_Produit_Degredation = models.CharField(max_length=50, null=True) danger_sante = models.OneToOneField(Danger_Sante, on_delete=models.CASCADE, null=True) danger_environement = models.OneToOneField(Danger_Environement, on_delete=models.CASCADE, null=True) exposition_sante = models.OneToOneField(Exposition_Sante, on_delete=models.CASCADE, null=True) exposition_environement = models.OneToOneField(Exposition_Environement, on_delete=models.CASCADE, null=True) et voici une partie de mon script: exposition_sante, _ = models.Exposition_Sante.objects.get_or_create( Note_Sante = row["santé 1"], Avis_Expert = row["Avis d'expert2"] ) exposition_environement, _ = models.Exposition_Environement.objects.get_or_create( Note_Env = row["santé 1"], Avis_Expert = row["Avis d'expert2"] ) produit, _ = models.Produit.objects.get_or_create( Sans_NGS = row["sans NGS"], Taux = row["taux"], Famille = row["Famille"], Nom_Commercial_FDS = row["nom commercial FDS"], MPE = row["MPE"], Achete_sur_les_3_dernieres_années = row["acheté sur les 3 dernières années"], NIP = row["NIP (avec 0)"], NGS = row["NGS"], CAS_des_ingredients_du_NGS = row["CAS des ingrédient du NGS"], Nom_du_CAS = row["nom du CAS"], Substance_Impurete_ou_Produit_Degredation = row["substance, impureté ou produit dégradation … -
connect django to mysql on shared hosting
I want to use mysql server in my django project and this was my database setting: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', ... } } but this engine needs mysqlclient and i can't install it on shared host. because i need superuser access to fix some issues. So i decided to use: DATABASES = { 'default': { 'ENGINE': 'mysql.connector.django', ... } } however, this engine has some bugs!! when i wanna get a row from database, it doesn't return boolean columns(return None instead). now i want to know if there is another engine for this or any other idea to solve it?? django==2.0 python==3.6 -
Form is not saving in database when submitted
I am working on a project on Django, where user can input values on form and submit using POST request. When form is submitted, datas are not saved in database. How do I implement save data when form is submitted. Models: class DataInfo(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) beneficiary_name = models.CharField(max_length=250, blank=True) beneficiary_bank_name = models.CharField(max_length=250, blank=True) beneficiary_account_no = models.CharField(max_length=250, blank=True) beneficiary_iban = models.CharField(max_length=250, blank=True) beneficiary_routing_no = models.CharField(max_length=250, blank=True) amount = models.IntegerField(blank=True) date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'DataInfo' verbose_name_plural = 'DataInfo' ordering = ['-date'] '''Method to filter database results''' def __str__(self): return self.user.username Views: @login_required def TransferView(request): form = DataForm(request.POST) if request.method == "POST": if form.is_valid(): pp = form.save(commit=False) pp.user = request.user pp.save() return redirect('site:transfer_cot') else: form = DataForm() context = { 'form':form } return render(request, 'transfer.html', context) Forms: class DataForm(forms.ModelForm): class Meta: model = DataInfo fields = ('beneficiary_name', 'beneficiary_bank_name', 'beneficiary_account_no', 'beneficiary_iban', 'beneficiary_routing_no', 'amount') Template: <form method="POST" action="{% url 'site:transfer_cot' %}"> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-secondary">Submit</button> </form> -
How to filter a form based on a DateTimeField using timedelta
I have the following model for Sessions: courses/models.py: class Session(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) course_date_start = models.DateTimeField() course_date_end = models.DateTimeField() is_in_session = True def session_id(self): new_session_date = self.course_date_start.strftime('%Y') return f'{new_session_date}{self.course.number}{self.pk}' def __str__(self): return f'{self.course.number} - {self.course.title} - {self.session_id()}' And in my users/forms.py: class EnrollStudentInCourseForm(forms.Form): global roster_limit student = forms.ModelChoiceField(queryset=Student.objects.all()) courses=SessionRemainingSlotsForm(queryset=Session.objects.annotate(num_students=Count('student')).filter(num_students__lt=roster_limit)) I'd like to filter out the fields so that it only shows sessions where course_date_start plus a week, to cover a student joining the class a little late. -
can't log_in in the django admin panel with custom user model
I have created a custom user model in django. Everything is working fine, just can't login at the admin panel. here is my code. models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.utils import timezone class User_Manager(BaseUserManager): def create_user(self,username, email, password=None): if not email or not username: raise ValueError("Users must provide username & email address") user = self.model( username = username, email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,username, email, password=None): user = self.create_user( username, email, None ) user.isSuperuser = True user.isStaff = True user.save(using=self._db) return user class User_Profile(AbstractBaseUser, PermissionsMixin): email = models.EmailField( max_length=50, unique=True, ) first_name = models.CharField( max_length=20, ) last_name = models.CharField( max_length=10, ) username = models.CharField( max_length=20, unique=True ) isStaff = models.BooleanField( default=False, null=True, ) isActive = models.BooleanField( default=True ) isSuperuser = models.BooleanField( default=False ) date_joined = models.DateTimeField( default=timezone.now ) objects = User_Manager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = [ "email", ] def __str__(self): return self.username def get_full_name(self): return " ".join([self.first_name, self.last_name]) def has_perm(self, perm, obj = None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.isStaff @property def is_active(self): return self.isActive @property def is_superuser(self): return self.isSuperuser admin.py: from django.contrib import admin from django import forms from django.contrib.auth.models import Group from …