Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django union and if statement based on the table in database
My views.py look like this: def home(request): cars = Car.objects.all() bikes = Bikes.objects.all() vehicles_together = cars.union(bikes, all=True).order_by('power') context = { 'vehicles_together': vehicles_together, } return render(request, 'home.html', context) In my HTML I have got a redirect to the detail page, where I need to pass an id. If there was only one table involved, it would look like that: href="{% url 'detail' car.id %}" But I have data from 2 tables displayed and I need to write an If statement based on the table. Is it possible to write an If statement when union is involved? It would have to look like this: if data from table car then href="{% url 'detail' car.id %}", but if data from table bike it would pass bike.id instead of car.id. My detail view looks like this: def detail_view(request, id): car = get_object_or_404(Car, id=id) bike = get_object_or_404(Bike, id=id) photos = PostImage.objects.filter(car=car) photos2 = PostImageBike.objects.filter(bike=bike) return render(request, 'detail.html', { 'car':car, 'bike':bike, 'photos2':photos2, 'photos':photos }) -
How to forward raw email from django
So I have a raw email string I'd like to send to another recipient. I'd like to use Django for this (have 3.1 running). I know I can take my input (say raw_email) and make it a python email.Message running email.message_from_string(raw_email) but from there I'm not sure the best way. I can imagine I could do something weird like instantiate a new instance of django.core.mail.EmailMultiAlternatives and pass each argument 1 by 1 to the constructor, but that seems heavyweight. FWIW I'm not using SMTP, hence the desire to stick with django code/apis. -
functions inside view function in django did not work
I have this python code to recognize color from an image. When I run it manually from pycharm it works perfectly. Then I try to put this inside my web app (I'm using django), I put this code inside my views.py as a view function but it did not work. Can someone explain to me where is my mistake or how to solve this? def identification(request): root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename() img = cv2.imread(file_path) clicked = False r = g = b = xpos = ypos = 0 index = ["color", "color_name", "hex", "R", "G", "B"] csv = pd.read_csv('planning/codes.csv', names=index, header=None) def getColorName(r, g, b): minimum = 10000 for i in range(len(csv)): d = abs(r - int(csv.loc[i, "R"])) + abs(g - int(csv.loc[i, "G"])) + abs(b - int(csv.loc[i, "B"])) if d <= minimum: minimum = d colorname = csv.loc[i, "color_name"] return colorname def draw_function(event, x, y, flags, param): if event == cv2.EVENT_MOUSEMOVE: global r, g, b, xpos, ypos, clicked clicked = True xpos = x ypos = y b, g, r = img[y, x] b = int(b) g = int(g) r = int(r) cv2.namedWindow('Machining Process Identification') cv2.setMouseCallback('Machining Process Identification', draw_function) while 1: cv2.imshow("Machining Process Identification", img) if clicked: cv2.rectangle(img, … -
how to prevent submitting a form with empty CKEditor in django
In my django project, I use Django CKEditor for getting richtextfield in a message form. I want to prevent the user from submitting an empty message. this is my simplified form in one of my templates: <form action="{% url 'contact' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-row"> <div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12"> <div class="form-group"> <div class="row"> <div class="col-1 mr-auto"> <label for="message" class="col-form-label">Message:</label> </div> <div class="col-10 ml-auto"> <textarea name="message" id="message" class="form-control" maxlength="4096" onkeyup="textCounter(this,'counter',4096);" autofocus required ></textarea> </div> </div> </div> </div> </div> <!-- Submit button --> <div class="form-row"> <div class="col-12 col-sm-12 col-md-2 col-lg-2 col-xl-2 mx-auto"> <div class="form-group"> <button class="btn text-capitalize font-weight-bold text-light btn-block" type="submit" value="Send" > Send </button> </div> </div> </div> </form> <script type="text/javascript" src="{% static "ckeditor/ckeditor-init.js" %}"></script> <script type="text/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script> <script src="//cdn.ckeditor.com/4.15.0/full/ckeditor.js"></script> <script> CKEDITOR.replace( 'message' ); CKEDITOR.config.allowedContent = true; CKEDITOR.config.removeFormatAttributes = ''; CKEDITOR.config.ignoreEmptyParagraph = false; CKEDITOR.config.toolbarGroups = [ { name: 'document', groups: [ 'mode', 'document', 'doctools' ] }, { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] }, { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi', 'paragraph' ] }, { name: 'clipboard', groups: [ 'clipboard', 'undo' ] }, { name: 'forms', groups: [ 'forms' ] }, { name: 'editing', groups: [ 'find', 'selection', 'spellchecker', 'editing' … -
AUTH_USER_MODEL refers to model 'Sistema.User' that has not been installed with Pyinstaller
AUTH_USER_MODEL refers to model 'Sistema.User' that has not been installed with Pyinstaller I'm using a custom User to add fields to this model. However, I was unable to solve the problem with pyinstaller. Could anyone help? Very grateful for the attention. server@srvr:~/app$ ./dist/sistema Traceback (most recent call last): File "django/apps/config.py", line 178, in get_model KeyError: 'user' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "django/contrib/auth/__init__.py", line 157, in get_user_model File "django/apps/registry.py", line 211, in get_model File "django/apps/config.py", line 180, in get_model LookupError: App 'Sistema' doesn't have a 'User' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> File "manage.py", line 17, in main File "django/core/management/__init__.py", line 401, in execute_from_command_line File "django/core/management/__init__.py", line 377, in execute File "django/__init__.py", line 24, in setup File "django/apps/registry.py", line 122, in populate File "django/contrib/auth/apps.py", line 22, in ready File "django/contrib/auth/__init__.py", line 161, in get_user_model django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'Sistema.User' that has not been installed [694099] Failed to execute script manage -
GCP Cloud NLP API error when running in heroku in django
my django project is perfectly running in local computer, but when i deployed to heroku it shows error when GCP api calls. i have used GCP NLP apis and i also want to know that how to set GOOGLE APPLICATION CREDENTIALS? as i already set but showing this error on heroku server only. error is - If the request argument is set, then none of the individual field arguments should be set.enter image description here -
Static files serving from Google Cloud Console in Django
I am using GCP to serve static files. But Django is using a signed URL which contains expire googleserveraccessId and etc. Please tell me how I can use an unsigned URL which only has a path. my settings.py file DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' STATICFILES_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = 'xyzxyzxyx' GS_CREDENTIALS = service_account.Credentials.from_service_account_file( "project/filename.json" ) STATICFILES_DIRS =[ os.path.join(BASE_DIR, 'myapp/static') ] STATIC_URL = '/static/' STATIC_ROOT = 'https://storage.googleapis.com/{}/static/'.format(GS_BUCKET_NAME) MEDIA_URL = 'https://storage.googleapis.com/{}/'.format(GS_BUCKET_NAME) MEDIA_ROOT = 'https://storage.googleapis.com/{}/'.format(GS_BUCKET_NAME) -
Exception Value: Module "storages.backends.gcloud" does not define a "GoogleCloudMediaStorage" attribute/class
I am working on uploading media file to google cloud storage from my django app running on cloud engine. But while submitting file, I am keep getting error The above exception (module 'storages.backends.gcloud' has no attribute 'GoogleCloudMediaStorage') was the direct cause of the following exception:. Following error screen shot and code snippets for more details. Any help on this is much appreciated. settings.py from google.oauth2 import service_account GS_CREDENTIALS = service_account.Credentials.from_service_account_file( os.path.join(BASE_DIR, 'credential.json')) DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudMediaStorage' GS_PROJECT_ID = 'project-test' GS_BUCKET_NAME = 'project-bucket' MEDIA_ROOT = '/media/' UPLOAD_ROOT= 'media/cad_files' MEDIA_URL = 'https://storage.googleapis.com/{}/'.format(GS_BUCKET_NAME) gcloud.py is from django.conf import settings from storages.backends.gcloud import GoogleCloudStorage from storages.utils import setting from urllib.parse import urljoin class GoogleCloudMediaStorage(GoogleCloudStorage): """ Google file storage class which gives a media file path from MEDIA_URL not google generated one. """ def __init__(self, *args, **kwargs): if not settings.MEDIA_URL: raise Exception('MEDIA_URL has not been configured') kwargs['bucket_name'] = setting('GS_BUCKET_NAME', strict=True) super(GoogleCloudMediaStorage, self).__init__(*args, **kwargs) def url(self, name): """.url that doesn't call Google.""" return urljoin(settings.MEDIA_URL, name) views.py def file_upload(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): file = form.save(commit=False) # commit=False Read file but Don't save the file yet file.uploaded_file = request.FILES['uploaded_file'] # Read file instance in model parameter file.customer = request.user.customer # Get current … -
Django: https://127.0.0.1:8000 not working in django
Long story short, I created a django project and used the django for professionals book 2.2 as a reference(Made a couple more fields in the models). However, once I reached the security chapter and tried running the docker commands in the terminal, I get a programming error. After researching and trying to debug, I decided to delete all migrations from the project, the volume from the docker container, and delete/comment out certain files/code. From here, I reran all the migrations and now when I check my terminal, I still get 21 unapplied migrations and "Starting development server at http://0.0.0.0:8000/". When I click on the link, I get the "Disallowed Host at / ...Invalid HTTP_HOST header:..." I am just wondering what went wrong because it seems to me that my docker-compose.yml and settings.py seems to be contributing to this error. I am trying to get my terminal to get the link to "https://127.0.0.1:8000/". settings.py: I am using the postgres database DEBUG = int(os.environ.get('DEBUG', default=0)) ALLOWED_HOSTS = [] docker-compose.yml: I left out the secret key version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 environment: - DEBUG=1 - ENVIRONMENT=development volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: … -
I am tried to setup the saleor in my windows 10 but its giving error
in dlopen raise OSError(error_message) # pragma: no cover OSError: no library called "cairo" was found cannot load library 'C:\msys64\mingw64\bin\libcairo-2.dll': error 0x7e cannot load library 'libcairo.so': error 0x7e cannot load library 'libcairo.2.dylib': error 0x7e cannot load library 'libcairo-2.dll': error 0x7e -
Displaying model data in Django using for loop
Im attempting to display all the course Names in my Course Model, {% for course in object_list%} <li>{{ course.courseName}} </li> {% endfor %} </ol> Heres a snippet from the HTML page Im trying to display them in. here's my models.py # Create your models here. SEMESTER_CHOICES = ( ("SPR 21", "SPR 21"), ("FA 21", "FA 21"), ("SPR 22", "SPR 22"), ("FA 22", "FA 22"), ("SPR 23", "SPR 23"), ("FA 23", "FA 23"), ("SPR 24 ", "SPR 24"), ("FA 24", "FA 24"), ) PROGRAM_CHOICES = ( ("Architectural Science","Architectural Science"), ("Civil Engineering","Civil Engineering"), ("Computer Information Technology","Computer Information Technology"), ("Computer Science","Computer Science"), ("Construction Management","Construction Management"), ("Electrical Engineering","Electrical Engineering"), ("Engineering Technology Management","Engineering Technology Management"), ("Manufacturing Engineering","Manufacturing Engineering"), ("Mechanical_Engineering","Mechanical_Engineering") ) # declaring a Student Model class AddCourse(models.Model): program = models.CharField( max_length = 20, choices = PROGRAM_CHOICES, default = 'Architecural Science' ) courseName = models.CharField(max_length=250) semester = models.CharField( max_length = 20, choices = SEMESTER_CHOICES, default = 'SPR 21' ) preRequisites = models.TextField() def __str__ (self): return self.courseName and here is my views.py from django.shortcuts import render from .models import AddCourse from django.contrib.auth.decorators import login_required # Create your views here. @login_required def currentpathway(request): return render(request, "SEAS_Course_Planner/home.html") @login_required def newpathway(request): return render(request, "SEAS_Course_Planner/newpathway.html") Nothing is printing out and … -
Why is Django giving me a completely different image from what I have?
I've been practising Django for quite awhile and so I've been redoing projects to get myself familiar with the whole process. However, when I started a new project and made a static folder, the image appearing on the website is not the new image I have in my static folder, but is the image from the previous project which has already been deleted. In fact, I've already deleted everything used in that project, but still the image I am trying to use appears as the previous one. On top of that, when I inspect element and look at sources, the image is from my previous django project and not of my new static folder. Is this a bug or feature or did I mess something up? -
I'm learing about Conda environment.yml and I'm not sure how to get Conda to find a certain version of dependancy
So I want to be able to build a environment that contains all libs I need for my project that im going to port to Docker. So far my yml looks like this: name: wt channels: - anaconda - conda-forge - defaults dependencies: - python=3.7.* - django=3.1.1 - wagtail=2.11 So judging by the compatibility link I have the correct versions to run Wagtail but when I goto call conda env create -f environment.yml I get: ResolvePackageNotFound: - wagtail=2.11 So I had a look on the Conda repo and I can't see a version 2.11. How would I get V 2.11 when can only get with v1 or v 2.7 which are both incompatible? I have checked Wagtail Github and they are on version 2.7 but version 2.1 has LTS and thats why I would like to use it. -
how to get data from gst api while click on submit button in django
I have a field gst in that when user input the data get from the gst api .i am totally beginers and don't know how to do this. -
How do you add a constraint? in the models.py in Django to check the variable the models get?
I have a code as the following: # models.py class UserFollower(models.Model): user_id = models.ForeignKey(CustomUser, related_name="following", on_delete=models.CASCADE) following_user_id = models.ForeignKey(CustomUser, related_name="followers", on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, db_index=True) def __str__(self): return f"{self.user_id} follows {self.following_user_id}" Now here, I want to check when the data is passed, if the user_id equals the following_user_id, it will output a message saying something like "It isn't possible" and not save the model. Of course later in the development, I wouldn't have the "Follow" button or something like that associated with the same user, but in this case, how would I do so?? Or is it something I can't do in the models.py and do it in the views.py? -
Django admin panel has no styling
When I started my project and went to the admin panel the admin panel had no styling There is no styling as usual. What should I do to fix it. Thank you -
Django not creating new object instance
Hey guys I'm getting an error when I try to submit a reply to a post on my forum app. It says that Reply is not defined. But, as you can see, it is defined in my Models.py file and I have run makemigrations and migrate. I have opened the database with a viewer and I can see that the Reply table exists with all the required fields. Anyone know why I'm getting error? views.py: def reply(request, id): query = NewPost.objects.filter(id = id) return render(request, "network/reply.html", {"queries": query}) def replied(request): body = request.POST.get("body") username = request.POST.get("username") postID = request.POST.get("postID") #new = Reply.objects.create(postID = postID, username = username, body = body) #new.save() return render(request, "network/replied.html") Models.py: class Reply(models.Model): postID = models.IntegerField(default=0) username = models.CharField(max_length=64) body = models.CharField(max_length=64, default="") rating = models.IntegerField(default=0) timestamp = models.DateTimeField(auto_now_add=True, null=True, blank=True) reply.html: {% extends "network/layout.html" %} {% block body %} {% for query in queries reversed %} <h2>Reply to {{query.username}}'s Thread</h2> <form method="POST" name="replied" action="/replied"> {% csrf_token %} <input type="text", name="title", value="Re:{{query.title}}" readonly> <p>{{query.username}} said: </p> <textarea name="oldBody" readonly>{{query.body}}</textarea> <p></p> <textarea name="body" placeholder="Enter Thread Body"></textarea> <p></p> <p></p> <input type="hidden" value={{ user.username }} name="username"> <input type="hidden" value={{ query.id }} name="postID"> <input type="submit" value="Reply"> </form> {% endfor %} … -
Django TestCase helper function inheritance
After writing tests for my Django Model Validators I found I was duplicating a lot of code and wanted to simplify it using some sort of helper function. This answer may be a solution but I can't translate it to my problem. The code example below will return the following error message: AttributeError: 'ExampleTestCase' object has no attribute 'assertRaised' from django.test import TestCase from django.core.exceptions import ValidationError from .models import ExampleModel class ExampleTestCase(TestCase): def setUp(self): ExampleModel.objects.create(string='1-2-3') def test_string_validation(self): example_model = ExampleModel.objects.get(pk=1) field_name = 'string' expected_raise = ['1', 'a-a-a', '1--23'] # These inputs should raise Validation Errors expected_ok = ['9-8-7', '2-2-2'] # These inputs should not raise Validation Errors self.helper_func( obj=example_model, field_name=field_name, raise_list=expected_raise, ok_list=expected_ok ) # Duplicated code I want to avoid: # example_model.string = '1' # self.assertRaises(ValidationError, example_model.full_clean) # example_model.string = 'a-a-a' # self.assertRaises(ValidationError, example_model.full_clean) # example_model.string = '1--23' # self.assertRaises(ValidationError, example_model.full_clean) # example_model.string = '9-8-7' # example_model.full_clean() # self.assertEqual(example_model.string, '9-8-7') # example_model.string = '2-2-2' # example_model.full_clean() # self.assertEqual(example_model.string, '2-2-2') def helper_func(self, obj, field_name, raise_list, ok_list): for i in raise_list: setattr(obj, field_name, i) # Current code uses try, except blocks but below is desired self.assertRaised(ValidationError, obj.full_clean) for i in ok_list: setattr(obj, field_name, i) # Current code uses try, except blocks … -
Django Has to Keep Updating The Backed Updated Info
I need technical advice about Django and I have no idea where to even look for the general direction. Right now, I have an app that keeps track of work/shift schedule. It is an Android/iOS app with a Django backend and I am the backend engineer. When a user updates their schedule and makes a backup to our server, the phone sends a long sequence of requests. This sequence starts with 'backup' URI and ends with 'vacationData' URI. When the backup is successful, the last request my server will receive will be the 'vacationData' URI. What I am trying to achieve is this: just like in Google Spreadsheet, whenever the user updates their schedule and make a backup, the "shared schedule" URI has to update accordingly. I began setting up the "share schedule" URI with Django Signals that listens to the "vacationData" URI. However, now I realize that the only user sends GET request to "shared schedule" URI and thus the shared timetable won't be updated unless the user chooses to send a new GET request to "shared schedule". Is there any way to send the updated(newly backed up) schedule info to the client regardless of whether they requested it … -
How to get msgctxt in .po file with Django and pgetttext()
I am writing a notification module for a booking app which has English and Spanish. It is supposed to be flexible enough to deal with any model and any status change (e.g. created, updated, cancelled etc). The get_subject() function will prepare a 'subject' line for the notification using the related object's model name (e.g. Appointment) and the status verb. So we should get 'Appointment 123ABC modified' or 'Payment 789XYZ created' etc. I have it working translationwise all apart from allowing for the grammatical gender of words in Spanish. So 'Appointment 123ABC modified' would be 'Cita 123ABC actualizada' whereas say, 'Payment 123ABC modified' would be 'Pago 123ABC actualizado'. I know the solution is to use pgettext(context, string) along with having the msgctxt in the .po file, but I just can't figure out how to get manage.py makemessages to add the msgctxt when it preps the .po file. I have tried various ways of editing the .po directly but I am getting errors when running compilemessages (Execution of msgfmt failed: backend/locale/es/LC_MESSAGES/django.po:3966: duplicate message definition...) and makemessages just overwrites my edits anyway. I am not sure whether all I need is the right format for the po file or whether I need the … -
What should be written to the Superfeedr callback file, in Django, Python?
I have a backend project developed in Django and I need to create an url endpoint in my urlpatterns variable, to receive push notifications from Superfeedr. How should I do it? -
How do I update my inventory Database in django?
I am creating a web application that will serve as a grocery store. The way I set it up is so the customer can come onto the website, click on the items that they would like to purchase, and then click a submit button to purchase those items. The problem I am running into is having a views.py function to take the information of which products were selected and subtracting 1 from the quantity of the database. """models.py""" class Post(models.Model): title = models.CharField(max_length=100) Price = models.DecimalField(max_digits=4, decimal_places=2,default=1) Sale = models.DecimalField(max_digits=4, decimal_places=2,default=1) quantity = models.IntegerField(default=1) author = models.ForeignKey(User, on_delete=models.CASCADE) category = TreeForeignKey('Category',null=True,blank=True, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) views.py class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' def inventory(request): request.POST.getlist('products') for x in range (len('products')): a = Post.objects.get('products[x]') count = a.quantity() count -=1 a.quantity = count a.save() return HttpResponseRedirect("{% url 'profile'%}") urls.py path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('inventory', views.inventory, name='inventory'), home.html {% extends "blog/base.html" %} {% block content %} {% for post in posts %} {% if post.quantity > 0 %} <input type="checkbox" name="products" id="product_{{ post.id }}" value="{{ post.id }}"> <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username … -
Displaying data from 2 tables and ordering them
I have got 2 tables with the same fields: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) class Post2(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) I am displaying them on the same page: def home(request): context = { 'posts': Post.objects.all(), 'post2': Post2.objects.all() } return render(request, 'home.html', context) I use that in the html: {% for post in posts %} <p>{{ post.title }}</p> {% endfor %} {% for post in post2 %} <p>{{ post2.title }}</p> {% endfor %} What I am trying to do is display them all based on the date posted. Currently its doing so, but the tables are not mixed. First are displayed the posts from table Post ordered by date, and then there are displayed posts from table Post2 based on date. Is there a way to order by date, but taking to consideration both tables, so the posts from both tables would be mixed and displaying in order by date? -
An email subscription form with Django and Mailchimp doesn't work after deployment (DigitalOcean)
I've built a simple email subscription form with Django and Mailchimp. It works perfectly fine locally, however, after deploying it to DigitalOcean it doesn't seem to work. I thought it might be related to the database, but I did migrate on the server and haven't received any errors (using Ubuntu 20.04 on the server). Hope someone has a clue and could assist me with this issue. Here is the form: https://www.winoutt.io views.py from django.contrib import messages from django.http import HttpResponseRedirect # from django.conf import settings from .models import Signup from decouple import config import json import requests # MAILCHIMP_API_KEY = settings.MAILCHIMP_API_KEY # MAILCHIMP_DATA_CENTER = settings.MAILCHIMP_DATA_CENTER # MAILCHIMP_EMAIL_LIST_ID = settings.MAILCHIMP_EMAIL_LIST_ID MAILCHIMP_API_KEY = config("MAILCHIMP_API_KEY") MAILCHIMP_DATA_CENTER = config("MAILCHIMP_DATA_CENTER") MAILCHIMP_EMAIL_LIST_ID = config("MAILCHIMP_EMAIL_LIST_ID") api_url = f"https://{MAILCHIMP_DATA_CENTER}.api.mailchimp.com/3.0" members_endpoint = f"{api_url}/lists/{MAILCHIMP_EMAIL_LIST_ID}/members" def subscribe_email(email): data = {"email_address": email, "status": "subscribed"} req = requests.post( members_endpoint, auth=("", MAILCHIMP_API_KEY), data=json.dumps(data) ) return req.status_code, req.json() def newsletter_email_list(request): if request.method == "POST": email = request.POST.get("email", None) email_query = Signup.objects.filter(email=email) if email: if email_query.exists(): messages.info(request, "You are already on the waitlist.") else: try: subscribe_email(email) subscribed = Signup.objects.create(email=email) subscribed.save() messages.success( request, "Thank you! We're putting you on the waitlist. Bear with us.", ) except: messages.warning(request, "Something went wrong. Please try again.") return HttpResponseRedirect(request.META.get("HTTP_REFERER")) else: messages.warning(request, … -
Custom Django Login
I'm struggling to pass through/access the password that should be passed through from the form I have created. Can someone tell me where I am going wrong? I need a custom login page since I want to alter the way the username is inputted. I've changed my username authentication just for the time being to try and get this standard version correct before I change my username verification back. html Login template I want the password input to be visible to the user Views.py The prints return 'None' on the console urls.py Can anyone spot where I am going wrong or advise if this is a terrible way to create a custom login page on Django