Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save contents of template html page to a list in Djano web application?
I am working on development of a web application in Django. I don't have much experience in it. In the html template page(e.g. homepage.html) after a button click, an action takes place and a relevant text is displayed. It is shown under "notes" id as: <div id="notes"></div><br> Text changes to different button clicks and different text is displayed under "notes" id. **I wanted to be able to save the contents as a list of strings/dictionaries and append the texts each time a new button is pressed. Or else update the last added entry in the list (similar to python or C++ coding) I learnt that we can carry out some codes using <script> tag but I had the assumption that such scripts are only for client-side and not server-side. I need the list on the server-side for further processes in the web app (or downloading the the list or ac**. Please suggest what should be done. I've been stuck at this problem for a long time. Thanks very much! -
Apache2 not using WSGI with HTTPS
I had been running my django app on top of a basic html website in an Apache2 webserver. mysite.com is the basic html site, while django was pointed at mysite.com/app using WSGI alias in the apache2 site config. It worked perfectly fine until I set up HTTPS with Certbot. Even after updating the site config, it no longer works. Whenever I try to go to mysite.com/app the error log states it tried to access var/www/html/app instead of var/www/mydjangoapp as it has previously done without issue. According to the log, WSGI does start successfully and runs several python processes, but if we go to the url, we get a 404. Here's my config which is located in a single file mysite.conf and enabled: <VirtualHost *:80> ServerName mysite.com Alias /static /var/www/myapp/static <Directory /var/www/myapp/static> Require all granted </Directory> <Directory /var/www/myapp/myapp> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myapp python-path=/var/www/myapp python-home=/var/www/djangoenv WSGIProcessGroup myapp WSGIScriptAlias /myapp /var/www/myapp/myapp/wsgi.py RewriteEngine on RewriteCond %{SERVER_NAME} !^443$ RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L] </VirtualHost> <VirtualHost *:443> ServerName mysite.com Alias /static /var/www/myapp/static <Directory /var/www/myapp/static> Require all granted </Directory> <Directory /var/www/myapp/myapp> <Files wsgi.py> Require all granted </Files> </Directory> #WSGIDaemonProcess myapp python-path=/var/www/myapp python-home=/var/www/djangoenv WSGIProcessGroup myapp WSGIScriptAlias /myapp /var/www/myapp/myapp/wsgi.py SSLEngine on SSLCertificateFile /etc/letsencrypt/live/mysite.pem SSLCertificateKeyFile /etc/letsencrypt/live/mysite.pem … -
How can I make a list of data show as a dropdown in DjangoAdmin?
I have a column in Django Admin, that is not a field on the table model. The column shows a list of data. I would like this column to be a dropdown, but it is currently just showing as text. It looks like I can use choices to force this to be a dropdown, but the options in the dropdown are dynamic, so choices doesn't seem to be a good fit here. Here is my method defining the column: def my_method: collection = list(MyModel.objects.values_list('name', flat=True)) return mark_safe(collection) How can I make a list of data show as a dropdown in DjangoAdmin? Sorry if this is too vague - I am new to Django and DjangoAdmin, so not sure what kind of information is necessary. -
Django: Setting def __str__ to a Related Model
Objective: I am trying to set the __str__ of a model to the name of a related model. The Profile model has a __str__ that returns "last name, first name" of the user. I would like the Inspector to return something similar with their inspector_number. Currently: The __str__ is returning "users.Profile.None 12345" instead of the desired "Doe, John 12345". This is one of my first times using related_name for a model and I seem to be missing something. Model.py class Profile(BaseModel): user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True, blank=True) inspector = models.ForeignKey(Inspector, on_delete=models.SET_NULL, null=True, blank=True, related_name="inspector_profile") def __str__(self): return self.user.last_name + ", " + self.user.first_name class Inspector(BaseModel): ... inspector_number = models.CharField(max_length=19, unique=True, editable=False, default=get_inspector_number) def __str__(self): ret = str(self.inspector_profile) + " " + str(self.inspector_number) return ret -
Django: how to make a get param or 404 function?
I want my endpoints to throw a 404 status code WITH a message like "parameter foo not found" if the request is missing a required field. Since i have too many endpoints, adding 3 lines of code (try, except, return) is not a happy solution for me. That's why i want to make a function similar to get_object_or_404 from django.shortcuts, where just using the function, the request returns 404 instead of just raising an exception and crashing the server. Taking a look to the get_object_or_404 function, i note that it does raise Http404 and this does work, but it always returns "detail": "Not Found" ignoring any parameter i pass to the exception raising code. Here's what i did: class ParamNotFound(Exception): def __init__(self, param_name): self.param_name = param_name self.status_code = 404 def __str__(self) -> str: return f"Param {self.param_name} not found" def get_body_param_or_404(params, param_name: str): param = params.get(param_name, None) if param is None: raise ParamNotFound(f"param_name {param_name} not found") return param But this does only raise a exception and crash the server if i dont explicitly catch it. Is there a clean and short way to do this? -
Users to see only their objects in Django
So I have an application where users can create their own Companies. But what I want in the view is for them to see only their entries on the view. I have seen similar questions on this platform but they don't work as expected. Below is my code. Models.Py from django.contrib.auth.models import User class Company (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) company_name = models.CharField(max_length=100, null=True) mailing_address = models.CharField(max_length=100, null=True) physical_address = models.CharField(max_length=100, null=True) class Meta: verbose_name_plural = "Companies" def __str__(self): return self.company_name views.py @login_required(login_url='login') def company (request): all_companies = Company.objects.filter(user=request.user) count= Company.objects.all().count() context = {'all_companies': all_companies, 'count': count} return render(request, 'company/company.html', context) forms.py class CompanyForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CompanyForm, self).__init__(*args, **kwargs) self.fields['company_name'].widget.attrs = {'class': 'input',} self.fields['date_created'].widget.attrs = {'class': 'input',} self.fields['mailing_address'].widget.attrs = {'class': 'input',} self.fields['physical_address'].widget.attrs = {'class': 'input',} class Meta: model = Company fields = ('company_name', 'date_created', 'mailing_address', 'physical_address',) The so largely this works to ensure that every user only sees the company they have created. However, I can successfully create the companies from the admin side but a glaring issue appears. I have to manually select users from the form field = users in the admin form as shown in the picture below, to be able to create and … -
IntegrityError at /signup UNIQUE constraint failed: auth_user.username
IntegrityError at /signup UNIQUE constraint failed: auth_user.username Request Method: POST Request URL: http://127.0.0.1:8000/signup Django Version: 4.0.3 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: auth_user.username Exception Location: C:\msys64\mingw64\lib\python3.9\site-packages\django\db\backends\sqlite3\base.py, line 477, in execute Python Executable: C:\msys64\mingw64\bin\python.exe Python Version: 3.9.10 from http.client import HTTPResponse from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib import messages from django.shortcuts import redirect # Create your views here. def home(request): return render(request, "authentication/index.html") return HttpResponse("Test") def signup(request): if request.method == "POST": username = request.POST.get('username') fname = request.POST.get('fname') lname = request.POST.get('lname') email = request.POST.get('email') password = request.POST.get('password') password2 = request.POST.get('passowrd2') myuser = User.objects.create_user(username, email, password) myuser.first_name = fname myuser.last_name = lname myuser.save() messages.success(request, "Your Account Has Been Created.") return redirect('signin') return render(request, "authentication/signup.html") def signin(request): return render(request, "authentication/signin.html") def signout(request): pass -
Python regex specific pattern on the whole string
I wondering to know how I can find the below characters in the string. Target: Finding "1": { in the whole string The string is : "1": {"nodename": "G00L", "nodeSerial": "EZ00kksd000", "nodeIP": "100.000.000.000", "inventoryString": "{\"sh5\": {\"sl0\": \"\", \"sl1\": \"2|EZ1517A786|32EC2|8DG62635AAAA01|None\", \"sl9\": \"4|EZ1535A02880|11QPA4|8DG60349AAAC02|None\", \"sl0\": \"6|EZ170520014|WTOCM-F|8DG613788AAAB01|{~OCM~: None}\", \"sl8\": \"44|EZ1530A2788|AHPHG|8DG59245AAAB04|None\", \"sl18\": \"12|RT184905823|32EC2|8DG62635AANE05|None\", \"sl36\": \"11|LBALLU-YP15250047C|16DC65|3KC49010AAAB01|None\", \"sl37\": \"21|EZ1645A2184|16FAN2|3KC48990AAAD02|None\", \"sl40\": \"22|EZ1645A369912|16UP2|3KC48980AAAC01|None\"}}", "NodeOwner": "kk", "NodeSWVer": "0000PSSECX-00.0-00", "JiraOwner": "gggg", "LastJiraRun": "0000-00-00 00:00:00", "LastUpdated": "2022-03-08 10:29:03"}, -
Tastypie Resource post request not completing successfully
I am trying to create tastypie resurce to post the timezone and currency in DB table. I am getting this error response: error: "The 'timezone' field has no data and doesn't allow a default or null value." My Django Models: class Currency(models.Model): currency = models.CharField(max_length=200) iso = models.CharField(max_length=3, unique=True) created = models.DateTimeField(auto_now=True, db_index=True) updated = models.DateTimeField(auto_now=True, db_index=True) active = models.BooleanField(db_index=True, default=False) class Meta: db_table = 'currency' class Timezone(models.Model): timezone = models.CharField(max_length=200, unique=True) display_name = models.CharField(max_length=200) offset = models.DecimalField(max_digits=8, decimal_places=4) created = models.DateTimeField(auto_now=True, db_index=True) updated = models.DateTimeField(auto_now=True, db_index=True) class Meta: db_table = 'timezone' class Account(models.Model): timezone = models.ForeignKey(Timezone, on_delete=models.PROTECT) currency = models.ForeignKey(Currency, on_delete=models.PROTECT) country_code = models.CharField(default=120) created = models.DateTimeField(auto_now=True, db_index=True) updated = models.DateTimeField(auto_now=True, db_index=True) class Meta: db_table = 'account' And here is my Tastypie resources: lass TimezoneResource(ModelResource): class Meta(CommonMeta): queryset = Timezone.objects.all() resource_name = 'timezone' allowed_methods = ['get', 'post', 'put', 'patch', 'delete'] excludes = ['created', 'updated'] filtering = { 'timezone':ALL, } class CurrencyResource(ModelResource): class Meta(CommonMeta): queryset = Currency.objects.all() resource_name = 'currency' allowed_methods = ['get', 'post', 'put', 'patch', 'delete'] excludes = ['created', 'updated'] filtering = { 'currency':ALL, } class ManageTimezoneAndCurrency(ModelResource): timezone = fields.ForeignKey(TimezoneResource, 'timezone', full=True) currency = fields.ForeignKey(CurrencyResource, 'currency', full=True) class Meta(CommonMeta): queryset = Account.objects.all() always_return_data = True resource_name = 'manage-timezone-currency' allowed_methods … -
Moving Images and Data from Gallery 3, a php app, to a new Django web site
Just curious if anyone has ported their Gallery 3 data (images, comments, tags, etc) (https://galleryrevival.com, http://galleryproject.org/) to a Django photo gallery app. Just looking for pointers or gotcheas as I run down this rabbit hole... Gallery 3 is an old php application. I am not looking to create a Django version of Gallery 3, as I don't speak php and the code is getting a little long in the tooth at this point. I just want to import the images and metadata to a new Django photo gallery. Also, looking for recommendations for a simple Django photo gallery that has a way to import existing photos and metadata. Thanks! -
SQL Server String Data Types with Django
I am using Django with DRF to host a production API with SQL Server as our backend. We do not require Unicode data in any of our char/varchar usage, but when I capture the TSQL being compiled by Django, every string value being sent to SQL is defaulting to nvarchar. Are there any changes to settings.py for my Django project to force the use of UTF-8 when communicating with the database? I also see that Microsoft let's you set your database's collation level, but none of the UTF-8 options translate to my needs directly. -
How to obtain a list of all distinct first letters of given field
Let's say I have this Person class that consist of last_name string field. I would like to display links of all first letters of names existing in db. So for example: A B D E... when there's Adams, Brown, Douglas, Evans and no one that last_name starts with C. Of course view is not a problem here as I want to prepare all of this on backend. So the question is how to write good model's or view's function that will provide this. I would like it to be DB-independent, however tricks for any particular DB would be a bonus. Also, I would like this to be quite well optimized in terms of speed because it could be a lot of names. It should be less naive than this most simple algorithm: Get all people Create set (because of the uniqueness of elements) of the first letters Sort and return So for example (in views.py): names = Person.objects.values_list('last_name', flat=True) letters = {name[0] for name in names} letters_sorted = sorted(letters) Of course I could order_by first or assign new attribute to each objects (containing first letter) but I don't think it will speed up the process. I also think that assuming … -
Django data not being saved into the sqlite database
I am quite new to Django and I am working on this project. I am trying to save a recipe into the database and after correcting a few errors I get the "Success" message. However, when I open the database with the sqlite viewer it shows that the table is empty. Here is my views file: from django.http import HttpResponse, HttpResponseRedirect import json from django.http import StreamingHttpResponse from django.shortcuts import render from django.core.serializers import serialize from django.http import JsonResponse from django.template import RequestContext from .models import StockYeast, queryset_to_indexlist,queryset_to_array, Brew, Fermentable, Miscs, RecipeYeast, Recipes, Yeast,StockFermentables from .models import Hop,StockHop,StockMiscs from .forms import RecipeForm, RecipeFermentableForm, RecipeHopForm, RecipeMiscForm,RecipeWaterForm, RecipeYeastForm,RecipeMashForm, StockMiscForm from .forms import StockFermentableForm,StockHopForm,StockYeastForm, StockMiscForm from django.forms import formset_factory def index(request): return render(request, 'index.html') def recipes(request): if request.method == 'POST': form = RecipeForm(request.POST) if form.is_valid(): n = form.cleaned_data["name"] t = Recipes(name=n) t.save() return HttpResponse("Success") else: recipes = Recipes.objects.all() recipeFermentableFormset = formset_factory(RecipeFermentableForm, extra=1) recipeHopFormset = formset_factory(RecipeHopForm, extra=1) RecipeMiscFormSet= formset_factory(RecipeMiscForm, extra=1) RecipeYeastFormSet = formset_factory(RecipeYeastForm,extra=1) RecipeMashFormSet = formset_factory(RecipeMashForm,extra=1) return render(request, 'recipes.html', {'recipes':recipes,"recipe_form" :RecipeForm(auto_id="recipe_%s"), "recipe_fermentableformset":recipeFermentableFormset(prefix='fermentable'), "recipe_hopformset":recipeHopFormset(prefix='hop'), "recipe_miscformset":RecipeMiscFormSet(prefix='misc'), "recipe_yeastformset":RecipeYeastFormSet(prefix='yeast'), "recipe_mashformset" :RecipeMashFormSet(prefix='mash'), "recipeWaterForm":RecipeWaterForm()}) Here is my recipes.html: {% block content %} <!-- Modal --> <div class="card shadow-sm"> <div class="card-header" id="headingOne"> <h5 class="mb-0"> Receptas</h5> </div> <div id="card-base" class="collapse show" aria-labelledby="headingOne" … -
How to make a post call with Django where your models are many to many?
I am trying to understand how I should be structuring my post call when I want to do a many to many relationship. class School(models.Model): name = models.CharField(unique=True, max_length=30, blank=True) teachersAtSchool = models.ManyToManyField('Teacher', blank=True) class Teacher(models.Model): account = models.ForeignKey(Account, default=1, on_delete=models.SET_DEFAULT) schoolsTeachingAt = models.ManyToManyField('School', blank=True) I send in the following JSON: { "name": "school Name", "teachersAtSchool": 0 } and get the following result: { "id": 13, "name": "school Name", "teachersAtSchool": [] } I have checked there are indeed teachers in the database that I can get with my GET call. I even tried with different id's but I get the same result. Its possible this is something super simple I just don't understand. Please help me. Regards -
Django Admin Dashboard problem with user permissions
What can I do to prevent user w1 from selecting user q when creating the location? The uesr w1 has all the rights to create the models and has staff status. Is there a way that the user w1 is written directly into the field "user" without the user w1 having to do this manually? code: models.py and admin.py https://www.codepile.net/pile/QmA9awmV enter image description here -
Summernote Icons not showing using django-summernote
I am using django-summernote and its icons aren't loading. I have followed multiple suggestions on other stack posts (like this one), and tried suggestions on github, including hard-coding CDN links to summernote's CSS, and I have tried modifying the @font-face css with A) urls to local font files, and B) hard coded urls to the fonts in my static storage, none of which worked. I also tried pulling the CSS files (unminified) directly into my page in <script> tags, also with no luck. I'm using digital ocean spaces to serve static files (which follows the AWS S3 api standards, if relevant), and I can verify they're loading, as shown in the image. The directory and each asset are designated public. Furthermore, font-awesome is already used throughout my app (version 6). I've tried rolling back to previous versions of F-A, which also did not work. From other posts, it seems summernote gets F-A icons somehow, but I'm not sure how. If anyone has any insight into this issue, I'd appreciate it. Here's how it looks now, on Chrome and other browsers: Short of writing a script to replace summernote's icons with something that works, I'm not sure what to try next. -
Django - RelatedObjectDoesNotExist / User has no customer
I am creating an e-commerce website where people can choose to login or not but still the can order and checkout (even if you are an AnonymousUser or Guest user). Now, I am making a login and register form in my website. The login form works and looks good but the register form wasn't working and throwing an error that said "RelatedObjectDoesNotExist at / User has no customer." I think the reason is that when I register, it only makes a User in database but didn't register anything in the Customer table (which consists Name and Email). How can I register a Customer and User at the same time when I hit the "Submit" button? And how can I make that specific User have "Staff status" only and cannot make changes in the Admin site? Also, I want to add new fields in the Register form for Name and Email that will go directly to the Customer table. I tried to do this one but it doesn't work and throwed and error that says "django.core.exceptions.FieldError: Unknown field(s) (name) specified for User". Here's what I did: from django.forms import ModelForm from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import … -
django filter fields + custom Q field
I am trying to use regular filter fields with multi search field. If I put just fields = [`q`] or fields = { 'model': ['icontains'], 'type' : ['icontains'], } then it works but if I try to use them together, it doesn't. How do I make this work? filter.py class CustomFilter(django_filters.FilterSet): q = django_filters.CharFilter(method='custom_search_filter',label="Title & Tag Search") class Meta: model = CustomModel fields = { 'model': ['icontains'], 'type' : ['icontains'], ['q'] } def custom_search_filter(self, queryset, name, value): return queryset.filter( Q(title__icontains=value) | Q(tag__icontains=value) ) -
whats wrong this query in djagno
def get_available_working_hours(location_id, date, appointment_type): providers = get_availabe_providers(location_id, appointment_type.id).values_list('id', flat=True) _workinghours = WorkingHour.objects.filter( Q(week_days__contains=[date.weekday()]) | Q(date__lte=date) & Q(end_date__gte=date), location_id=location_id, provider_id__in=providers ).distinct().values( 'start_time', 'end_time', 'provider_id' ) workinghours = normalize_datetime(date, _workinghours) # print(workinghours) _blockhours = BlockHour.objects.filter( provider_id__in=providers, location_id=location_id, date=date ).values( 'start_time', 'end_time', 'provider_id' ) blockhours = normalize_datetime(date, _blockhours) -
Assign user input in charField as foreign key
I am trying to implement a registration key in the registration form which the user has to input to be able to create an account. In my users model, I have a key field which is the foreign key of the Key model. The relation looks like this class RegistrationKey(models.Model): key = models.CharField(max_length=30) class User(AbstractUser): ... key = models.ForeignKey(RegistrationKey, on_delete=models.CASCADE, null=True, blank=True) I have tried to validate the input like this in the view def registerPage(request): form = MyUserCreationForm() if request.method == 'POST': form = MyUserCreationForm(request.POST) key_input = request.POST.get('key') ... if RegistrationKey.objects.filter(key_input=key).exists() and form.is_valid(): user = form.save(commit=False) user.key.add('key_input') ... user.save() In my form have I set the key field as a CharField as I can not display the keys for the user. This means that the user inputs a string but django needs an instance to be able to save it to the database. I don't know how to implement this. Is there any way to convert a string to an instance or is there a better way to query the the database, to check and see if the input is a valid key? -
Get related Model foreignkey (in addition to the ManyToMany) with prefetch_related(model_SET).all()
With prefetch_related, I retrieve the list of my different warehouses stock like this : Model Product [nothing special] Model Warehouse [nothing special] Model SstStock class SstStock(models.Model): warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) product = models.ManyToManyField(Produit) qty = models.IntegerField() last_update = models.DateTimeField(default=timezone.now) views.py class ProductListView(LoginRequiredMixin, ListView): queryset = Product.objects.prefetch_related('sststock_set').all() context_object_name = "produits" paginate_by = 10 template_name = 'products/produits.html' def get_context_data(self, *args, **kwargs): context = super(ProductListView, self).get_context_data( *args, **kwargs) context['title'] = 'Produits' return context Template {% for produit in produits %} {{ produit.sku}}<br> {% for sst in produit.sststock_set.all %} <span>{{ sst.warehouse.code }} - {{sst.qty}} - {{sst.qty}}</span> {% endfor %} {% endfor %} But when I get the information related to the warehouse eg. sst.warehouse.code in template, the number of queries explodes. (already 36 queries with a pagination of only 10 products) Is there a way to add warehouse in prefetch_related in the view ? -
How to process an uploaded file and notify the user later when the file is uploaded in django
I have a Django app that allows a user to upload file. I am processing this file on the server and it takes about 3 mins for the task to complete. I am assuming the browser won't wait that long for a response after POST request. So I want a way to respond to the post immediately after the file upload and start the heavy operation in a new thread and then 3 mins later notify the user. Is this possible in Django and how? please do guide me. Thanks -
When I save the data and upload multiple files nothing happens
I have a question, what happens is that I am making a form that accepts text and also has 2 input buttons to upload multiple images. I've been reviewing the documentation of the official django site and there are things where I get lost. For example, I already made the view as it comes in the documentation, but when I save, it does not save images or data in the database. Only one detail was missed in the view and it is that I did not understand how to do the iteration with the for. At first I put the fields of the model and the same fields I put them in the arguments where it says def post but I get a thousand errors. Can you help me to solve this problem? Thanks models.py class Carro(models.Model): placas=models.CharField(max_length=255) tipo=models.CharField(max_length=255) marca=models.CharField(max_length=255) modelo=models.CharField(max_length=255) año=models.IntegerField() vin=models.CharField(max_length=255) color=models.CharField(max_length=255) motor=models.CharField(max_length=255) agente_seguros=models.CharField(max_length=255, null=True) compañia_seguros=models.CharField(max_length=255, null=True) no_politica=models.CharField(max_length=255, null=True) cliente= models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True) fotosCarro=models.ImageField(null=True, upload_to="images/") garantia=models.ImageField(null=True, upload_to="images/") fecha_registros = models.DateTimeField(default=datetime.now, null=True) def __str__(self): return f'{self.placas} {self.año}{self.marca} {self.modelo} {self.tipo}{self.motor}{self.vin}{self.color}' \ f'{self.agente_seguros}{self.compañia_seguros}{self.no_politica}{self.cliente}' \ f'{self.fecha_registros}{self.fotosCarro}{self.garantia}' carros-form-add.html <div class="col-md-4"> <div class="mb-3"> <label>Policy No.</label> {{ form.no_politica }} </div> </div> </div> <div class="row mb-3"> <div class="col-md-4"> <div class="mb-3"> <label>Cliente</label> {{ form.cliente }} </div> </div> … -
Django Server not starting because of RestFramework
[error message][1] Each time i include the Django Rest Framework in my installed apps in my settings.py file, I get an error while starting my server. Kindly help. I attached a screenshot of the error message and settings.py file for reference. Thank you. -
Having trouble saving django forms to sqlite
I am currently working on a program which is currently in development. Now I have never worked with Django before this and I am having some troubles. I am trying to save a few form fields to a sqlite database however I am getting errors. Here is the error that I get NameError at /recipes name 'form' is not defined Request Method: POST Request URL: http://localhost:8000/recipes Django Version: 4.0.2 Exception Type: NameError Exception Value: name 'form' is not defined Exception Location: C:\Users\Admin\Desktop\praktika\brew\brewery\views.py, line 24, in recipes Python Executable: C:\Program Files\Python310\python.exe Python Version: 3.10.2 Python Path: ['C:\\Users\\Admin\\Desktop\\praktika\\brew', 'C:\\Program Files\\Python310\\python310.zip', 'C:\\Program Files\\Python310\\DLLs', 'C:\\Program Files\\Python310\\lib', 'C:\\Program Files\\Python310', 'C:\\Users\\Admin\\AppData\\Roaming\\Python\\Python310\\site-packages', 'C:\\Program Files\\Python310\\lib\\site-packages', '/home/ponasniekas/wwwpi/brew', '/home/ponasniekas/wwwpi/brew/brew', '/home/ponasniekas/wwwpi/brew/brew/brewery', '/home/ponasniekas/.local/lib/python3.8/site-packages'] Here is my views file: from django.http import HttpResponse import json from django.http import StreamingHttpResponse from django.shortcuts import render from django.core.serializers import serialize from django.http import JsonResponse from django.template import RequestContext from .models import StockYeast, queryset_to_indexlist,queryset_to_array, Brew, Fermentable, Miscs, RecipeYeast, Recipes, Yeast,StockFermentables from .models import Hop,StockHop,StockMiscs from .forms import RecipeForm, RecipeFermentableForm, RecipeHopForm, RecipeMiscForm,RecipeWaterForm, RecipeYeastForm,RecipeMashForm, StockMiscForm from .forms import StockFermentableForm,StockHopForm,StockYeastForm, StockMiscForm from django.forms import formset_factory def index(request): return render(request, 'index.html') def recipes(request): if request.method == 'POST': recipes = RecipeForm(request.POST) if form.is_valid(): n = form.cleaned_data["name"] t = Recipes(name=n) t.save() else: recipes …