Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django adding event to Month of a Calender issue
I am working on a Calender project, for the already got the code online. if booking an event we give a start date and end date. if submit the form the event will get saved in the calendar only on the start time, the event is visible in the calendar template, My requirement is that Now I want to modify the calendar so that all the dates matching the start date and end date should show the event. Example: i have given the start date as 20th Dec 2020 and the end date as 24th Dec.. so in the calendar, the same event should show on 20,21,22,23,24... days I believe here I am inserting the data in the Html template, i need to pass end time here that i don't know events_per_day = events.filter(start_time__day=day) d = '' for event in events_per_day: d += f'<li> {event.get_html_url} </li>' Tried alot but no success Below is the code : Models from django.db import models from django.urls import reverse class Event(models.Model): title = models.CharField(max_length=200) description = models.TextField() start_time = models.DateTimeField() end_time = models.DateTimeField() @property def get_html_url(self): url = reverse('cal:event_edit', args=(self.id,)) return f'<a href="{url}"> {self.title} </a>'} utils,py from datetime import datetime, timedelta from calendar import … -
Date form fields in Django with data-dependent-fields attribute error messages are not properly displayed
My requirement is to display error message when date difference between from and to date is more than 6 months. When I change the to_date field keeping from_date constant, errors are displaying when the range is greater than 6 months. But, when I change the from_date keeping to_date constant, error message is getting cleared for valid case and when I change the from_date to have difference more than 6 months error message is not getting displayed. I tried debugging the backend code too and error messages is getting added properly. It is only problem with displaying in frontend. Following is forms code from_date = forms.DateField( label=_("From Date"), required=False, widget=forms.DateInput( attrs={ 'class': 'date-field input-medium', 'data-dependent-fields': '#id_to_date', }, format="%m/%d/%Y" ) ) to_date = forms.DateField( label=_("To Date"), required=False, widget=forms.DateInput( attrs={ 'class': 'date-field input-medium', 'data-enable': 'true', 'data-dependent-fields': '#id_from_date' }, format="%m/%d/%Y" ) ) Following is backend code to add error messages if cleaned_data.get('from_date') and cleaned_data.get('to_date'): limit_date = cleaned_data.get('from_date') + relativedelta(months=+_(constants.DATE_RANGE_6M)) if limit_date < cleaned_data.get('to_date'): self._errors["to_date"] = self.error_class([_(constants.INVALID_DATE_RANGE_6M_ERROR)]) Non-Working case Working case Django Version is 1.11.18 -
can't make changes to database or create new one
everything worked fine till yesterday, i noticed that can't make changes or create new objects! that's not a .save() problem, cause i tried even through the Django admin and again got stuck for a while and then the 502 error page showed up! the project on my laptop works fine! the same project with the same version of postgresql (but in Pycharm) and i use cdn and ufw too. actually im not familiar with ufw and perhaps you could help me! thanks -
Django rest knox - Forbidden (CSRF cookie not set.)
I am using Django, rest, knox and while some things work (viewsets work well) I cannot get POST to work (without a viewset) without getting this error Forbidden (CSRF cookie not set.). Using GET I am able to retrieve fine, but POST/PUT produces this error. A few more details. When I use a viewset I can successfully POST/PUT and GET so all authentication pieces work well. However, it's when I am not using a viewset and using POST/PUT that I receive this error. -
Django 'ModelBase' object is not iterable TypeError
Getting the below from a unit test in Django. Can't seem to figure out the reason this is happening. My migrations look identical to the other migrations I have made. Also, I was able to run this on my local machine in the admin section, so my other question is is this big deal if it is happening during the test, if it can be pushed live. Trying to follow best practices here, so appreciate others opinions on that. models.py class LeadComplete(models.Model): """Complete lead info""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, ) title=models.CharField(max_length=255) time_minutes = models.IntegerField() score = models.DecimalField(max_digits=5, decimal_places=2) link = models.CharField(max_length=255, blank=True) client = models.ManyToManyField('Client') def __str__(self): return self.title serializers.py class LeadCompleteSerializer(serializers.ModelSerializer): """Serialize a leadComplete""" client = serializers.PrimaryKeyRelatedField( many=True, queryset=Client.objects.all() ) class Meta: model = LeadComplete fields = [ 'id', 'title', 'time_minutes', 'score', 'link', 'client', ] read_only_fields = ('id',) views.py class LeadCompleteViewSet(viewsets.ModelViewSet): """Manage LeadComplete in the database""" serializer_class = serializers.LeadCompleteSerializer queryset = LeadComplete.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get_queryset(self): """Retrieve the leadcomplete for the authed user""" return self.queryset.filter(user=self.request.user) test_lead_complete_api.py from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from rest_framework import status from rest_framework.test import APIClient from core.models import LeadComplete from leads.serializers import LeadCompleteSerializer … -
Pass extra argument to auth url
I am trying to implement google allauth authentication. Before clicking this button to make google register a user: <a href="{% provider_login_url 'google' %}" type="submit">Registrarse with Google</a> I have this input field <input id="nombrelink" placeholder="specialname"></input> What that button does is automatically register and log the user in. I would like to pass this input parameter to the google button so that whenever someone creates an account, that inputs gets prepended to their database How can I pass an extra argument to that url? -
How to handle asynchronous tasks with queues defined on a user (or other attribute) basis with django and celery?
thank you for viewing my question. I am new to celery and I am trying to wrap my head around the world of threading and multiprocessing, but I cannot seem to find any info that fits my specific use case. Consider this, I have a django-rest-framework API for my personal trading software that receives post requests to perform a buy or sell order to my broker's REST API. Now, I want to make sure that my API can handle numerous concurrent requests and queue those requests and process those in the order that they were received. One task cannot happen before the other if finished because the next task will rely on database information that the former task has written. I have implemented a celery instance to process a FIFO queue. Here lies my question, lets say I have multiple strategies, and I don't want the queues from multiple strategies to be mixed in the same queue. I want an asynchronous queue per strategy. Do I now require multiple worker instances, or can I separate queues into one worker instance? What exactly would that syntax look like or what celery methods should I be looking in to? The post request … -
Django get_context( ) method. Does this exist?
I have looked through the Django docs and search the code but cannot find any details for a function called get_context(). However, I have seen it used in a few spots in the code. Is this a method that is available to use in Django or some internal method? I am not referring to get_context_data. Thanks -
Is it possible to query each and every fields in form_fields of abstractform in wagtail
Created some fields in abstract form through wagtail admin, now I want to query that each and every field to another template (profile page). any ideas? class FormField(AbstractFormField): page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='form_fields') class FormPage(AbstractEmailForm): intro = RichTextField(blank=True) thank_you_text = RichTextField(blank=True) content_panels = AbstractEmailForm.content_panels + [ FieldPanel('intro', classname="full"), InlinePanel('form_fields', label="Form fields"), FieldPanel('thank_you_text', classname="full"), MultiFieldPanel([ FieldRowPanel([ FieldPanel('from_address', classname="col6"), FieldPanel('to_address', classname="col6"), ]), FieldPanel('subject'), ], "Email"), ] -
'ManagementForm data is missing or has been tampered with' error at Django 3.1.3 occured to me
there. I had created CRUD form app which can upload multiple images optionally before. And then, when I tried to enter a post form page, Django returned to me the below error, ValidationError at /ads/ad/create ['ManagementForm data is missing or has been tampered with'] Request Method: GET Django Version: 3.1.3 Exception Type: ValidationError Exception Value: 'ManagementForm data is missing or has been tampered with' Exception Location: /~~~/lib/python3.8/site-packages/django/forms/formsets.py, line 92, in management_form So, what's happening on my app when a post created?? I'm showing a few parts of the python codes that seem to be related with this error following, views.py 8 # Create the form class. 9 class CreateForm(forms.ModelForm): 10 class Meta: 11 model = Ad 12 fields = ['title', 'category', 'text'] 13 14 class FilesForm(forms.ModelForm): 15 max_upload_limit = 2 * 1024 * 1024 16 max_upload_limit_text = naturalsize(max_upload_limit) ~ ~ 21 picture = forms.FileField(required=False, label='File to Upload <= '+max_upload_limit_text, 22 widget=forms.ClearableFileInput(attrs={'multiple': True})) 23 upload_field_name = 'picture' 24 25 26 class Meta: 27 model = Adfiles 28 fields = ['picture'] forms.py 93 class AdCreateView(LoginRequiredMixin, View): 94 template_name = 'ads/ad_form.html' 95 success_url = reverse_lazy('ads:all') 96 97 def get(self, request, pk=None): 98 FilesFormSet = formset_factory(FilesForm) 99 data = { 100 'form-TOTAL_FORMS': '1', 101 … -
Using login url to register an user
Im trying to implement google allauth authentication. I tried and realized that if I click on this button: <a href="{% provider_login_url 'google' %}" type="submit">Registrarse con Google</a> And choose a google account that hasn't been registered yet, allauth automatically registers and logs the user in. I have two questions: Is this a safe and proper way to register an user? How can I pass an extra argument to that url? -
how do I access a class if it's active in javascript
I'm working on a toast message setup where I can't access the classes if they're active and add space between the elements if multiple of em are in bound(maybe a margin of 15px) and display them on the bottom-corner of the screen(fixed) and make em disappear after 3 secs one by one. Thnx! Here's my code. {% if messages %} {% for message in messages %} {% if message.tags == 'success' %} <div class="color-green"> <div class="color-white"> <div class="icon-success"> <i class="fas fa-check icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% elif message.tags == 'info' %} <div class="color-blue"> <div class="color-white"> <div class="icon-info"> <i class="fas fa-info icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% elif message.tags == 'warning' %} <div class="color-orange"> <div class="color-white"> <div class="icon-warning"> <i class="fas fa-exclamation-circle icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% elif message.tags == 'error' %} <div class="color-red"> <div class="color-white"> <div class="icon-cross"> <i class="fas fa-times icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% endif %} {% endfor %} {% endif %} .color-green{ bottom: 0; position: absolute; background-color: #40ff00; box-shadow: 4px 4px 16px 0 rgba(0, 0, 0, 0.05); margin-bottom: 10px; margin-left: 15px; z-index: 4; border-radius: 4px; padding-left: 0.4em; } .color-blue{ bottom: 0; position: absolute; background-color: … -
Django ORM inside of AWS Lambda function
I am looking to move away from celery and start using AWS Lambda to generate my files and store into S3. After I save on S3, I would like to be able to save a reference to my Django Database (being hosted on RDS). Am I able to do this on Lambda? Or would an option be that I generate the file, save to s3 and send the reference to my currently hosted Django application? My app is currently being hosted on an EC2 instance. I know Zappa exists but am wondering if redeploying my entire application would be overkill. -
I am have trouble configuring my Django app for Heroku
I have a Django app that runs fine on my local machine so I want to upload it on Heroku I used the following video to guide me: https://www.youtube.com/watch?v=GMbVzl_aLxM but I am getting the followng error message when I run the following commands gunicorn core.wsgi [2020-12-18 02:29:16 +0200] [104166] [INFO] Starting gunicorn 20.0.4 [2020-12-18 02:29:16 +0200] [104166] [INFO] Listening at: http://127.0.0.1:8000 (104166) [2020-12-18 02:29:16 +0200] [104166] [INFO] Using worker: sync [2020-12-18 02:29:16 +0200] [104168] [INFO] Booting worker with pid: 104168 [2020-12-18 00:29:16 +0000] [104168] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/snr/.local/share/virtualenvs/Music_Repo-DS3TLAOE/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/home/snr/.local/share/virtualenvs/Music_Repo-DS3TLAOE/lib/python3.8/site-packages/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/home/snr/.local/share/virtualenvs/Music_Repo-DS3TLAOE/lib/python3.8/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi self.wsgi = self.app.wsgi() File "/home/snr/.local/share/virtualenvs/Music_Repo-DS3TLAOE/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/snr/.local/share/virtualenvs/Music_Repo-DS3TLAOE/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/home/snr/.local/share/virtualenvs/Music_Repo-DS3TLAOE/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp return util.import_app(self.app_uri) File "/home/snr/.local/share/virtualenvs/Music_Repo-DS3TLAOE/lib/python3.8/site-packages/gunicorn/util.py", line 358, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line … -
Nested variables in Django Templates
I'm not sure if it is variable or tag. I have two apps (different styles, different navbars) but want to print the same document from db. I created base.html, templates with extends and everything works perfectly. But. The body of template is filled from database, which is a part of html code. And in this code there's <p>The contact email is: blabla@firstapp.example.com</p> Of course this is wrong for secondapp. I tried to change body with <p>The contact email is: {{ app_email }}</p>, and set it with context But it doesn't work - it prints The contact email is: {{ app_email }} template/document.html: {% extends base %} {% load crispy_forms_tags %} {% load static %} {% block head %} <title>{{ title }}</title> {% endblock %} {% block content %} <div class="container"> <div class="row justify-content-center"> <div class="col-9"> <h1 class="mt-2">{{ document.header }} !!!</h1> <hr class="mt-0 mb-4"> {% autoescape off %} {{ document.body }} {% endautoescape %} </div> </div> </div> {% endblock %} firstapp.views.py: def myview(request): context = { 'app_title' : 'First', 'title' : 'First - document', 'app_name' : 'first', 'app_email' : 'contact@first.example.com', 'document' : get_document('document1'), 'base' : 'first/base.html' secondapp.views.py: def myview(request): context = { 'app_title' : 'Second', 'title' : 'Second - document', 'app_name' … -
How to filter vlaues that contain underscore in Django?
I want to do this code = Book.objects.filter(category__contains=("cat_en_00001")) I want to get the objects that have the value "cat_en_00001" for the category field. But I get nothing. I know that _ is a special character but I tried \_ and other options and no success. The return is empty. -
Set primary key in Django
The title is not entirely accurate, but I do not know how to explain, so I took a screenshot of where my problem is, and I will try to explain what I am trying to achieve. I have a vehicle model, and when I create a new vehicle object, the name of vehicles just says Vehicle object (1) How can I change my model, or serializer (or something else) so that will show some unique value of the object. Here is my model: class Vehicle(models.Model): make = models.CharField(max_length=100, blank=True) model = models.CharField(max_length=300, blank=True) license_plate = models.CharField(max_length=7, blank=True) vehicle_type = models.CharField(max_length=20, blank=True) seats = models.IntegerField(default=4, validators=[ MaxValueValidator(70), MinValueValidator(4)], ) year = models.IntegerField(_('year'), default=datetime.today().year - 10, validators=[ MinValueValidator(1975), max_value_current_year]) inspected = models.BooleanField(default=True) # fuel_type # fuel_price created_at = models.DateTimeField(auto_now_add=True) -
How to Assign New users to Old Users As Upline Payment in django based on Category
Am building a django project and i want Newly Authenticated User to be Attached to Old Authenticated User as Upline for payment purposes(i sure know how to handle the payment case). This Attachment or Assign of this New User to Old User should be based on the Request of the Old User and the willingness of the New Users. There is a payment category for Users of the App in a range of $50, $100, $150, $200. Lets take for example- the old User Request For a payment of $50 and the new user select a category of payment of $50. Then the new user which is assigned to the old user will be automatically Assigned to pay the new User the amount Category Requested by the old User and agreed upon by the New Users. After the Request from the old User and Request from the New User then i will want my app to automatically assign the old user to the new user. Note. I will determine the other conditions that will enable the old user elligible to make such requests. Lets take a look at my Code. Payment Category Class PayCategory(models.Model): Amount = models.Charfield(max_length=6) My Manager which … -
Pass parameter through django-allauth url
Before authenticating an user with Google in my page, I have an input that users can fill in with a special name, let's call this name variable nombrelink. When the user fills in the input and clicks submit, I send a fetch post request to the server to check wether that name is already taken or not. The problem is: when the person completes that input and THEN tries to sign up with google, I can't find a way to insert nombrelink into the database of the recently google created user. This is what happens on the server, to check wether the input name (nombrelink) is already taken or not. def landing(request): if request.method == "POST": content = json.loads(request.body) creator = Creador.objects.filter(url_name=content['nombrelink']).first() if not creator: content.update({"nadie": "nadie"}) return JsonResponse(content) else: return JsonResponse(content) return render(request, 'app1/landing.html') So in summary what the code should be doing is: The user fills in the input with a name that gets stored in nombrelink If nombrelink is not taken, then the user can register via google allauth nombrelink gets added to my google created user model I'm failing to implement point 3 -
Django Bootstrap - How to parse a variable from a local JSON file and display it in a .html template?
I'm new to JS and would like to display in my html file a variable to be parsed from a local JSON file ? I'm running that in Django with bootstrap. myfile.json contains: [{"myvar":"1500000"}] my html template contains: ... <div class="col-9"> <h3 class="f-w-300 d-flex align-items-center m-b-0"><i class="feather icon-arrow-up text-c-green f-30 m-r-10"></i><span id="output_1"></span></h3> </div> ... ... <!-- Specific Page JS goes HERE --> {% block javascripts %} {% load static %} <script src="{% static 'dashboard_data.json' %}"> var my_kpi = fetch("/static/dashboard_data.json") .then(response => response.json()) .then(data => { console.log(data.myvar) document.querySelector("output_1").innerText = data.myvar }); document.getElementById('output_1').innerHTML = my_kpi </script> {% endblock javascripts %} I'm not sure what I'm doing wrong. From the development tool when debugging in the browser, I can see that the JSON file appears in the sources, but the myvar value does not show in the console nor in the html page. It looks like nothing is being parsed at all inside my_kpi. Many thanks for your help. -
How do I update a CustomUser value via UpdateView using a hidden logic
I've spent several hours on this and I'm not able to see any signs as to why the change on the flag is not getting through. Please note the change form already works for all exposed fields, i.e. the user can go in and change the name or country already and it will get saved after clicking on update profile. What I'm now trying to do is to also change the confirmed_email flag to True (but without telling or letting the user see it) whenever the client makes an update to the form. To do this I check if the user was logged in using Linkedin (or any Social account for that matter) via something along the lines of ""if user.social_auth.exists()"". That said, it's not that i can't fulfill this function, it's that even when i use a silly condition that i know it's true the field "email_confirmed" will still NOT change to True in the back-end. Thanks so much in advance. I appreciate your time. PS. I'm a noob with Django but loving it. Models.py class CustomUser(AbstractUser): id = models.BigAutoField(primary_key=True) email = models.EmailField(unique=True) email_confirmed = models.BooleanField(default=False) country = models.CharField(max_length=30,choices=COUNTRY, null=True, blank=False) first_name = models.CharField(max_length=50, null=False, blank=False, default="") last_name = … -
UNIQUE constraint failed: main_user.username
Help with this error and I'm trying that my phone be my username but i dont know exactly why but when i create a new object for my model user, the register isn't being save in the same row models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): address= models.CharField( max_length=50 ) gender = models.CharField( max_length=30 ) celular = models.CharField( unique=True,max_length=16 ) genero = models.CharField( choices=(('M', 'Mujer'), ('H', 'Hombre')), max_length=16, blank=True ) fecha_nacimiento = models.DateField( null=True ) forms.py class UserForm(ModelForm): class Meta(): model = User fields=['celular'] views.py def user_register(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): x= form.cleaned_data['celular'] # User.objects.create(username=x) print(x) form.save() return redirect('index',) else: form = UserForm() return render(request, 'useregister.html', {'form': form}) An example for celular= username on my database Sqlite3 1 name last name celular username 123 2 name last name celular username 123 -
Django form dropdown field shows data owned by other users
I have trouble querying only user owned items from CreateView and Form: # views.py class ExpenseCreateView(LoginRequiredMixin, CreateView): model = Expense form_class = ExpenseCreateForm template_name = "expenses/expense_form.html" success_url = reverse_lazy("expense-list") def form_valid(self, form): form.instance.owner = self.request.user return super(ExpenseCreateView, self).form_valid(form) # forms.py class ExpenseCreateForm(forms.ModelForm): class Meta: model = Expense exclude = ("owner", ) widgets = {"date": DateInput(), "time": TimeInput()} # models.py class Expense(models.Model): date = models.DateField(db_index=True) time = models.TimeField(null=True, blank=True) amount = models.DecimalField(max_digits=10, decimal_places=2, help_text="Amount of € spent.") location = models.ForeignKey("Location", on_delete=models.SET_NULL, null=True) document = models.FileField( upload_to=UploadToPathAndRename("documents/"), blank=True, null=True ) image = models.ImageField( upload_to=UploadToPathAndRename("images/"), blank=True, null=True ) payment = models.ForeignKey("Payment", on_delete=models.SET_NULL, db_index=True, null=True) comment = models.TextField(null=True, blank=True, help_text="Additional notes...") owner = models.ForeignKey(User, on_delete=models.CASCADE) class Payment(models.Model): title = models.CharField(max_length=100) comment = models.TextField(blank=True, null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) The form works, but every user can see Location and Payment of other users. Which is the right spot and way to add validation/check to only return Location which is owned by the user issuing request? -
Dokku: setuidgid: fatal: unable to run gunicorn: file does not exist
I am trying to run my application in Dokku I get this error: 5b188e740fcae5a5080e2ac498e6b93a593ae107e656c53e5df1d8c8e13948c8 remote: ! App container failed to start!! =====> lala web container output: setuidgid: fatal: unable to run gunicorn: file does not exist setuidgid: fatal: unable to run gunicorn: file does not exist setuidgid: fatal: unable to run gunicorn: file does not exist setuidgid: fatal: unable to run gunicorn: file does not exist setuidgid: fatal: unable to run gunicorn: file does not exist setuidgid: fatal: unable to run gunicorn: file does not exist setuidgid: fatal: unable to run gunicorn: file does not exist =====> end lala web container output remote: 2020/12/17 23:22:13 exit status 1 remote: 2020/12/17 23:22:13 exit status 1 remote: 2020/12/17 23:22:13 exit status 1 To coffee-and-sugar.club:lala ! [remote rejected] main -> master (pre-receive hook declined) -
check_password not working for django custom user model
I have created a custom backend which accepts email/password combo only. The backend with the authentication function is as so: class EmailOnlyBackend(ModelBackend): def authenticate(self, request, email, password): try: user = get_user_model().objects.get(email=email, is_email=True) print(user) if user.check_password(password): return user except get_user_model().DoesNotExist: return None def get_user(self, user_id): try: return get_user_model().objects.get(pk=user_id) except get_user_model().DoesNotExist: return None The account manager model and the user model are: class MyAccountManager(BaseUserManager): def create_user(self, email, password=None, username="", is_email=None): if not email: raise ValueError("Missing email address") try: get_user_model().objects.get(email=email, is_email=True) raise ValueError("User with this email address already exists") except get_user_model().DoesNotExist: pass user = self.model(email=self.normalize_email(email)) user.set_password(password) if is_email: user.is_email = True user.save(using=self._db) return user class EmailOnlyUser(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=60, unique=False) username = models.CharField(max_length=30, unique=False) date_joined = models.DateTimeField(verbose_name='date_joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last_login', auto_now=True) is_email = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = MyAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email I can't give much info as I don't know what's causing it, the emails and passwords are passed correctly as strings down to the set_password and check_password functions and the user is then added to the db with the hashed password, but when logging in the check_password in authenticate never returns true.