Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I do drag and drop and save the state after drop on django
I newbie here, I try to do some projects on Django (sqlite). In this project, I try to do drag and drop on a webpage. The drag and drop card was made. Then I do with jquery and jquery ui but it doesn't work. I want to drag the card to the zone that I made from . In the have an of building blueprint. the card will drop in the room direction and they stay in the position after drop even though refresh. How should I do? I have been looking for its solutions but didn't find any help. Thank you -
Item does not decrease Django
Hello I want to make a feature, that if I click quantity decrease by 1 but it does not decrease and only returns HttpResponse. class CartView(TemplateView): template_name = "shop/cart.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['cart'] = Cart.objects.annotate( price=Sum(F('orderitem__item__price') * F('orderitem__quantity')) ).get(order_user= self.request.user) cart = context['cart'] cart.total = cart.price cart.save() context['order_items'] = OrderItem.objects.filter(cart=cart) return context def post(self, request): if 'minus' in request.POST: cart = Cart.objects.get(order_user=self.request.user) primary = request.POST.get('orderitem__id') item = OrderItem.objects.filter(id=primary, cart=cart) item.quantity = F('quantity') - 1 item.update() return HttpResponse("cart uptaded") -
Django form is not showing up
Here is my forms.py from django import forms class EmailForm(forms.Form): from_ = forms.EmailField(max_length=50) Here is my views.py from django.shortcuts import render from .forms import EmailForm def index(request): return render(request, "base.html") def emailSender(request): form = EmailForm(); return render(request, "base.html", {"form" : form}); And finally here is my html template <form id="form" method="post"> {% csrf_token %} {{ form }} <div class="form-outline mb-4"> <label class="form-label" for="from">From:</label> {{ form.from_ }} </div> Any of my {{ form }} does not work. When I check the inspect tab they both are not created so I think this isn't some css problems here. -
Why i get error when i try to create an article for a child user?
Here is the problem: When I try to create article for the user itself, it works. But when I try to create an article as the parent of the child user instead of the child user itself, I get a validation error. I am trying to make sure the parent is the authenticated user. How can I solve this issue? class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) username =models.CharField(max_length=40,unique=True,default='undefinedusername') parent = models.ForeignKey('self',on_delete=models.CASCADE,null=True, blank=True) class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles') caption = models.CharField(max_length=250) class ArticleCreateSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ('id','author','caption') def validate(self, attrs): attrs = super().validate(attrs) if attrs['author'].id != self.context['request'].user.pk: raise ValidationError('Unauthorized Request') elif attrs['author'].parent.id == self.context['request'].user.pk: return attrs elif (attrs.get('author').parent != None) and (attrs.get('parent').id != self.context['request'].user.pk): raise ValidationError('Unauthorized Request') return attrs -
Django pytest: can't test userpage detail
I have a detailed page of the author of the blog, which uses following urlpatterns urls.py from . import views from django.urls import path,include urlpatterns = [ path('all/', views.PostListView.as_view(), name='all'), path('<int:id>/',views.PostDetailView.as_view(), name='detail'), path('blogger/<username>/',views.userpage, name='userpage'), path('bloggers/', views.allblogers, name='allauthors'), ] main urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('app.urls')), path('account/', include('accounts.urls')) ] When using this test function, an error occurs: WARNING django.request:log.py:224 Not Found: /blog/1/ ========================== short test summary info ========================== FAILED app/tests.py::test_user_detail - assert 404 == 200 tests.py @pytest.mark.django_db def test_user_detail(client, django_user_model): user = django_user_model.objects.create( username='someone', password='password' ) url = reverse('detail', kwargs={'id': user.id}) response = client.get(url) assert response.status_code == 200 assert 'someone' in response.content -
Django - Table-like form for updating multiple relationships between multiple objects at the same time
Context Say I have two Orders (O1, O2) and three Tasks that can be done multiple times (T1, T2, T3). The table below shows how many repetitions of each task have been ordered: so e.g. order O1 consists of 2 reps of T1 and 8 reps of T2. I have all year to do these repetitions, but I want to control how many were done each month. Say these are the repetitions that I did: so in the month of September I only did 4 repetitions of task 2 and assigned 1 to order 1 and 3 to order 3 in October, I did 2 reps of T1 for O1, 2 reps of T2 for O1, and 1 rep of T3 for O2 and so on for November I am currently storing each of these numbers in the second table as a RepetitionLog object (with fields task, order, month, and reps) that looks like this: class RepetitionLog(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE) order = models.ForeignKey(Order, on_delete=models.CASCADE) reps = models.DecimalField('Geleistete Wiederholungen', max_digits=9, decimal_places=2) month = models.DateField('Monat') Question My main question is what's the best way to generate an interactive table similar to the second table above and use it to create/update several … -
Forms not showing up when using a registration app
I'm using this app to register the user of my website https://github.com/egorsmkv/simple-django-login-and-register. The problem is that no metter what I do my form are not visible (they were when I did not use this registration app and the code worked just fine). This is my code: model class UserBio(models.Model): name = models.CharField(max_length=120) age = models.CharField(max_length=2) phone = models.CharField(max_length=10) height = models.CharField(max_length=3) weight = models.CharField(max_length=3) form class UserBio(forms.ModelForm): class Meta: model = UserBio fields = (name', 'age', 'phone', 'height', 'weight') views def add_bio(request): submitted = False if request.method == "POST": info_form = UserBio(request.POST) if info_form.is_valid(): info_form.save() return HttpResponseRedirect('add_information?submitted=True') else: info_form = UserBio() if 'submitted' in request.GET: submitted = True return render(request, 'accounts/profile/add_information.html', {'form': info_form, 'submitted':submitted}) urls urlpatterns = [ path('add/information', views.add_information, name='add_information'), ] html {% extends 'layouts/default/base.html' %} {% block title %} Add info {% endblock %} {% load i18n %} {% block content %} <h4>{% trans 'Add Info' %}</h4> {% if submitted %} Sumitted correctly {% else %} <form method="post"> {% csrf_token %} {{ info_form.as_p }} </form> </div> <br/> </body> {% endif %} {% endblock %} Any help would be very apprecieted! -
How to sent POST request to Django from external app
I am trying to sent post request from python script which works on Windows machine. Here is my views.py Django def check(request): if 'login/password' in request.POST: checkdata(request.POST) else: message = '404' return HttpResponse(message) And here is my post.py param_tuples = [('login', 'value1'), ('pass', 'value2')] response = requests.post('http://127.0.0.1:8000/check', data=param_tuples) The problem is that Django reject my request because i dont have csrf token Forbidden (CSRF cookie not set.): /check How can i get csrf token in order to sent request to Django server externally ? -
How to serve non ascii file name with django and apache using xsendfile
I wanted to serve protected contents in django,so I tried to set xsendfile in both django and apache. It works for ascii file names, but when I tried with non-ascii file name the apache server reponds with 404. Do any one know whats going on here? Django: def media_xsendfile_pdf(request): file = Media.objects.last() response = HttpResponse() response['Content-Type'] = 'application/pdf' response['X-Sendfile']= smart_str(f"{settings.BASE_DIR}{file.file.url}") return response Apache: AllowEncodedSlashes On XSendFile On XsendFilePath /path-to-the-protected-resource Blockquote -
Get Many to many fileds in django model with together model fields
I have two models; class userPageAuths(models.Model): enName = models.CharField(max_length=30) trName = models.CharField(max_length=30) def __str__(self): return self.enName class userPages(models.Model): enName = models.CharField(max_length=30) trName = models.CharField(max_length=30) parent_id = models.IntegerField(blank=True, null=True) user_page_auths = models.ManyToManyField(userPageAuths, related_name="page_auth_list", blank=True) def __str__(self): return self.enName First model data is in my database; second model data is; and this data is for many to many field; I want to get all data like this; [ { "id": 1, "enName": "x", "trName": "x", "parent_id": null }, { "id": 2, "enName": "y", "trName": "y", "parent_id": null }, { "id": 3, "enName": "z", "trName": "z", "parent_id": 2 }, { "id": 1, "enName": "a", "trName": "a", "parent_id": 3 // this userpages_id which connected manytomany relation and ı want to get this as a parent_id }, { "id": 2, "enName": "b", "trName": "b", "parent_id": 3 }, { "id": 3, "enName": "c", "trName": "c", "parent_id": 3 }, ] I use this serailizers; class pagesSerializer(serializers.ModelSerializer): class Meta: model = userPages fields = ('id', 'enName', 'trName', 'parent_id') and this is my method; class pagesListView(ListAPIView): serializer_class = pagesSerializer def get_queryset(self): return list(itertools.chain(userPages.objects.all(), userPageAuths.objects.all())) ı got data like this; [ { "id": 1, "enName": "x", "trName": "x", "parent_id": null }, { "id": 2, "enName": "y", "trName": "y", "parent_id": null … -
Define component schema with drf-spectacular for django API
I am using drf-spectacular to generate an OpenAPI schema for django. As I am not using serializers, I am defining everything in the extend_schema decorator. Now my question is, if it is possible to manually define a component schema. Here is an example what my api view looks like: from rest_framework.decorators import api_view from drf_spectacular.utils import (extend_schema, OpenApiExample) from drf_spectacular.types import OpenApiTypes from rest_framework.response import Response @extend_schema( examples=[OpenApiExample( value=[ {'title': 'A title'}, {'title': 'Another title'}, ], )], responses={ 200: OpenApiTypes.OBJECT } ) @api_view(['GET']) def list_articles(request): return Response([{'title': 'Test1'}, {'title': 'Test2'}]) and the corresponding component is shown as empty (e.g. in swagger): Here is the definition in the documentation but I cannot figure out how to achieve it with drf-spectacular. -
How to use django signal inside async function?
I have the following async function that notify users when the DB changed. I tried to skip using async function and use normal function instead but I can't do that. I must use django signals inside the async function and return the signal from inside it. async def liveSignals_generator(obj, info): while True: @receiver(post_save, models.Post) def do_stuff(instence): print('test=======') yield instence.id problem when I use the receiver inside async function it act like it does not exist at all. Also, is it possible to use await inside liveSignals_generator before do_stuff? Goal any possible approach to to return/yield the new signals data from inside the liveSignals_generator. Maybe we can create an external function that connect these .... -
graphene-django: Why ENUMS in grahene-django returns the value instead of key?
When i create candidate, It return the value of the enum instead of the key. e.g. When i select "FRESH_AND_LOOKING" in mutation to create candidate it returns"Unemployed. Looking for job". I need the actual key of enum instead of value This is model class Candidate(models.Model): class JobStatus(models.TextChoices): FRESH_AND_LOOKING = "Unemployed. Looking for job" WORKING_BUT_LOOKING = "Working but looking for new opportunities" NOT_LOOKING = "Not looking for job" date_of_birth = models.DateField() address = models.CharField(max_length=300) job_status = models.CharField(max_length=100, choices=JobStatus.choices) This is enums class JobStatusEnum(graphene.Enum): FRESH_AND_LOOKING = "Unemployed. Looking for job" WORKING_BUT_LOOKING = "Working but looking for new opportunities" NOT_LOOKING = "Not looking for job" This is arguments class CandidateInput(graphene.InputObjectType): date_of_birth = graphene.Date() address = graphene.String(required=False) job_status = graphene.Field(JobStatusEnum, required=False) This is type class CandidateType(DjangoObjectType): class Meta: model = Candidate fields = "__all__" This is mutation class CreateCandidate(graphene.Mutation): _candidate = graphene.Field(CandidateType) class Arguments: input = CandidateInput(required=True) @classmethod def mutate(cls, root, info, input=None): candidate = Candidate.objects.create(**input) return CreateCandidate(_candidate=candidate) -
Sending the response of an API from one server, through API of another server
Below is the response from a endpoint of a server(server1). I need to build an API and send the same response through different server(server2). Reason being I cannot expose anything related to server1. Problem is,how to point the doc_url file links which are coming from server1 to server2. I'm trying to do this using Django Rest Framework CBV. "data": [ { "issue_date": "2019-06-13", "attachments": [ { "doc_name": "three.pdf", "doc_url": "http://server_url/_uploads/person/39/three.pdf } ] }, { "issue_date": "2019-06-13", "attachments": [ { "doc_name": "two.pdf", "doc_url": "http://server_url/_uploads/person/39/two.pdf" }, { "doc_name": "one.jpg", "doc_url": "http://server_url/_uploads/person/39/one.jpg" }, ] } ] -
TypeError at / 'NoneType' object is not iterable Request Method: GET Request URL: http://localhost:8000/
When I run my Django application I get this error TypeError at / 'NoneType' object is not iterable Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.2.8 Exception Type: TypeError Exception Value: 'NoneType' object is not iterable , line 32, in user_login_request return render(request=request, template_name="auth/tg_login.html", context=context) In my views.py this is what I have def user_login_request(request): print('calling user_login_request') if request.method == "POST": print('calling user_login_request POST') # a form bound to the POST data login_form = TGArchiveUserLoginForm(request.POST) if login_form.is_valid(): # print('calling login_form.is_valid()') username = login_form.cleaned_data.get("user_login_name") password = login_form.cleaned_data.get("user_login_password") user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # print("You have logged in as " + request.user.username) messages.info(request, f"You are now logged in as {username}.") return redirect(reverse('members:dashboard')) else: messages.error(request, "Invalid username or password.") return redirect('/') else: messages.error(request, "Invalid username or password.") context = { 'user_login_form': TGArchiveUserLoginForm() } return render(request=request, template_name="auth/tg_login.html", context=context) I have changed the template name and send a blank context to the template and still get the same error code. -
run daphne with fabric without blocking the terminal
I installed Daphne on my Django app and it works fine. But when I run Daphne from fabric, fabric does not return to the line on the termial. I would like to run daphne and not be blocked by fabric. i have this to : I have to do a ctrl c to return to the line but i want it to do it automatically And i would like to have this after start : here is the fabric code : def _start(c, server="dev", con=None): """start asgi server""" con = con if con else get_con(server, user=DEFAULT_WEB_USER, enrich=True) con.run("daphne -p 8000 myproject.asgi:application") -
Django - Serialized model of type User is not JSON serializable
I'm currently trying to find out how setup a API for my app using the django rest framework. Currently I have the following two files: serializers.py: from rest_framework import serializers, permissions from App_Accounts.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('user',) views.py from rest_framework import permissions from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response @api_view(['GET']) @permission_classes((permissions.AllowAny,)) def current_user(request): user = request.user return Response({ 'user': user, }) When I open: http://localhost/api/current_user/ it just get the following error returned at my console: File "/usr/local/lib/python3.9/json/encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type User is not JSON serializable I don't know how important it is but I'm using a custom User model -
Too long select if using JSON fields
There are two connected models from django.contrib.postgres.indexes import GinIndex from django.db import models class Model(models.Model): name = models.CharField(max_length=128, db_index=True) attributes = models.JSONField(null=True) class Meta: db_table = 'models' indexes = [GinIndex(fields=['attributes'])] class Offer(models.Model): price = models.DecimalField(decimal_places=2, max_digits=8, db_index=True) quantity = models.SmallIntegerField() model = models.ForeignKey('Model', related_name='offers', on_delete=models.CASCADE) class Meta: db_table = 'offers' indexes = [GinIndex(fields=['attributes'])] When I make queries using several offer attributes, it takes to many time. What wrong with this code? I have about 5000 models and about 300 000 offers in my db. Query takes about 20 seconds. If I use only one attribute from offer it's ok. result = ( Model.objects .prefetch_related('offers') .filter(attributes__param1='value1') .filter(attributes__param2=False) .filter(offers__attributes__width='255') .filter(offers__attributes__height='55') .filter(offers__attributes__diameter='16') ) -
ModuleNotFoundError: No module named 'myproject.settings'
So, i try to upload my python django website to PYTHONANYWHERE, and when i try to run the website is error they say Something Went Wrong, so i try to look at the logs, and that logs say this 2021-10-07 12:11:37,339: ModuleNotFoundError: No module named 'myproject.settings' 2021-10-07 12:11:37,339: File "/var/www/webtest_pythonanywhere_com_wsgi.py", line 29, in <module> 2021-10-07 12:11:37,340: application = get_wsgi_application() 2021-10-07 12:11:37,340: 2021-10-07 12:11:37,340: File "/home/webtest/.virtualenvs/mynenv/lib/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2021-10-07 12:11:37,340: django.setup(set_prefix=False) 2021-10-07 12:11:37,340: 2021-10-07 12:11:37,340: File "/home/webtest/.virtualenvs/mynenv/lib/python3.9/site-packages/django/__init__.py", line 19, in setup 2021-10-07 12:11:37,340: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2021-10-07 12:11:37,340: 2021-10-07 12:11:37,340: File "/home/webtest/.virtualenvs/mynenv/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ 2021-10-07 12:11:37,341: self._setup(name) 2021-10-07 12:11:37,341: 2021-10-07 12:11:37,341: File "/home/webtest/.virtualenvs/mynenv/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup 2021-10-07 12:11:37,341: self._wrapped = Settings(settings_module) 2021-10-07 12:11:37,341: 2021-10-07 12:11:37,341: File "/home/webtest/.virtualenvs/mynenv/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ 2021-10-07 12:11:37,341: mod = importlib.import_module(self.SETTINGS_MODULE) 2021-10-07 12:11:37,342: *************************************************** 2021-10-07 12:11:37,342: If you're seeing an import error and don't know why, 2021-10-07 12:11:37,342: we have a dedicated help page to help you debug: 2021-10-07 12:11:37,342: https://help.pythonanywhere.com/pages/DebuggingImportError/ 2021-10-07 12:11:37,342: *************************************************** And,i research in google and youtube and i get this way to solve the error, and i try that way. So i run this python -m venv myproject command in the root directory, with mynenv running,still not working … -
Not Found: /callback/ Error. i want my payment_reponse function to update order.paid to True, save to database and return a done.html page
#orders.view# The payment completes successfully. but instead of setting order.pad=True, saving and redirecting to the orders:done and orders:canceled it returns "Not Found: /callback/" error from django.shortcuts import render, redirect from django.urls import reverse from cart.cart import Cart from .models import OrderItem, Order from .forms import OrderCreateForm from .tasks import order_created from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from django.shortcuts import get_object_or_404 from django.views.decorators.http import require_http_methods from django.template import loader from decimal import Decimal import environ import random import math import requests env = environ.Env() environ.Env.read_env() def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) total_cost = cart.get_total_price() if form.is_valid(): name = form.cleaned_data['last_name'] email = form.cleaned_data['email'] amount = f'{total_cost:.2f}', phone = form.cleaned_data['phone'] order = form.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) # clear the cart cart.clear() # launch asynchronous task order_created.delay(order.id) request.session['order_id'] = order.id return redirect(str(process_payment(name, email, amount, phone))) else: form = OrderCreateForm() return render(request, 'orders/order/create.html', {'cart': cart, 'form': form}) def process_payment(name, email, amount, phone): auth_token = env('SECRET_KEY') hed = {'Authorization': 'Bearer ' + auth_token} data = { "tx_ref": ''+str(math.floor(1000000 + random.random()*9000000)), "amount": amount, "currency": "NGN", "redirect_url": "http://localhost:8000/callback", "payment_options": "card", "meta": { "consumer_id": 23, "consumer_mac": "92a3-912ba-1192a" }, "customer": { "email": email, "phonenumber": phone, "name": name … -
Post non-persisting model with dictionary attribute with REST Framework in Django
I want to make a post request where I request an object containing free text, process it, and respond with another object containing a collection with the corrections per word. In Django, every model.Models class gets a DB table, but I do not want to store either the request or the response. I just want to use the server to compute the spell checker. The class I want to request is the following: class FreeText(models.Model): text = models.TextField() class Meta: db_table="free_text" Even though here I use a models.Model, It may be a regular class. The class I want to respond with is the following: class SpellCheckedText(): def __init__(self, text: str, spell_dict: dict): self.text = text self.spell_dict = spell_dict To serialize it, I tried something like the following, but I do not see any field type fitting of a dictionary. class CommentSerializer(serializers.Serializer): text = serializers.TextField() spell_dict = serializers.... How should I build the serializer and the post request? -
Django_Crontab does not seem to run
hoping I can get some guidance on django crontab. I have the following set up: in settings.py: INSTALLED_APPS = [ 'django_crontab', ........ ] #other settings not related to crontab CRONJOBS = [ ('*/1 * * * * ', 'my_app.cron.cronjob') ] in my my_app/cron.py(for now I have a model with the name 'name'): def cronjob(): total_ref = models.Count.objects.get(name='name') total_ref.total += 1 total_ref.save() return() in my my_app/models.py: class Count(models.Model): name = models.CharField(max_length=100, blank=True, null=True) total = models.IntegerField(blank=True, null=True) def __str__(self): return self.name When i run the following: $ python manage.py crontab add crontab: no crontab for user adding cronjob: (26ea74b6ee863259e86bcab90f96ec1a) -> ('*/1 * * * * ', 'ms_app.cron.switch_count') And when i check to see if it is in my crontab $ crontab -l */1 * * * * /Path_to_env/bin/python /Path_to_my_app/my_project/manage.py crontab run 26ea74b6ee863259e86bcab90f96ec1a # django-cronjobs for myl_project i am running python 3.8.2 with Django 3.2.5 and django_crontab 0.7.1 With all of this checked I still do not get any changes when I go and check my model entry (total) -
Storing likes and follows informations in different models gives me error: most likely due to a circular import
I have two models: Product and User class Product(models.Model): #here are information fields about Product likes = models.ManyToManyField( User, related_name="product_likes", blank=True) object = models.Manager() productobjects = ProductObjects() def __str__(self): return self.name class User(AbstractBaseUser, PermissionsMixin): #here are information fields about User followed = models.ManyToManyField( Product, related_name="followed_products", blank=True) objects = CustomAccountManager() object = models.Manager() def __str__(self): return self.email Inside Product I need to have a likes filed ManyToMany which store which users liked the product. Inside User I need to have followed field ManyToMany which store which products the user follow. I have an error: cannot import name 'Product' from partially initialized module 'product.models' (most likely due to a circular import). How can I fix it? Or maybe can I do this differently? The problem is that inside product.models I import: from users.models import User and inside users.models I import: from product.models import Product. (I am using the likes filed just to GET number of likes, but from followed I need to GET all the products that specified user follow and informations about them) -
How can I install djangoshop-sendcloud?
I'm trying to install djangoshop-sendcloud package by using pip. But following error occure. UnicodeDecodeError: 'cp950' codec can't decode byte 0xe2 in position 529: illega l multibyte sequence How can I fix this error and install package. -
django UniqueConstraint error in email field (sendgrid verification email)
I am tryting to implement sendgrid email verification to my django project. I have been following https://www.twilio.com/blog/send-dynamic-emails-python-twilio-sendgrid tutorial. I have models and views setup accordingly however, I am facing UniqueConstraint error when trying to use the same email address twice (although my model has Email Field set to unique = True. My error: Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: newsletter_newsletteruser.email My models.py: from django.db import models class NewsletterUser (models.Model): email= models.EmailField(unique=True) date_added = models.DateTimeField(auto_now_add=True) conf_num = models.CharField(max_length=15) confirmed = models.BooleanField(default=False) def __str__(self): return self.email + " (" + ("not " if not self.confirmed else "") + "confirmed)" my admin.py from .models import NewsletterUser, MailMessage # Register your models here. class NewsletterAdmin(admin.ModelAdmin): list_display = ('email','date_added','conf_num', 'confirmed') admin.site.register(NewsletterUser, NewsletterAdmin) admin.site.register(MailMessage) my views.py from django.db.models.fields import EmailField from django.shortcuts import render, redirect from sendgrid.helpers.mail.bcc_email import Bcc from django.http import HttpResponse from .forms import NewsletterUserForm, MailMessageForm from django.contrib import messages from django.contrib.auth.decorators import login_required import os from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, Email, Content, To from .models import NewsletterUser from django import forms import pandas as pd from django.shortcuts import render from django.http import HttpResponse from django.conf import settings from django.views.decorators.csrf import csrf_exempt import random from sendgrid import SendGridAPIClient # …