Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django model foreign key: reference to composite key
I have a table named as Detail with several columns: columns: 'header_id' 'code_key' 'code_desc' 'header_id' and 'code_key' are composite key. So I set constraints = [ models.UniqueConstraint( fields = ['code_key', 'header_id'], name = 'XXXX' ) ] in the table's Meta. I have another table named Report which also contains column 'code_key'. I want this column to refer to the 'code_key' column in table Detail . However, error comes out saying: 'Detail.code_key' must be unique because it is referenced by a foreign key. HINT: Add unique=True to this field or add a UniqueConstraint (without condition) in the model Meta.constraints. Since I already set UniqueConstraint in table Detail, what else should I do now? Thanks for any help T___T -
Changing Boolean value after specific time
I am building a BlogApp and I am trying to set a Boolean Field to False after 10 minutes , so created a function in models.py to change the Boolean Value which are older than 10 minutes. But the function in models.py is not working, It is not changing the Boolean value after 10 minutes. import datetime from django.utils import timezone from datetime import timedelta class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') body = models.CharField(max_length=30,default='') date_added = models.DateTimeField(auto_now_add=True) is_old = models.BooleanField(default=False) #Function to change Boolean Value to False after 10 minutes def active(self): now = timezone.now() if date_added < timezone.now() - timedelta(minutes=10): is_bountied = False self.save() I am not using in views What have i tried ? I followed THIS question's Answers and created a celery task but it was not working, didn't show any errors. Than i tried :- @property def active(self): return self.date_added >timezone.now() - timedelta(minutes=10) def __init__(self): super().__init__() self.active = self.end_date > datetime.datetime.utcnow() BUT it also didn't update the field. It is still not changing or saving the field. Any help would be much Appreciated. Thank You in Advance. -
Django serve image authorization with JWT
I am trying to serve images from my Django server. I need these images to be secured with my user's JWT token. ie. If user GETs profile 1, and profile 1 has image ABC. Unless the user has access to Profile 1, they should not be able to navigate to BASE_URL/static/images/ABC.jpg and get an image. -
login error when I try to login the user. Django
Good evening community, I am building my first website and I am facing the following two problems when I try to logging the user: I can see the password as I write it. When I click submit I get a 404 because it sends me to the wrong URL: Request URL: http://127.0.0.1:8000/login_user/simple_investing/create_company.htm/ Here is my code: Forms.py: class UserForm(UserCreationForm): class Meta: model = User fields = ('username', 'email', 'password1', 'password2') class UserLogin(ModelForm): class Meta: model = User fields= ('username', 'password') Views.py: def login_page(request): messages.success(request, 'Account created successfully') form = UserLogin if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect('simple_investing/create_company.htm/') context = {'form' : form} return render(request, 'simple_investing/login.htm', context) HTHML: {% for message in messages %} <p>{{ message }}</p> {% endfor %} <p>Log in and start using our tools!</p> <form action= "" method='post'> {% csrf_token %} {% for field in form %} <p>{{field.label}}{{field}}</p> {% endfor %} <button type="submit" class="btn btn-success">Login User</button> </form> Any hints? -
Environment variables works on Django's server but not on Apache server
When I use the environment variable in Django's server, it works. SMTP_PASSWORD = os.environ["SMTP_PASSWORD"] However, when I run the same code on Apache, it doesn't. The code os.environ["..."] just doesn't work. I am using Windows 10, Python 3.9.5 and Django 3.2.4. Any idea what is happening? -
Create postgresql view in django
I want to use postgresql view to store intermediate result of queryset in django. Is there a good way to create a view in django? Below is the code of the flow I want! elements = Element.objects.filter(is_active=True, eventcardad__isnull=False) # save elements to database view # reuse the query results by using view -
How to create individual product page using Django?
I'm trying to create an individual page for each of my products. I found a solution online so I did this: models.py: #IMPORTS from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from multiselectfield import MultiSelectField import uuid class Product(models.Model): product_id=models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) product_title=models.CharField(max_length=100) product_price=models.FloatField(default=1.00) image_one = models.ImageField(upload_to='media', default='def.jpg') image_two = models.ImageField(upload_to='media', default='def.jpg') image_three = models.ImageField(upload_to='media', default='def.jpg') product_description = models.TextField() #Toys class Toy(Product): CATS = ( ("BT", "Boy Toys"), ("GT", "Girl toys"), ("BbyT", "Baby toys") ) Category=models.CharField(max_length=10, choices=CATS) views.py: class ProductList(ListView): model = Product def Productdetail(request,pk): product= Product.objects.get(id=id) context = {'product': product} return render(request, 'ecomm/product.html', context) . . . my urls.py: from django.urls import path from . import views from .views import ProductList, Productdetail urlpatterns = [ path('', views.home, name='ecomm-home'), path('products/', ProductList.as_view()), path('products/<int:pk>/', Productdetail, name='product_detail'), .... product_detail.html: {% extends "base.html" %} {% block content %} <h2>Product</h2> {{product.product_title}} {% endblock %} girls_toys.html: {% extends "ecomm/base.html" %} {% block content %} <style> .prod{ text-align:center; padding-left:50px; width:500px; display:block; float:left; padding-top:50px; } .header{ font-size:40px; font-family:serif; } </style> <center><h class="header"> Shop girl toys </h></center> <br> {% for t in toys %} {% if t.Category == 'GT' %} <div class="prod"> <a href="{% url 'product_detail' t.id %}"><img src="{{t.image_one.url}}" height="200px" width="250px"></a> … -
Is this the correct way to update existing data using formset?
I have the following code to update my database using formset for one part of the form. I am able to get a queryset and display it currently. But when i submit back, dd_form has the following error in my powershell []. Can anyone guide me on how to correct this? Thank you. def device_edit(request, pk): device = Device.objects.get(pk=pk) deviceDetail = DeviceDetail.objects.get(DD2DKEY=pk) deviceInterface = DeviceInterface.objects.filter(I2DKEY = pk) if request.method == 'POST': # Device_frm contains only hostname and ip address device_frm = DeviceForm2(request.POST) dd_form = DeviceDetailForm2(request.POST) di_formset = modelformset_factory(DeviceInterface, fields=('moduletype', 'firstportid', 'lastportid'), extra=1,max_num=3) di_form=di_formset(request.POST) device_frm.hostname = device.hostname device_frm.ipaddr = device.ipaddr if device_frm.is_valid(): Device.objects.filter(pk=pk).update(ipaddr=device_frm.cleaned_data['ipaddr']) if dd_form.is_valid(): DeviceDetail.objects.filter(DD2DKEY=pk).update(mgt_interface=dd_form.cleaned_data['mgt_interface'],subnetmask = dd_form.cleaned_data['subnetmask'],ssh_id = dd_form.cleaned_data['ssh_id'],ssh_pwd = dd_form.cleaned_data['ssh_pwd'],enable_secret = dd_form.cleaned_data['enable_secret'], dev_mod = dd_form.cleaned_data['dev_mod']) if di_form.is_valid(): for instances in deviceInterface: DeviceInterface.objects.filter(I2DKEY = pk).update(moduletype = di_form.cleaned_data['moduletype'], firstportid = di_form.cleaned_data['firstportid'], lastportid = di_form.cleaned_data['lastportid']) return redirect('/device/', {'device':Device.objects.all, 'devices':device}) else: print(di_form.errors) else: device_frm = DeviceForm2() dd_form = DeviceDetailForm2() di_form = DeviceInterfaceForm() return render(request, 'interface/device_edit.html',{'form': device_frm, 'dd_form': dd_form, 'di_form': di_form, 'devices':device, 'deviceDetail':deviceDetail, 'deviceInterface':deviceInterface }) -
How to hide SMTP Host name and password to Heroku hosted site Django
I made forgot password reset for my Django hosted Heroku app. I have been finding it difficult to hide my Gmail account, especially the password for production and security reasons but it couldn't be found. I hid it in the Heroku config var EMAIL_HOST_USER 'email address' EMAIL_HOST_PASSWORD 'email address password' but it was not still working. I also tried using config, but the .env file is not pushed to GitHub because it is hidden in .gitignore and Heroku can't access it. Is there any other way I can set this?? -
Django + Gunicorn + Nginx wont reload old static file
I have a site running with django > gunicorn > nginx combination. Here are my config files gunicorn.config #!/bin/bash # Name of the application NAME="mediadbin" DJANGODIR=/home/mediaroot/mediadbin/mediadbin NUM_WORKERS= $(( $(nproc) * 2 + 1 )) DJANGO_SETTINGS_MODULE=mediadbin.settings DJANGO_WSGI_MODULE=mediadbin.wsgi echo "Starting $NAME as `whoami`" cd $DJANGODIR ENV=new_django source /root/.virtualenvs/new_django/bin/activate exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --timeout 600 --name $NAME \ --workers &NUM_WORKERS \ --bind=127.0.0.1 \ --log-level=debug \ --log-file=- My site-enabled in nginx congif server { listen 80; server_name mediadbin.n-media.co.jp; client_max_body_size 500M; access_log /home/mediaroot/mediadbin/logs/nginx-access.log; error_log /home/mediaroot/mediadbin/logs/nginx-error.log; server_tokens off; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Real-IP $remote_addr; } location /static { alias /home/mediaroot/mediadbin/mediadbin/static; } location /media { alias /home/mediaroot/mediadbin/mediadbin/media; } include global404; } I have my static files in /home/mediaroot/mediadbin/mediadbin/main_app/static/main_app (as for development) and also collected in /home/mediaroot/mediadbin/mediadbin/static for deployment. Both folders contains the newest static files. Here is the problem: When I try to update existing static files: for example x.js or x.jpg which name already existed on the site before, the static files are not updated to the newest file. But when I change a name to something new <- something that doesn't existed on the page before, like y.jpg this files are … -
DRF Browserable API triggering other self.actions - which in turn is triggering irrelevant permissions resulting in KeyError
I have a DRF ViewSet that seems is triggering the "create" permission_class (IsListOwner below) when I simply want to retrieve a list view. urls.py router = DefaultRouter() router.register(r"list-items", ListItemViewSet, basename="list_item") views.py class ListItemViewSet(viewsets.ModelViewSet): queryset = ListItem.objects.all() def get_serializer_class(self): if self.action == "retrieve": return ListItemDetailSerializer if self.action == "create": return ListItemCreateSerializer return ListItemListSerializer def get_permissions(self): print("self.action", self.action) permission_classes = [AllowAny] if self.action == "list" or self.action == "retrieve": permission_classes = [AllowAny] elif ( self.action == "create" or self.action == "update" or self.action == "partial_update" or self.action == "destroy" ): permission_classes = [IsListItemOwner] return [permission() for permission in permission_classes] So that when I go to http://localhost:8000/api/v1/list-items/, I get the following error: web_1 | Internal Server Error: /api/v1/list-items/ web_1 | view.check_permissions(request) web_1 | File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 332, in check_permissions web_1 | if not permission.has_permission(request, self): web_1 | File "/project/app/permissions.py", line 60, in has_permission web_1 | return List.objects.get(pk=request.data["list_id"]).user == request.user web_1 | KeyError: 'list_id' web_1 | [27/Aug/2021 01:22:14] "GET /api/v1/list-items/ HTTP/1.1" 500 126003 Which points to the "IsListOwner" permission in my permissions.py file. (Even though my only explicit self.action is "list") I understand that this happens because DRF's browserable API initializes serializers for HTML forms. If I log the self.actions when I visit http://localhost:8000/api/v1/list-items/, … -
Django DRF: read_only_fields not working properly
I have the following models class Breed(models.Model):: name = models.CharField(max_length=200) class Pet(models.Model): owner = models.ForeignKey( "User", on_delete=models.CASCADE, ) name = models.CharField(max_length=200) breed = models.ForeignKey( "Breed", on_delete=models.CASCADE, ) I am trying to add few fileds for representation purpose. I dont want them to be included while create or update class PetSerializer(serializers.ModelSerializer): owner_email = serializers.CharField(source='owner.email') breed_name = serializers.CharField(source='breed.str') class Meta: model = Pet fields = "__all__" read_only_fields = ["breed_name","owner_email"] This is not working. I see the owner_email and breed_name in the HTMLform (the DRF api page) Where as class PetSerializer(serializers.ModelSerializer): owner_email = serializers.CharField(source='owner.email',read_only=True) breed_name = serializers.CharField(source='breed.str',read_only=True) class Meta: model = Pet fields = "__all__" This is working. I dont see them in the HTMLform Also i observed, if i use a model field directly in read_only_fields then it works. class PetSerializer(serializers.ModelSerializer): class Meta: model = Pet fields = "__all__" read_only_fields = ["name"] This will make all name not shown in update or create Why read_only_fields is not working properly -
TypeError: Object of type 'Product' is not JSON serializable
I am creating a store which can handle shopping without any registration, but i have some problems. I am storing data about products that user added to basket in django sessions and i am trying to create the similar system which would store a orders which user has done. This is the view which is executed after all payments are done: #I am not pasting the imports, all fine with them basket = Basket(request) orders = Orders(request) ### We are looping through the all items we are storing in basket to create for each one, single order for basketitem in basket: #This order is automatically created for admin, just ignore it, it's working fine order = Order.objects.create(user_id=user_id, product=basketitem['product'], size=basketitem['size'], quantity=basketitem['quantity'], full_name=full_name, address1=address1, address2=address2, postcode=postcode, town=town, country=country, total_paid=baskettotal, order_key=order_key, authenticated=False) #This is the main problem, this is trying to get a product from database "Product" comparing id from database to id that we store in basket in django sessions product = get_object_or_404( Product, id=int(basketitem['productid'])) orders.add(product=product, quantity=basketitem['quantity'], size=basketitem['size'], full_name=full_name, address1=address1, address2=address2, postcode=postcode, town=town, country=country, created=now.strftime("%d/%m/%Y %H:%M:%S")) And after this occurs error "Object of type 'Product' is not JSON serializable" Basket.py class Basket(): def __init__(self, request): self.session = request.session basket = self.session.get('bt') if … -
How do I pass a search query to a Django backend without storing the search results in a database?
My goal is to post a search query to a scraper function in a Django Rest Framework backend and return the results to the frontend without storing the results in a database. Currently, I can pass a search a search from the frontend to the backend, but the search results are stored in the database. Here are my Django Model and Views file that show how it is structured: models.py from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Data(models.Model): created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) data_1 = models.TextField(blank=True) data_2 = models.TextField(blank=True) search = models.CharField(max_length=255, default='') views.py from rest_framework import viewsets from apps.data.models import Data from apps.data.serializers import DataSerializer from apps.search.util import scraper class DataViewSet(viewsets.ModelViewSet): serializer_class = DataSerializer queryset = Data.objects.all() def perform_create(self, serializer): print(scraper(self.request.data['search'])) data_1 = scraper(self.request.data['search']) data_2 = scraper(self.request.data['search']) serializer.save(created_by=self.request.user, data_1 = data_1, data_2 = data_2) def get_queryset(self): return self.queryset.filter(created_by=self.request.user) How would I structure this Django backend application to pass a search query through my scraper without storing the result in the database? -
Serving Static on AWS - Django - Python
I have all of my static images served locally on my Django website project. I need them to be hosted on AWS for my DEBUG = False to work. I have followed many tutorials on how to do this and have had no luck. I have posted my code below for a last-ditch effort hoping that it is just something I have missed. I have my AWS bucket currently as public because that's what I have seen others doing. Any help is greatly appreciated. Thanks! setings.py AWS_ACCESS_KEY_ID = 'hidden for privacy' AWS_SECRET_ACCESS_KEY = 'hidden for privacy' AWS_STORAGE_BUCKET_NAME = 'hidden for privacy' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Caracas' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) #STATIC_ROOT = os.path.join(BASE_DIR, 'static') #MEDIA_URL = '/images/' #MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, '..','www','media') HTML {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link rel="shortcut icon" type="image/x-icon" href="{% static 'tab_icon.ico' %}"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{% static "css/side.css" %}"> <link rel="stylesheet" href="{% static "css/style.css" … -
Django uploads to the database, using the one to many relation
I'm a beginner in Django trying to give a customer his command. Please I need help on a views.py and models.py for my app, which is intended to submit a picture, several documents, and a name for a customer's information. These documents include certificates and some scans! -
Django Admin Panel - How to Create a DateTime String
For Django, I have this in my model: date = models.DateTimeField() the widget for this is AdminSplitDateTime in the Admin Panel. It then displays a graphical widget that shows the date and time, and allows you to pick today or now. What I want to do instead is just display the date time as a string, as such: Date: 08/26/2021 04:46:11 PM I just want to display the date/time as text rather than a fancy widget... I spent time trying to figure this out, but I am stuck. Do you guys have any idea on how to implement this in Django? Thanks! -
Is it possible to create two different submit button in one form in Django?
So I'm working on my Django project and ran into an issue. I have a custom ModelForm, with which I'm trying two different works. I'm trying to create two submit buttons for the form, one for normal submission, and the other for making changes to the input data and then submitting. For Example, let's say I have name field in my form. If the user clicks button A, name is submitted. But if the user clicks button B, I want the name field to be submitted as name@gmail.com. Is it possible to have two buttons working differently in one Django form? Thanks in advance. -
'django_1 | no port[s] to connect to' after running docker-compose up
I am new to docker, and have written a containerized django app, and react app. When I go to run docker-compose up I get a weird, perpetuating error that django has no port(s) to connect to. Running the server from the react and python side both work. Frontend dockerfile: COPY ./react_app/package.json . RUN apk add --no-cache --virtual .gyp \ python \ make \ g++ \ && npm install \ && apk del .gyp COPY ./react_app . ARG API_SERVER ENV REACT_APP_API_SERVER=${API_SERVER} RUN REACT_APP_API_SERVER=${API_SERVER} \ npm run build WORKDIR /usr/src/app RUN npm install -g serve COPY --from=builder /usr/src/app/build ./build Django Python backend Dockerfile WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt FROM python:3.7.9-slim-stretch RUN apt-get update && apt-get install -y --no-install-recommends netcat && \ apt-get autoremove -y && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* COPY --from=builder /usr/src/app/wheels /wheels COPY --from=builder /usr/src/app/requirements.txt . RUN pip install --no-cache /wheels/* WORKDIR /usr/src/app COPY ./entrypoint.sh /usr/src/app/entrypoint.sh COPY ./django_app . RUN chmod +x /usr/src/app/entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.sh"] and the nginx dockerfile FROM nginx:1.19.0-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d WORKDIR /usr/src/app Django Python backend Dockerfile WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY … -
Django Blog - I can't add new comment
Problem with a comment system in my Django project. When I add a new comment in 127.0.0.1:8000 or localhost:8000 the page just reloads and nothing happens. In "blog/views.py" in post_detail(request, year, month, day, slug): I guess there is something wrong at if request.method == 'POST': and then move on to else: comment_form = CommentForm() so that I can only see the page just reloads. However, I don't know how to fix it... This is a full code of my Django project. my github repository -
How to load django model rows in a list?
I have a django model that I am basically quering on keypress using ajax to find possible matches cause I am avoiding duplicated rows. Now my question is how can I copy all the rows from a django model and query on it rather than hitting the database everytime the user presses a key because I do not think this is a good idea and please correct me if I am wrong. What are the consequences of hitting a database on keypress? -
Unable to see error messages in registration template. Django
Good afternoon Community, I hope you are all well. I am building my first website and I have the following problem; when I try to create a new user, if the user enters the wrong data the template does not show the error. Any hints? Template: <form action= "" method='post'> {% csrf_token %} {% for field in form %} <p>{{field.label}}{{field}}</p> {% endfor %} <button type="submit" class="btn btn-success">Create User</button> Views.py: def register_page(request): form = UserForm if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('http://127.0.0.1:8000/login_user/') context = {'form' : form} return render(request, 'simple_investing/register.htm', context) Forms.py: class UserForm(UserCreationForm): class Meta: model = User fields = ('username', 'email', 'password1', 'password2') -
Sessions and user id django
I have a form that can be submitted by any user, anonymous included. I want to save the user id (can be randomly generated) into my database that's associated with their input. I want to keep track of which input came from the same/different user. Essentially, if I have a new session, I would generate a new user_id. However, if this is an old session, I would save into the database the old/same user_id. However, I am a total newbie to Django, so I'm not sure how to implement this. So, my database should look something like this where the input values from the same user has the same user_id. |id| user_id | Order | |1 | ---------------------------------- | -------------- | |2 | f205f606c6764a79a77e5495b9d740bc | 10 | |3 | f205f606c6764a79a77e5495b9d740bc | 5 | |4 | f205f606c6764a79a77e5495b9d740bc | 10 | |5 | f205f606c6764a79a77e5495b9d740bc | 3 | |6 | fee472e3b07c4f59834e22751d9d2d60 | 2 | |7 | fee472e3b07c4f59834e22751d9d2d60 | 6 | -
how to make custom creation method [Django models]
class Boat(models.Model): name = models.CharField(max_length=100) quantity = models.DecimalField(max_digits=8, decimal_places=2) fish_type = models.CharField(max_length=50, choices=FISH_TYPE) class Load(models.Model): boat = models.ForeignKey(Boat, on_delete=models.CASCADE) delivery_date = models.DateTimeField(auto_now_add=True) class OrderLoad(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) quantity = models.DecimalField(max_digits=8, decimal_places=2) fish_type = models.CharField(max_length=50, choices=FISH_TYPE) what I want to do is, when orderload instance created, it should reduce the quantity. -
Django Review / Optimization / Recommendations
I have been learning Django over the last couple of weeks and have been working on some projects as practice and to learn real world applications. I have pages (pictured below) that show a list of students, and teachers assigned to those students, on these pages I have a number of forms to do different things such as selecting students, creating new students, editing the student, assigning a teacher etc. I have attached my code below, this all works fine, but I can't help but feel like this is an extremely inefficient way of doing it. Keen to hear people's thoughts and feedback. I am always keen to learn! Students Screen (Ignore the red squares, just covering school names and logos): View.py @login_required(login_url='/login/') def students(request): if request.method == "POST": ## Checks which form is submitted, and actions the correct form if 'new_student' in request.POST: student_queryset = Student.objects.all().filter(creationuser__userschool=request.user.userschool) all_teachers_queryset = Teacher.objects.all().filter(creationuser__userschool=request.user.userschool) teacher_queryset = '' search_term = "" view_state = '' new_teacher_state = '' form = StudentForm(request.POST) if form.is_valid(): save_form = form.save(commit=False) save_form.creationuser = request.user save_form.save() save_form = StudentForm() if 'new_teacher' in request.POST: student_queryset = Student.objects.all().filter(creationuser__userschool=request.user.userschool) all_teachers_queryset = Teacher.objects.all().filter(creationuser__userschool=request.user.userschool) teacher_queryset = '' search_term = "" view_state = '' new_teacher_state = '' form …