Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : automatically fill in one of the fields of the form
I have a query for security reasons, I would like to automatically fill in one of the fields of the form. a- depending on the selected channel automatically fill in the seller field. b- if the consumer field (form.instance.consumer = self.request.user) does not match the channel user, return an error. if you have any idea or similar stack page I'm interested in :) forms.py #Channel RATING @method_decorator(login_required(login_url='/cooker/login/'),name="dispatch") class ChannelReview(FormView, ListView): model = Rating template_name = 'channel_review.html' form_class = ChannelRatingForm context_object_name = 'userrating' def get_context_data(self, **kwargs): context = super(ChannelReview, self).get_context_data(**kwargs) context['form'] = self.get_form() return context def form_valid(self, form): if form.is_valid(): #form.instance.channel = self.object form.instance.consumer = self.request.user form.save() return super(ChannelReview, self).form_valid(form) else: return super(ChannelReview, self).form_invalid(form) def post(self,request,*args,**kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_valid(form) models.py class Rating(models.Model): channel = models.OneToOneField(Channel,on_delete=models.CASCADE,related_name="rating_channel") consumer = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE,related_name='rating_consumer') seller = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE,related_name='rating_seller') is_rated = models.BooleanField('Already rated', default=True) comment = models.TextField(max_length=200) publishing_date = models.DateTimeField(auto_now_add=True) ratesugar = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) def __str__(self): return self.channel.name class Meta: ordering = ['-publishing_date'] class Channel(models.Model): consumer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_consumer", blank=True, null=True) name = models.CharField(max_length=10) seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_seller") image = models.ImageField(null=True,blank=True,default='user/user-128.png', upload_to='channel/') date_created = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField('Make it happen', default=False) … -
How to Connect celery to Redis without Password?
I know connect celery to Redis with Password? app = Celery('celery_tasks.tasks', broker='redis://:appleyuchi@127.0.0.1:6379/0') but how to connect celery to Redis without Password? Thanks for your help. -
template datepicker post form.is_valid send back error message not a valid date
I don t understand where is my mistake: my model: class Listing(models.Model): enddate= models.DateField('Ending Date', blank=False) forms: class NewListingForm(forms.ModelForm): def __init__(self, *args, **kwargs): self._newly_created = kwargs.get('instance') is None self.Creation_date = datetime.now() super().__init__(*args, **kwargs) class Meta: model = Listing _newly_created: bool # permit to test if instance is a new one or an existing instance fields = ('title','description','enddate','category','initialBid','photo','active') widgets = {'Creation_date': forms.HiddenInput(), 'author': forms.HiddenInput()} my template: {% load crispy_forms_tags %} {% block body %} <h2>{% if not listing_id %}Create Client {% else %} Edit {{ object.name }}{% endif %}</h2> <form id="create-edit-client" class="form-horizontal" action="" method="post" accept-charset="utf-8"> {% csrf_token %} {{ form.title|as_crispy_field }} {{ form.description|as_crispy_field }} <br> <br> <div class="row"> <div class="col-3"> {{ form.enddate|as_crispy_field }} </div> <div class="col-2"> {{ form.active|as_crispy_field }} </div> </div> <br> <br> <div class="form-actions"> <input type = submit type="submit" value="Save" name="submit"> </div> </form> <script> $(function () { $("#id_enddate").datetimepicker({ format: 'Y/m/d', changeMonth: true, changeYear: true }); }); </script> {% endblock %} views.py: def newlisting(request): form = NewListingForm() if request.method == "POST": form = NewListingForm(request.POST) if form.is_valid(): if form._newly_created: # test if the form concern a new instance form = form.save(request, commit=False) form.save(request) messages.success(request, 'listing saved') # message for inform user of success - See messages in html file return HttpResponseRedirect(reverse("index", {"title": … -
GET is working but POST is not working on Docker
The application is on Django configured with Docker. GET requests are working fine. But the POST requests are not working. I am adding the nginx.conf file below for the reference. The POST request is necessary for authentication. upstream app_server { server djangoapp:8000 fail_timeout=0; } server { listen 80; server_name samplewebsite.com; root /opt/djangoapp/src/samplewebsite/samplewebsite; index index.html; server_tokens off; location / { try_files $uri $uri/ /index.html; } location /media { alias /opt/djangoapp/src/media/; } location /static { alias /opt/djangoapp/src/static/; } location /api/ { proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_pass http://app_server/; } location /admin/ { proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_pass http://app_server/admin/; } client_max_body_size 128m; } Let me know if I need to add more information to the question. -
Creating if statment in Django Crispy Forms, conditional form layout
I am using Django Cripsy Forms. I want to write if else statement, when the value of field name is "Daisy" Age field should appears, otherwise there should not be field 'age". My code: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper.layout = Layout( HTML(form_opening.format('Cats')), 'name', 'age', HTML(form_closing), ), ``` -
Dynamic foreign key filter for add/change admin form django 2.2
I have 3 following models: class Brand(models.Model): name = models.CharField(max_length=255) class Branch(models.Model): name = models.CharField(max_length=255) class Admin(models.Model): brand = models.ForeignKeyField('Brand', on_delete=models.CASCADE) branch = models.ForeignKeyField('Branch', on_delete=models.CASCADE) I need to filter branches by brand Admin model in admin panel. In other words, when adding or changing new admin, I need to choose brand and based on brand I get branches. -
Configure DynamoDB in Django
I'm new using Django, and I'm trying to configure settings.py to define DynamoDB using a library called pynamodb. The main structure of my project is: ⌙ env ⊢ bin ⌙ lib ⌙ pynamodb ⌙ src ⊢ core ⌙ djangoserver ⌙ settings.py So, in settings.py i wrotte: DATABASES = { 'default': { 'ENGINE': '..env.lib.pynamodb', 'NAME': 'posts', } } But i get this error TypeError: the 'package' argument is required to perform a relative import for '..env.lib.pynamodb.base' I tried inserting package=pynamodb in different parts of the dictionary's arguments, but it doesn't work.. -
Object of type QuestionAnswer is not JSON serializable
I hope everyone is fine and safe! I am working on a requirement where data is taken from a voice synthesizer and convert to text and sent as a ajax request to the Django backend. In the backend it takes the values checks in the database and returns a JSON response to the front-end. I have below codes here and i tried changing the code but "i am getting Object of type QuestionAnswer is not JSON serializable error" and have no clue on moving further **views.py** def Answer(request): if request.method=='GET' and request.is_ajax(): question_asked=str(request.GET.get("message_now")) try: answer=QuestionAnswer.objects.filter(question=question_asked)[0] data={"data":answer} return JsonResponse({"success": True, "data": data}, status=200) except Exception as e: print(e) return JsonResponse({"success": False}, status=400) else: print("Not Suceess") **main.js** function chatbotvoice(message){ const speech = new SpeechSynthesisUtterance(); if(message!==null && message!==''){ $.ajax({ url: "http://127.0.0.1:8000/getanswer", type: 'GET', data: { message_now:message }, success: function (data) { speech.text=JSON.parse(data); window.speechSynthesis.speak(speech); chatareamain.appendChild(showchatbotmsg(speech.text)); }, error: function(error){ speech.text = "Oh No!! I don't Know !! Maashaa Allah, I am still learning!! Your question got recorded and answer for your question will be available with me in 24 hours"; window.speechSynthesis.speak(speech); chatareamain.appendChild(showchatbotmsg(speech.text)); }, }); } } Please help me with this code and let me know if you need any more information -
Error: UNIQUE constraint failed: auth_user.username
I keep getting this error: UNIQUE constraint failed: auth_user.username I can't work out why though. I am trying to extend the User model in Django so I can build my own profile model if anyone has any tips on how to do that or why this error keeps appearing please could you let me know. Thanks. Also, if a Stack Overflow moderator is reading this, don't tell me I haven't researched this problem enough before posting this, because I have! Here is my code. models.py from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save, pre_delete from django.dispatch import receiver class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) firstName = models.CharField(max_length=32) lastName = models.CharField(max_length=32) nickName = models.CharField(max_length=32) phoneNumber = models.IntegerField() def __str__(self): return f'{self.user.username}' @receiver(post_save, sender=User) def create_profile_for_user(sender, instance=None, created=False, **kwargs): if created: UserProfile.objects.get_or_create(user=instance) @receiver(pre_delete, sender=User) def delete_profile_for_user(sender, instance=None, **kwargs): if instance: user_profile = UserProfile.objects.get(user=instance) user_profile.delete() views.py from django.shortcuts import render from rest_framework import viewsets, status from rest_framework.decorators import action from rest_framework.response import Response from .models import UserProfile from .serializers import UserProfileSerializer from django.contrib.auth.models import User from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated, AllowAny class UserProfileViewSet(viewsets.ModelViewSet): queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer serializers.py from rest_framework … -
How to tell django to use variable as html?
So, I have created an html page and it gets content from Python.I am able to get the text from the python program in view.py but unable to set it as an html tags. I have setup the css and js in HTML file but only this problem is arising. Is there a way out? IN SHORT: How to tell Django that it is html and it has to simply join it in the code.(Not to use as text.) Details Python 3.8.2 Django 2.2.7 -
Error while installing misaka( using windows 10 OS ) in django virtual env
First Screenshot Second screenshot -
Django Serializer using multiple Models joined by and use it as api in Flutter application
I have a Model "Question" , which is inherited by class "MCQUestion". I have another model "Answer" along with model "Quiz" I am trying to create a serializer which displays all the Questions and its answers in a Quiz class Question(models.Model): """ Base class for all question types. Shared properties placed here. """ quiz = models.ManyToManyField(Quiz, verbose_name=_("Quiz"), blank=True) category = models.ForeignKey(Category, verbose_name=_("Category"), blank=True, null=True, on_delete=models.CASCADE) sub_category = models.ForeignKey(SubCategory, verbose_name=_("Sub-Category"), blank=True, null=True, on_delete=models.CASCADE) figure = models.ImageField(upload_to='uploads/%Y/%m/%d', blank=True, null=True, verbose_name=_("Figure")) content = models.CharField(max_length=1000, blank=False, help_text=_("Enter the question text that " "you want displayed"), verbose_name=_('Question')) explanation = models.TextField(max_length=2000, blank=True, help_text=_("Explanation to be shown " "after the question has " "been answered."), verbose_name=_('Explanation')) DIFFICULTY_LEVEL=[ ('1','Beginner'), ('2','Intermediate'), ('3','Advanced'), ('4','Exppert'), ] difficulty = models.CharField( max_length=2, choices=DIFFICULTY_LEVEL, default=2, ) objects = InheritanceManager() class Meta: verbose_name = _("Question") verbose_name_plural = _("Questions") ordering = ['category'] def __str__(self): return self.content class MCQuestion(Question): answer_order = models.CharField( max_length=30, null=True, blank=True, choices=ANSWER_ORDER_OPTIONS, help_text=_("The order in which multichoice " "answer options are displayed " "to the user"), verbose_name=_("Answer Order")) def check_if_correct(self, guess): answer = Answer.objects.get(id=guess) if answer.correct is True: return True else: return False @property def order_answers(self, queryset): if self.answer_order == 'content': return queryset.order_by('content') if self.answer_order == 'random': return queryset.order_by('?') if self.answer_order == 'none': … -
Integrating Django and React
So guys, I was trying to integrate Django and React. I have seen different ways of doing that. The method that I tried using is the one where there are two different folders frontend and backend. The backend has my Django project and the frontend has my React app created by the create-react-app command. I could fetch data from the API using axios. What has been difficult for me is the authentication part. It uses actions and reducers for that. It also uses tokens and other stuffs too. I found a tutorial which explains this clearly. But it's kindda outdated. I was following it step by step until it reached the authentication part and it didn't work, which made it more complicated for me to understand it. So I was looking for another approach or guide that I can follow for the integration of Django and React - specially the authentication part. Thank you! -
Trying to connect Django to Payfort with an API .(Payment gateway integration). when i run the pay.html it gives me a value error in my views file
Error is :ValueError: The view hadid.views.initiate_payment didn't return an HttpResponse object. It returned None instead. Exception Location: C:\Users\Chaims music\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py in _get_response, line 124 I am adding my def initiate_payment below def initiate_payment(request): if request.method == "GET": return render(request, 'templates/pay.html') try: username = request.POST['username'] password = request.POST['password'] amount = int(request.POST['amount']) user = authenticate(request, username=username, password=password) auth_login(request=request, user=user) except: return render(request, 'templates/pay.html', context={'error': 'Wrong Account Details or amount'}) transaction = Transaction.objects.create(made_by=user, amount=amount) transaction.save() This is just the initiate_payment where the error is coming from. please help i already tried similiar error if any other file is needed let me know . any help is appreciated . -
django - How to create a form inside a detail view
I am creating a online debate app using django. I have used class based list view to create different topics using pk and once i click on the topic it takes me to its details page and once I go to the detail page I need a two text boxes to enter my for point and against point and after entering the point I need to display the point below the textbox. I have create the list of topics but unable to do the textbox to that particular page. Please help me. -
Django max_length character count shows the wrong number of characters
models.py class Tweet(models.Model): content = models.TextField(max_length=1000) ... forms.py ... tweet = forms.CharField( widget=forms.Textarea( label='Tweet', max_length=Tweet._meta.get_field('tweet').max_length) ... views.py class TweetCreate(LoginRequiredMixin, CreateView): login_url = reverse_lazy('home:login') model = Tweet slug_url_kwarg = 'tweet_slug' form_class = TweetForm template_name_suffix = '-create' def form_valid(self, form): self.tweet = form.save(commit=False) self.tweet.author = self.request.user print(form.cleaned_data['tweet']) # Passing case return super(TweetCreate, self).form_valid(form) def form_invalid(self, form): print(form.data['tweet']) # Failing case return super(TweetCreate, self).form_invalid(form) Failing case This is the test text I am using. It has exactly 1000 characters. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam porta suscipit tellus eget tristique. Etiam sit amet neque ac sem posuere mollis a imperdiet tellus. Nulla facilisi. Nulla pulvinar in nunc eget pellentesque. Integer volutpat, mauris in sollicitudin dictum, velit turpis rhoncus lacus, ac feugiat libero risus id risus. In ac gravida risus. Sed nec enim vel est interdum scelerisque. Integer at fringilla tortor, sit amet porta tortor. Maecenas congue euismod ipsum. Integer efficitur est risus. Quisque id erat tincidunt, convallis justo eget, eleifend lacus. Praesent volutpat tellus et accumsan accumsan. Curabitur sollicitudin, sem eu finibus iaculis, lectus orci suscipit eros, nec faucibus quam metus quis orc. Aliquam erat volutpat. Cras risus ex, venenatis nec risus eu, scelerisque fermentum neque. Praesent in finibus metus. … -
What does API endpoint refers to?
For example, I have a simple model for a bookshop. models.py class Author(models.Model): name = models.CharField(max_length=200) added_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=300) author = models.ForeignKey(Author, on_delete=models.CASCADE) added_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.title and the serializers too serializers.py from .models import Author, Book class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ['id', 'name', 'added_by', 'created_by'] class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ['id', 'title', 'description', 'created_date', 'author', 'added_by'] and I have designed the api views for the crud operation which is not necessary to show here. I have also completed the urls.py for the four crud views. I just want to know what api endpoints actually refers to in this case. -
Get file URL from raw django SQL query
I have two models class Post(models.Model): ... class PostImage(models.Model): post = models.ForeignKey(Post) ... In a ListView I need to query post and one image for it, so I end up writing raw query. What I hit now is that the url fields are simple path strings which django tries to load from my app, instead of the MEDIA_URL which otherwise works if object is loaded via the ORM. Is there a way to convert that path to url in the template using the django sytax ? {{ post.image.url }} -
Formset and Form Wizard, Django
I have created a working first page using Form Wizard, on second page I am trying to use the value from first page which is stored to create formset forms. Is there a tutorial/guidance or documentation which helps? I went through documentation but am unable to figure it out. -
Django Model Form DateTimeField form validation error
I am a django noobie, I am having problem with models Datetimefield. When I am using model form to fill the date time it's showing pleae enter valid date. Here is My files Views.py def Report_incident(request): if request.method=='POST': form=IncidentReportForm(request.POST) if form.is_valid(): report=form.save(commit=False) report.user=request.user report.save() return HttpResponse('Success') else: form=IncidentReportForm() context={'form':form} return render(request, 'Assginment/report.html',context) Here is Model Form forms.py class DateTimeInput(forms.DateTimeInput): input_type = 'datetime-local' class IncidentReportForm(forms.ModelForm): incident_cat=( ('Environmental incident','Environmental incident'), ('Injury/Illness','Injury/Illness'), ('Property Damage','Propert Damage'), ('Vehicle','Vehicle'), ) time=forms.DateTimeField(widget=DateTimeInput(), input_formats=['%d/%m/%Y %H:%M:%S']) incident_type=forms.MultipleChoiceField(choices=incident_cat, widget=forms.CheckboxSelectMultiple) class Meta: model=Incident fields=('location','description','incident_location', 'severity','cause','action_taken') Here is my Models.py part class Incident(models.Model): location_choices=( ('Corporate Headoffice','Corporate Headoffice'), ('Operations Department','Operations Department'), ('Work Station','Work Station'), ('Marketing Division','Marketing Division'), ) severity_choices=( ('Mild','Mild'), ('Moderate','Moderate'), ('Severe','Severe'), ('Fatal','Fatal'), ) location=models.CharField(choices=location_choices,max_length=300, default='Corporate Headoffice') description=models.TextField() time=models.DateTimeField() incident_location=models.CharField(max_length=200) severity=models.CharField(max_length=200,choices=severity_choices, default='Mild') cause=models.TextField() action_taken=models.TextField() incident_type=models.CharField(max_length=200,null=True,blank=True) reporter=models.ForeignKey(MyUser, on_delete=models.CASCADE, related_name='reporter') My template {% extends "base.html" %} {% block title %}Report An Incident {% endblock %} {% block content %} <form method="POST"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Report Incident"> </form> <p>{{ cd }}</p> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape … -
How do I not let a user be able to modify data of another user, using django-rest-framework
I am using django-rest-framework and generic views to build an API for a simple blog app. I am using the RetrieveUpdateAPIView for updating data. By default, if I have a post made by user 1, user 2 can send a POST request and be able to modify the data of the post. I do not want this to happen. This is what I have tried: class PostUpdateAPIView(RetrieveUpdateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer def perform_update(self, serializer): if self.request.user == self.request.POST.get('user'): serializer.save(user=self.request.user) But this does not work. It does not let another user update the post, but it does not let the same user update the post either. I am a complete beginner so I don't really know how to query properly yet. What can I do to make this work? -
I want to pass the instance of one form to another form. How can I do that?
For eg: I have booking form and I have passenger form. I have one to one relationship with Booking model and Passenger model. Now I am on booking form, and when I click "book this flight" I am routed to passenger form. Now at that time, I want to pass the instance of booking form to passenger form. IN the following code, I am putting instance of booking form in passenger form which doesnt work. Can someone help?? def bookpassenger(request,pk): obj = Booking.objects.get(id=pk) content = { 'form': PassengerForm(instance= obj) # 'items': Booking.objects.get(id=pk) } return render(request, 'booking/passenger.html', content) This is the view after i submit the passenger form. def bookpassengersubmit(request): # if request.method == 'POST': form = PassengerForm(request.POST or None) if form.is_valid(): form.save() print('we are good') messages.success(request, 'Successfully added') return redirect('booking') # else: # messages.error(request, 'Submit again') # return redirect('bookpassengersubmit') -
django - how to get all the projects for a team?
I am new to Django and have a question I couldn't solve it by myself. It is a big question for me. I want to show the list of Projects related to a specific Team and show it in a ListView. I would assume it should check the current user belong to which team and then based on the team, it should list the projects. I have a two apps in my project: 1) users and 2)projects users.models: from django.contrib.auth.models import AbstractUser from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse class CustomUser(AbstractUser): bio= models.CharField(max_length=300, null= True, blank=True) class Team (models.Model): title = models.CharField(max_length=200) user= models.ManyToManyField(get_user_model()) date_created= models.DateTimeField(auto_now_add=True, blank=True, null=True) date_updated= models.DateTimeField(auto_now=True,blank=True, null=True ) def __str__(self): return self.title def get_absolute_url(self): return reverse('team_detail', args=[str(self.pk)]) and the project model is class Project (models.Model): team= models.ForeignKey(Team,on_delete=models.CASCADE ) title = models.CharField(max_length=150, null=False, blank=False) notes = models.TextField( null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True) date_updated = models.DateTimeField(auto_now=True, blank=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('project_detail', args=[str(self.pk)]) in projects.views: I made the following codes but cant work out the queryset between two models. class ProjectPageView(ListView): model = Project def get_queryset(self): queryset = super(ProjectPageView, self).get_queryset() queryset = queryset.filter( XXXXXXXXXXXXXXX ) return queryset … -
sweetalert not working on django template
I started with the following code to send the ID to a method to delete an object of model.But the first ID is always sent. this is my HTML and JavaScript code: {% for yad in yads %} <form action="{% url 'del-yadd' %}" method="post" id="myform"> {% csrf_token %} <button type="button" name="yidd" value="{{yad.id}}" id="btndelme" class=" btn btn-danger" onclick=" swal({ title: 'warning!', text: 'do you want to delete?', type: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', cancelButtonText:'no', confirmButtonText: 'yes' }, function(isConfirm) { if (isConfirm) { document.querySelector('#myform').submit(); }}); ">delete</button> </form> {% endfor %} and this is my Django view code: def delete_yadd(request): id=request.POST['yidd'] yad=Yadd.objects.filter(id=id).delete() return redirect('home') -
Django login auth form with custom user model
I try to use the default django auth form for login. Django version 3.1 settings.py: AUTH_USER_MODEL = 'app.User' user.py: class User(AbstractUser): email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] According to the documentation: AuthenticationForm: Uses the username field specified by USERNAME_FIELD. However when i use the default authentication form it provides me a field for username and not email. When i handle the username field as an email it returns validation error (Please enter a correct email and password. Note that both fields may be case-sensitive). Any ideas what can be wrong?