Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3.1.1 NOT NULL constraint failed with Date
I'm getting this error on Django 3.1.1 while trying to define a model with an optional date field: class Tickets(models.Model): subject = models.CharField(max_length=255) content = models.TextField(blank=True) category = models.ForeignKey("TicketCategories", on_delete=models.PROTECT, related_name='ticket_category') openDate = models.DateTimeField(auto_now_add=True) closeDate = models.DateTimeField(blank=True, null=True) class Meta: verbose_name_plural = "Tickets" def __str__(self): return f"{self.id} {self.subject}" In this case closeDate should accept null and the user should be able to leave it empty on the admin panel. Unfortunately I am getting this error: NOT NULL constraint failed: api_tickets.closeDate Am I doing something wrong? -
Registration - sequence item 0: expected str instance, NoneType found
Django Version: 3.0.8 - Python Version: 3.7.8 I discovered an error on my Django site recently. When a user wants to create an account it returns this error: sequence item 0: expected str instance, NoneType found Operation: account creation (check if username does not already exist on the DB) creation user Active = False sends an email for confirmation of account creation. Error appears in the first step, the account is created (Active = False), no email is sent and error displayed. Traceback (most recent call last): File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/eodj89/DjangoPro/user/views.py", line 45, in signup user.save() File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 66, in save super().save(*args, **kwargs) File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/db/models/base.py", line 746, in save force_update=force_update, update_fields=update_fields) File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/db/models/base.py", line 795, in save_base update_fields=update_fields, raw=raw, using=using, File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in send for receiver in self._live_receivers(sender) File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp> for receiver in self._live_receivers(sender) File "/home/eodj89/DjangoPro/user/models.py", line 479, in create_user_profile UserProfile.objects.create(user=instance) File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 433, in create obj.save(force_insert=True, using=self.db) File "/home/eodj89/DjangoPro/user/models.py", line 346, in save … -
How can I upload profile picture in user extended model in Django
I am not getting any error while uploading cover image to the Django's User extended model but I cannot see what is wrong I'm doing because it's not giving any error and not even updating my model. Here I am giving the source code forms.py class UpdateCoverImageForm(forms.ModelForm): class Meta: model = Memer fields = ['cover'] views.py def profile(request, username): try: user = User.objects.get(username=username) user_ = User.objects.filter(username=username) memer = Memer.objects.filter(user=user_[0].id) except User.DoesNotExist: raise Http404("Memer does not exist.") context = { 'user_': user_, 'memer': memer, } if request.method == "POST": bioForm = EditBioForm(data=request.POST, instance=request.user.memer) coverImageForm = UpdateCoverImageForm(data=request.FILES, instance=request.user.memer) if bioForm.is_valid(): memer_ = bioForm.save(commit=False) memer_.save() messages.success(request, "Bio successfully updated your profile") return redirect('/profile/'+user_[0].username) elif coverImageForm.is_valid(): memer_ = coverImageForm.save(commit=False) memer_.save() messages.success(request, "Cover Image has been updated successfully!") # print(coverImageForm) return redirect('/profile/'+user_[0].username) else: messages.error(request, "Something wrong happend") return redirect('/profile/'+user_[0].username) return render(request, 'profile.html', context) profile.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ UpdateCoverImageForm }} <input type="submit" value="save"> </form> -
The order of inherited classes matters in Python?
I came across this error in my django application after hitting submit on a create or edit form: No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.. This was confusing because I have a get_success_url passed down through inheritance. To be clear, I have found the issue, but have no earthly idea why my solution worked. Here was the code causing the error inside .../views.py: class FormViews(): model = Ticket form_class = TicketForm def get_success_url(self): return reverse('tickets:index') class TicketCreate(CreateView, FormViews): template_name = 'tickets/ticket_create_form.html' model = Ticket form_class = TicketForm class TicketUpdate(UpdateView, FormViews): model = Ticket form_class = TicketForm template_name_suffix = '_update_form' I created the FormViews class so there would not be any repeated code for the model, form_class, and get_success_url. I was able to resolve this error by switching the parameters in my function definitions: class TicketCreate(CreateView, FormViews) became class TicketCreate(FormViews, CreateView) class TicketUpdate(UpdateView, FormViews) became class TicketUpdate(FormViews, UpdateView) This fixed it. Now I redirect to the index page without any issues. Why is it that the get_success_url is recognized after switching the listed parent classes? I would have thought that the attributes and functions are inherited and recognized by Django regardless … -
How to create a dynamic choice field without refreshing the server? Django
I'm creating a form which takes in one of their fields the list of categories the user created. But i'm having problems with that, the list is working but if i create a new category, it will not be shown in the form field until i refresh the server. So how can i make this without refreshing the server? This is my models: class Category(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(blank=True) created_date = models.DateTimeField(default=timezone.now) thumb = models.ImageField(default='default_notes.png', upload_to='notes_pics') def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:category-detail', kwargs={'pk': self.pk}) def __str__(self): return 'Notes: {}'.format(self.status) class Meta: verbose_name = 'Category' ordering = ['created_date'] class Notes(models.Model): PR = 'PRIVATE' OPTIONS_CHOICES = ( ('PRIVATE', 'PRIVATE'), ('PUBLIC', 'PUBLIC'), ) UN = 'ESCOGE UNA CATEGORIA' CAT_CHOICES = Category.objects.all().values_list('title','title') title = models.CharField(max_length=100) content = models.TextField(blank=True) created_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name = 'Category', choices=CAT_CHOICES, null=True, default=UN) notes_options = models.CharField(max_length=40, choices=OPTIONS_CHOICES, default=PR) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:notes-detail', kwargs={'pk': self.pk}) def __str__(self): return 'Notes: {}'.format(self.status) Thank you very much for your help! -
Can't deploy Django application to AWS wsgi.py
I'm deploying from codepiple with git and I keep getting this error for the last 2 hours been looking for solutions but I'm still enctountering it Target WSGI script not found or unable to stat: /opt/python/current/app/invgen/wsgi.py -.ebexstentions django.config -django -django wsgi.py manage.py -venv .gitignore req.txt django.config looks like this : option_settings: aws:elasticbeanstalk:container:python: WSGIPath: django.wsgi:application I also tried option_settings: aws:elasticbeanstalk:container:python: WSGIPath: django/wsgi.py And option_settings: aws:elasticbeanstalk:container:python: WSGIPath: django/django/wsgi.py -
Adding fonts to reportlab in docker container
I have an application running in 3 separated containers. One for django app, one for postgresql and the third one is for nginx. In my docker-compose file I have volume for static files where I put my font.ttf file. I checked the container and the file is there, however it is not being loaded. Here is the settings for web container: web: image: ashowlsky/foodgram:latest restart: always command: gunicorn foodgram.wsgi:application --bind 0.0.0.0:8000 volumes: - ./static:/code/static/ - ./media:/code/media/ ports: - "8000:8000" depends_on: - db env_file: - ./.env And here is the part of view: pdfmetrics.registerFont(TTFont('OS', '/code/static/OpenSans-Regular.ttf')) What do I do wrong? -
Django TypeError Field 'id' expected a number but got <class 'account.models.User'>
Error: TypeError: Field 'id' expected a number but got <class 'account.models.User'>. I have been reading the authentication documentation and I keep getting that error. I have tried a few different permutations of this but I'm really not sure what is going wrong other than its obviously a type error. The end goal is to just return the 'id' and 'email' of the newly created user, along with the token, I haven't been able to test the token returning yet, because of this error, but I imagine it should be good. What is working though is it is successfully posting a new user to the database with a token in another table with a matching key and now I have about 50 users from just testing and messing around. Side note I have overridden the default User Django sets you up with, but I followed the documentation so that code should be solid, but if need I can obviously post it Views.py from rest_framework import status from .models import User from .serializers import UserSerializer, RegisterSerializer from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework.authtoken.models import Token @api_view(['POST',]) def RegisterAPI(request): if request.method == 'POST': serializer = RegisterSerializer(data = request.data) if serializer.is_valid(raise_exception=True): … -
Django Registration - errors messages don't appears
I try to understand why errors don't appears on my template. I'm using classical registration with checks (email and username). If email already exists = error and the same for username. The thing is error appear if it's about password (ex. password are not the same, ...) but for email and username nothing appears. template <form method="post" class="user-log"> {% csrf_token %} {% if form.errors %} <div class="alert alert-warning alert-dismissible fade show" role="alert"> Oupss <a data-toggle="collapse" href="#collapseExample" class="alert-link" style="text-decoration:none;">something wrong</a>! <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true" style="color: #ffd14c;">&times;</span> </button> <div class="collapse" id="collapseExample"> {% for field in form %} {% if field.errors %} <strong>{{ form.label }}</strong> {{ field.errors|striptags }} {% endif %} {% endfor %} </div> </div> views def signup(request): if request.method == 'GET': return render(request, 'register.html') if request.method == 'POST': form = RegisterForm(request.POST) # print(form.errors.as_data()) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your registration' message = render_to_string('user_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return redirect ('user:user_registration_process') else: form = RegisterForm() return render(request, 'register.html', {'form': form}) forms class RegisterForm(UserCreationForm): username = forms.CharField(max_length=50) email = forms.EmailField(max_length=50) password1 = forms.CharField() … -
Video-chat using Django or Python
I want to build a video-chat using Django. Are there any 'batteries included' solutions? If there are no - what libraries or technologies should I use? -
How can I see the buttons in the navbar?
I'm currently coding my first django website and I'm stuck with the navbar. Well, I've downloaded from bootstrap a navbar just like this one. However, when i run the server, the navbar looks like this. I'd like to see the buttons in the navbar. Here's the code: <nav class="navbar fixed-top navbar-light" style='background-color: snow;'> <a class="navbar-brand" href="#"></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-link active" href="#">Home <span class="sr-only">(current)</span></a> <a class="nav-link" href="#">Features</a> <a class="nav-link" href="#">Pricing</a> <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a> </div> </div> </nav> </nav> -
deploying Django project -beginner
please help me I'm a beginner and this is the first time I want to deploy a website I want to use pythonanywhere but I don't know which folders of my project I have to upload hm trying to deploy the site for hours but going nowhere please help this is my source : inside my main project, I have this folder please help me how can i deploy my site -
Sending django single api logs via email
In my django project, I have many REST APIs. But I want to send the logs only for a specific API over email. Also, we have our own project(API) for sending emails which we use in all our django projects for sending the email. I have 2 questions here - how can I send logs only for a specific django api, and not whole project ? How to use our email api(REST) for sending the email if using the logging settings https://docs.djangoproject.com/en/3.1/topics/logging/ ? Thanks in advance. -
DJANGO, Calling one class from another Class by urls
I have a file that n ame is tes.py and in this file has a program class . and program class changes sqlite.db table and processes the data and that give me a table that I need to . so I want make the url for this and when I call the url, the process begin in this class and the the tables will change . I defined url.py : from django.urls import path , include from .tes import Program urlpatterns = [ path('newgp/', Program, name='Program' ), ] but I dont know how to write this line: path('newgp/', Program, name='Program' ) when i run this code i get this error: TypeError: Program() takes no arguments -
Django admin login not working when creating new User structure
I am trying to create a new User model with 'AbstractBaseUser' and 'BaseUserManager' but for soemw reason now when creating a new super user, logging in does not work and shows this error: Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive. Error Image here. Here is my code. models.py from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.db import models class UserManager(BaseUserManager): def create_user(self, email, firstName, lastName, phoneNumber, is_active=True, password=None, is_staff=False, is_admin=False): if not email: raise ValueError("Users must have an email address.") if not password: raise ValueError("Users must have a password.") user_obj = self.model( email=self.normalize_email(email) ) user_obj.set_password(password) user_obj.save(using=self._db) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active return user_obj def create_staffuser(self, firstName, lastName, phoneNumber, email, password=None): user = self.create_user( email, firstName, lastName, phoneNumber, password=password, is_staff=True, ) return user def create_superuser(self, firstName, lastName, phoneNumber, email, password=None): user = self.create_user( email, firstName, lastName, phoneNumber, password=password, is_staff=True, is_admin=True ) return user class User(AbstractBaseUser): objects = UserManager() firstName = models.CharField(max_length=255, unique=True, blank=True, null=True) lastName = models.CharField(max_length=255, unique=True, blank=True, null=True) nickName = models.CharField(max_length=255, unique=True, blank=True, null=True) phoneNumber = models.IntegerField(unique=True, blank=True, null=True) email = models.EmailField(max_length=255, unique=True) confirmed_email = models.BooleanField(default=False) confirmed_phoneNumber = models.BooleanField(default=False) timeStamp = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) … -
How do I write script to send the reports on my mail
I am building a Django report page, and whenever user reports something, I want the message to be sent on my mail box. How can I achieve this using either python or javascript. -
Can I access the choice category in a Django model?
Let's say I have this class PaymentType(models.Model): INSCRIPTION = 'INS' JANUARY = 'JAN' FEBRUARY = 'FEB' MARCH = 'MAR' APRIL = 'APR' MAY = 'MAY' JUNE = 'JUN' JULY = 'JUL' AUGUST = 'AUG' SEPTEMBER = 'SEP' OCTOBER = 'OCT' NOVEMBER = 'NOV' DECEMBER = 'DEC' NAME_CHOICES = [ ('Months'), ( (JANUARY, 'January'), (FEBRUARY, 'February'), (MARCH, 'March'), (APRIL, 'April'), (MAY, 'May'), (JUNE, 'June'), (JULY, 'July'), (AUGUST, 'August'), (SEPTEMBER, 'September'), (OCTOBER, 'October'), (NOVEMBER, 'November'), (DECEMBER, 'December') ) ('Others'), ( (INSCRIPTION, 'Inscription'), ) ] amount = models.FloatField() payment_type = models.CharField(max_length=3, choices=NAME_CHOICES) Is there a way that I can access the 'Months' or 'Others' category? For example I would like the user to be able to add more payment types to 'Others' or add/update the amount for all the 'Months' -
Django Form 'WSGIRequest' object has no attribute 'seller'
I'm doing a rating system inside of a group (channel) of two users. How I can automatically fill seller? As I do for consumer & channel. I use self.request.user for consumer because only consumer can give a grade. Pleas be kind, even if this question appears really simple. class ChannelReview(generic.DetailView, FormMixin): model = Channel context_object_name = 'channel' template_name = 'channel_review.html' form_class = ChannelRatingForm 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(): #seller = form.instance.channel = self.object form.instance.consumer = self.request.user form.instance.seller = seller form.save() return super(ChannelReview, self).form_valid(form) else: return super(ChannelReview, self).form_invalid(form) models.py 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") ... 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 -
NoReverseMatch at / "Reverse for 'home' not found. 'home' is not a valid view function or pattern name."
i'm getting following error while rendering my template someone please help NoReverseMatch at / Reverse for 'home' not found. 'home' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.14 Exception Type: NoReverseMatch Exception Value: Reverse for 'home' not found. 'home' is not a valid view function or pattern name. Exception Location: D:\dev\project\ECOM\env\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 673 Python Executable: D:\dev\project\ECOM\env\Scripts\python.exe Python Version: 3.8.5 Python Path: ['D:\\dev\\project\\ECOM\\ecom', 'D:\\dev\\project\\ECOM\\env\\Scripts\\python38.zip', 'c:\\users\\arjun\\appdata\\local\\programs\\python\\python38-32\\DLLs', 'c:\\users\\arjun\\appdata\\local\\programs\\python\\python38-32\\lib', 'c:\\users\\arjun\\appdata\\local\\programs\\python\\python38-32', 'D:\\dev\\project\\ECOM\\env', 'D:\\dev\\project\\ECOM\\env\\lib\\site-packages'] Server time: Tue, 22 Sep 2020 15:55:56 +0000 Error during template rendering In template D:\dev\project\ECOM\ecom\templates\store\navbar.html, error at line 6 Reverse for 'home' not found. 'home' is not a valid view function or pattern name. 1 <!-- Navbar --> 2 <nav class="navbar fixed-top navbar-expand-lg navbar-light white scrolling-navbar"> 3 <div class="container"> 4 5 <!-- Brand --> 6 <a class="navbar-brand waves-effect" href="{% url 'home' %}" target="_blank"> 7 <strong class="blue-text">MDB</strong> 8 </a> 9 10 <!-- Collapse --> 11 <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" 12 aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> 13 <span class="navbar-toggler-icon"></span> 14 </button> 15 16 <!-- Links --> here is my model.py (i have added get_absolute_url function) class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug … -
Failed to load module script: The server responded with a non-JavaScript MIME type of "text/plain". Strict MIME type checking i
while building a debug toolbar in Django I am getting an error in file toolbar.js ie. s.map: HTTP error: status code 404, net:: ERR_UNKNOWN_URL_SCHEME toolbar.js:1 Failed to load module script: The server responded with a non-JavaScript MIME type of "text/plain". Strict MIME type checking is enforced for module scripts per HTML spec. can anyone tell me the possible fix for that? -
how can I set instance in model when using form in django?
in model.py I have this code: class wallet(models.Model): User = models.OneToOneField(User, on_delete=models.CASCADE ,primary_key=True) coin= models.PositiveIntegerField(default= 50000) password = models.CharField(blank=True , max_length = 50) def __str__(self): return str(self.wallet) this is one-to-one relationship between User and wallet in my form.py I Have this code : class WalletForm(forms.ModelForm): User = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) class Meta: model = wallet fields = ( 'User', 'coin', 'password' ) def __init__(self , user , *args,**kwargs): super().__init__(*args,**kwargs) self.fields['User'].widget.attrs['value'] = Profile.objects.get(pk = user.id) self.fields['User'].widget.attrs['readonly'] = True self.fields['coin'].widget.attrs['value'] = 50000 self.fields['coin'].widget.attrs['readonly'] = True self.fields['password'].widget.attrs['placeholder'] = 'Wallet Password' I am trying to make wallet for every user .. the question is : how can I set User in wallet model to the already user who is logged in my site when the form submitting ... thanks -
Unresolved attribute reference 'title' for class 'ForeignKey' in django models
I got this Unresolved attribute reference 'title' for class 'ForeignKey' error when i tried to call title from Article model class in PostImage model class. Does anyone know why?? class Post(models.Model): title = models.CharField(max_length=250) description = models.TextField() image = models.FileField(blank=True) def __str__(self): return self.title class PostImage(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) images = models.FileField(upload_to = 'images/') def __str__(self): return self.post.title -
How to save a pdf response to django model?
I have a function that calls for an external url to get a pdf format of specific car, so far this is the gist of what I tried: def cars(id): headers = { 'Content-Type': 'application/pdf', 'Authorization': token } url = CAR_URL + f'/cars/{id}' response = requests.get(url, headers=headers) return File(BytesIO(response.content)) def save_car_data(id) ... Car.objects.get_or_create( ... pdf = cars(id) ) Model: class Car(models.Model): created_dttm = models.DateTimeField(auto_now_add=True) owner = models.CharField(max_length=100) pdf = models.FileField(upload_to="cars/", blank=True, null=True) but when I check the django admin it seems there is no file generated and just a button that uploads a file -
Django authentication login() returns anonymous user
I am trying to log in to a database that is not the default database, and for that I've wrote a custom authentication code but whenever I try to login the method returns an AnonymousUser. I've no idea why is it doing so because user authentication is done properly using the authenticate method. Any help would be really appreciated. MY FILES views.py def login_authentication(request): if request.method == "POST": form = New_Login_Form(request.POST) # print(request.POST) if form.is_valid(): email = request.POST['email'] password = request.POST['password'] user_operating_company = request.POST['user_operating_company'] user = authenticate(request, email=email, password=password, db=user_operating_company) if user: login(request, user, user_operating_company) return redirect('test') else: form = New_Login_Form() return render(request, 'index.html', {'form': form}) backends.py from django.contrib.auth.backends import ModelBackend from .models import Account class CustomAuthenticate(ModelBackend): def authenticate(self, request, email=None, password=None, db=None): try: user = Account.objects.all().using(db).get(email=email) if user.check_password(password): return user except: return None def get_user(self, request, email, db): try: return Account.objects.using(db).get(pk=email) except: return None and in the settings.py AUTHENTICATION_BACKENDS = ('accounts.backends.CustomAuthenticate', 'django.contrib.auth.backends.ModelBackend') -
How to configure django ckeditor image upload more easier?
I am using django-ckeditor RichTextUploadingField to allow upload img via editor. But I think this UI is not suit modern web. I want to imporve it like drag and drop or simple auto upload I'm still looking through Google to figure out how to set this up. I think someone has already made this. If there is no proper setup method, I'm going to implement this via Javascript.