Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django + Html: Is it possible to display the initial value in a <select> before change is made so they can see initial
Django + Html: Is it possible to display the initial value in a before change is made, so that if user dont want to update they can leave it as it is. So current i have not choice but to do this in my account update page. Is there a way to make it such that i can query the initial date of birth so i dont have to reselect my date of birth everytime i update other fields in the same form. Thanks views.py def edit_account_view(request, *args, **kwargs): user_id = kwargs.get("user_id") account = Account.objects.get(pk=user_id) if account.pk != request.user.pk: return HttpResponse("You cannot edit someone elses profile.") context = {} if request.POST: form = AccountUpdateForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): form.save() return redirect("account:view", user_id=account.pk) else: form = AccountUpdateForm(request.POST, instance=request.user, initial={ "id": account.pk, "date_of_birth": account.date_of_birth, } ) context['form'] = form else: form = AccountUpdateForm( initial={ "id": account.pk, "date_of_birth": account.date_of_birth, } ) context['form'] = form context['DATA_UPLOAD_MAX_MEMORY_SIZE'] = settings.DATA_UPLOAD_MAX_MEMORY_SIZE return render(request, "account/edit_account.html", context) forms.py class AccountUpdateForm(forms.ModelForm): class Meta: model = Account fields = ('username', 'date_of_birth') html <h6 class="mt-4 field-heading">Date of Birth</h6> <input type="date" name="date_of_birth" id="input_dateofbirth" class="form-control" placeholder="Date of birth" required required value="{{form.initial.date_of_birth}}"> <p >{{form.initial.username}}'s Birthday: {{form.initial.date_of_birth}}</p> <p style="color: red;">Reselect your Birthday date again during update … -
Difficulty accessing and working with Django models/QuerySets
My goal is to pull ship data once I pick the ship number but I have no idea how. Here is my model setup from django.db import models from django.contrib.auth.models import User class Hull (models.Model): hull = models.CharField(max_length = 33, ) def __str__(self): return self.hull class Hull_Spec(models.Model): ship = models.ForeignKey(Hull, on_delete=models.CASCADE) speed = models.FloatField() depth = models.FloatField() remarks = models.CharField(max_length =300) def __many_fields_simple_array__(self): return [self.remarks, self.depth, self.speed] Here is what I try starting data hull = SS1 depth = 10 speed = 10 remarks = 'remarks' from main.models import Hull. Hull_Spec hull = Hull.objects.get(hull = 'SS2') specs = hull.hull_spec_set.all() #which returns <QuerySet [<Hull_Spec: Hull_Spec object (2)>]> This is where I get stuck. I can get all of the information if I use the id but I have no idea how to retrieve a spec list's id unless I retrieve it from the terminal as shown above. Is there another way I can retrieve the data from the queryset without having to use get(id =) since I know already which ship this spec data corresponds to already? -
Why is Django authentication is now working for AbstractUser
So I have these Django models in the users app, and I have added AUTH_USER_MODEL = 'users.User' to settings.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): login_count = models.PositiveIntegerField(default=0) class Supplier(User): company_name= models.CharField(max_length=30) company_domain=models.CharField(max_length=30) class Meta: verbose_name = 'supplier' verbose_name_plural = 'suppliers' class Worker(User): ACCOUNT_TYPE = ( ('1', 'Admin'), ('2', 'Regular'), ) is_hub_manager = models.BooleanField(default=False) account_type = models.CharField(max_length=1, choices=ACCOUNT_TYPE) class Meta: verbose_name = 'worker' verbose_name_plural = 'workers' I also created an authenetication endpoint using Django rest framework. Surprisingly when I authenticate the admin everything works well. When I create a supplier and try to authenticate them. They always return invalid credentials. Here are my API views from rest_framework.generics import GenericAPIView from .serializers import UserSerializer from rest_framework.response import Response from rest_framework import status from django.conf import settings from django.contrib import auth import jwt class LoginView(GenericAPIView): serializer_class = UserSerializer def post(self, request): data = request.data username = data.get('username', '') password = data.get('password', '') user = auth.authenticate(username=username, password=password) if user: auth_token = jwt.encode({'username': user.username}, settings.JWT_SECRET_KEY) serializer = UserSerializer(user) data = {'user': serializer.data, 'token': auth_token} return Response(data, status=status.HTTP_200_OK) # SEND RES return Response({'detail': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED) What could I be doing wrong? -
Bootstrap modal to confirm deletion
When I loop over my images I have an icon that you can click to delete the image. Instead I'd like to have a modal pop up to confirm the deletion. The only problem is I don't want to repeate the code for the modal for each image. I need a way to pass the image id to the modal. I was thinking I could pass the id in through an onClick but I'm not sure that will work with the Bootstrap modal. Here's how I'm currently deleting: {% for image in images %} <img src="{{image.image.url}}"> <form method="POST" action="{% url 'products:delete_image> {% csrf_token %} <button type="submit" rel="tooltip" title="Remove"> <i class="material-icons">close</i> </button> </form> {% endfor %} Here's the modal code I'd like to integrate <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> -
Django: Template rendering error: NoReverseMatch. How to match necessary pattern using regex?
I am using django_filters and have a set of drop downs that, upon selection, filter and show consequent list from all possible objects. In other words, a simple online directory-like function. I want to pass the querysets to a new view so that the filtered list has its own separate web page. When trying to pass the data to the new view, upon button click, I receive a NoReverseMatch template rendering error. If I don't try to pass it to a new view, but just keep the results on the same page, the url of that page changes from: animal\search\ to animal\search\?type=5&ageGroup=2 and shows all necessary data as expected. I want this data to pass from animal\search, where the user selects desired filter options with the two drop downs, to animal\results\?type=5&ageGroup=2. How can I match this url pattern in regex or otherwise? Or is the problem in my view? Reverse for 'visitor_results_view' with arguments '(<django.forms.boundfield.BoundField object at 0x104847e80>, <django.forms.boundfield.BoundField object at 0x103460c88>)' not found. 1 pattern(s) tried: ['animals/results/(?P<type>[0-9]+)\\&(?P<ageGroup>[0-9]+)/$'] urls.py path('results/<int:type>&<int:ageGroup>/', views.AnimalSearchListView.as_view(), name='visitor_results_view'), path('search/', views.AnimalFilterView.as_view(), name='animalFilter_view'), animal/search.html <form class="form-inline justify-content-center" method="GET" action="{% 'url animals:visitor_results_view' type=filter.form.type ageGroup=filter.form.ageGroup %}"> <div class="col-md-3"> {{ filter.form.type | bootstrap}} </div> <div class="col-md-4 "> {{ filter.form.ageGroup | bootstrap}} … -
How to convert UTC to EST in Django
I am trying to convert UTC to EST in a view and display this in a template. Currently the code seems to have not effect. Here is the view: from django.shortcuts import render, redirect, get_object_or_404 from .models import Article from .models import Article Image from .models import Article Specs from datetime import datetime from django.utils import timezone from django.core.paginator import Paginator def detail(request, article_id): article = get_object_or_404(Article, pk=article_id) image_all = ArticleImage.objects.all() specs_all = ArticleSpecs.objects.all() # est = pytz.timezone('Pacific/Auckland') article_release_datetime = article.releaseDate.astimezone(est) # datetime_now = datetime.now(timezone.utc) datetime_now.astimezone(est) release_countdown = article_release_datetime - datetime_now # (days, remainder) = divmod(release_countdown.seconds, 86400) (hours, remainder) = divmod(remainder, 3600) (minutes, seconds) = divmod(remainder, 60) # return render(request, 'shoes/detail.html', {'article': article, 'image_all': image_all, 'specs_all': specs_all, 'days': days, 'hours': hours, 'datetime_now': datetime_now, 'minutes': minutes, 'seconds': seconds, 'release_countdown': release_countdown}) Here is the template:: enter code here -
django passing multiple parameters to JS document.location.url
In a Django template I am trying to redirect to a different view on a button click through JS. The url needs multiple arguments. I am able to pass multiple argument but when I check the kwargs in the view the values are wrong. The first argument grabs most of the second argument as well. Here is how it looks (Pdb) kwargs {'id1': 1659165, 'id2': 6} Here id1 should be 1659 and id2 should be 1656. Here is the JS code: compare_btn.onclick = function() { var m1=cube1_id.innerHTML; var m2=cube2_id.innerHTML; document.location.href = '{% url "cubes:cube-comparison" id1=11 id2=22 %}'.replace(11,m1).replace(22, m2); } Here is the url: path('cube-comparison/<int:id1><int:id2>', CompareCube.as_view(), name='cube-comparison') I have read one two 3 4 5 and some other questions. Its only one place where I have to use JS so I want to avoid using some library. Thanks for any help. -
HTTPError "message": "MISSING_EMAIL", CODE=400, IN Django Firebase Database
When we login that error occured enter image description here -
Why is Django Celery Beat not starting?
I have been working on this issue for about 4 days now, and it's been extremely frustrating. I would greatly appreciate it if somebody would answer this question for me. I am working on a Django Project that requires me to periodically check objects and some files in the media directory and delete them if outdated. After referring to the celery documentation , I set up everything properly (at least I think), and went ahead to run the program. I first ran my project on one terminal window, then ran a redis server using redis-server on another terminal window. Using a third terminal window, I ran the following: (djangoenv) Daeyongs-Air:Data_Science_Project daeyong$ celery -A Data_Science_Project worker -l info -------------- celery@Daeyongs-Air.fios-router.home v5.0.5 (singularity) --- ***** ----- -- ******* ---- macOS-10.16-x86_64-i386-64bit 2021-01-02 02:57:54 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: Data_Science_Project:0x7f9b0e59f1f0 - ** ---------- .> transport: redis://localhost:6379// - ** ---------- .> results: redis://localhost:6379/ - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . Data_Science_Project.celery.test . task_number_one [2021-01-02 02:57:55,154: INFO/MainProcess] Connected to … -
ValueError: Cannot query "": Must be "" instance
I have a quiz app where users can attempt each quiz as many times as they wish. I am now trying to show some quiz stats on the user's profile. What I'm struggling with is showing the user's average score across quizzes. So first, I get the total number of correct answers: correct_answers = QuizTaker.objects.filter(user = self.user, completed = True).aggregate(Sum('correct_answers'))['correct_answers__sum'] This works as expected. Now I need to get the number of attempts per quiz and multiply this by the number of questions in each quiz. Then I would be able to calculate the average score. I got stuck trying to get the number of attempts per quiz. If I hard code it as follows, it works: number_attempts = QuizTaker.objects.filter(user = self.user, completed = True, quiz__title='Afrika').aggregate(Max('attempt_number'))['attempt_number__max'] But I need the max number of attempts for every quiz. So I need to do a for loop. quiztakers = QuizTaker.objects.filter(user = self.user, completed = True) max_attempts = [] for quiz in quiztakers: number_attempts = QuizTaker.objects.filter(user = self.user, completed = True, quiz=quiz).aggregate(Max('attempt_number'))['attempt_number__max'] attempts.append(number_attempts) return max_attempts But then this gives me the following error: ValueError at /accounts/profile/ Cannot query "Username- Quiz: Afrika - Attempt number: 2": Must be "Quiz" instance. The relevant models: class … -
Django: How To Sort ManyToManyField By Alphabetical Order
I have a model that stores the genres/categories of items which can then be selected in form by multiple choice checkboxes. I have want to be able to add genres to the database and then have them slot in to their part in the alphabetical order. I could just enter the values in alphabetical order but that makes it harder to add more later so im trying to find if there is a better way to do it. i have saw someone using class meta: order, but i don't know if that can be used to sort a-z here is some relevant info models.py class Genres(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural = "Genres" class Post(models.Model): genres = models.ManyToManyField(Genres, null=True, blank=True) forms.py genre_choices = Genres.objects.all().values_list('name', 'name') genre_choices_list = [] for item in genre_choices: genre_choices_list.append(item) class NewPost(forms.ModelForm): genres = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={'class': 'form_input_select_multi'}), choices=genre_choices_list) -
Django and yFinance Python integration
I am very new to this. Trying to grab data from yFinance and view it in a web browser using the Views available in Django. The HomePageView renders in the browser as expected but the CompanyDetails does not. Also, there are no known errors... from django.views.generic import TemplateView from django.views import generic import yfinance as yf class HomePageView(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['my_thing'] = 'hello world, this is dynamic - 500%' return context class CompanyDetails(generic.DetailView): template_name = 'home.html' def get_context_data(self, **kwargs): tickerdata = yf.Ticker("MSFT") tickerinfo = tickerdata.info investment = tickerinfo['shortName'] context = super().get_context_data(**kwargs) context['ticker'] = investment return context -
I keep getting a Bad Request error due to a GET in my drf login view
Not sure what the problem is, I originally had a genericAPIview used as my user login view that had these errors: Method Not Allowed: /auth/login and "detail": "Method \"GET\" not allowed." So I added a GET method like so: class LoginAPIView(generics.GenericAPIView): permission_classes = [AllowAny] serializer_class = LoginSerializer # I ADDED THIS GET METHOD TO SOLVE FOR ABOVE def get(self, request, format=None): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data) def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) Adding the GET function did solve for "Method \"GET\" not allowed.", but now I'm getting this new error: Bad Request: /auth/login/ Here are my app urls.py urlpatterns = [ path('register/', CustomUserCreate.as_view(), name="register"), path('login/', LoginAPIView.as_view(), name="login"), path('home-auth/', include('rest_framework.urls', ] Here are my project urls.py urlpatterns = [ path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), # path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('admin/', admin.site.urls), path('home/', include('bucket_api.urls', namespace='bucket_api')), path('auth/', include('users.urls')), path('home-auth/', include('rest_framework.urls', namespace='rest_framework')), ] Any tips on how I can solve for the errors above? -
Django: Reverse for 'delete' with arguments '('',)' not found. 1 pattern(s) tried: ['$']
I'm a new face to Django so please be considerate to if ever my problem is something stupid. In this case I want to delete an item in my database, if I click on the button, the html will pass an id to views.py, then the funtion Delete() will delete this item. But whatever I tried it dosen't have any response. Now I add action="{% url 'todolist:delete' todo.id %}" in home.html, but it met some error : NoReverseMatch: Reverse for 'delete' with arguments '('',)' not found. 1 pattern(s) tried: ['$'] , and I don't know how to solve it. So please give me some advice, I'll be really grateful. My codes are as follows: project/urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', include('todolist.urls', namespace='todolist')), ] todolist/urls.py: app_name = "todolist" urlpatterns = [ path('', views.Add, name = 'add'), path('', views.Delete, name = 'delete'), ] home.html: <form action="{% url 'todolist:delete' todo.id %}" method="post"> {% csrf_token %} <table> <tbody> {% for each in todo_list %} <tr> <td><div class="thing"><input type="checkbox" name="done" value="done"><label>{{each.todo}}</label></div></td> <td><input type="button" class="edit" name="edit" value="E"></td> <td><input type="button" class="delete" name="delete" value="x"></td> </tr> {% endfor %} </tbody> </table> </form> views.py: def Delete(request, id): if 'delete' in request.POST: todo = Todo.objects.get(id=id) todo.delete() todo_list = Todo.objects.all() return … -
Django multiple user with using AbstracBaseUser and login email field
I want to use different users in my own project. Users will have different features and I want to log in by e-mail. I'm creating it using AbstracBaseUser, and there should be different login and register pages for both users. Can you tell me the sample code or project about it. -
Python Django - HTML Radio button truncates all letter after space when assigning value
By my read of the code shown below, clicking Test 1 or Test 2 should return Test 1 or Test 2, whichever was clicked; however, instead Test is only returned. Essentially everything following the space is truncated in the value field. Why is this happening? Thanks for your input! HTML <div> <form action = '/test_out/' method = 'POST'> {% csrf_token %} {% for item in test_var %} <input type = "radio" value = {{ item }} name = 'clicked'> {{item}} <br><br> {% endfor %} <input type = 'submit' text = 'Modify Hull'> </form> </div> views.py def test(response): return render(response, 'main/hull_view.html', {'test_var': ['Test 1','Test 2']}) def test_out(response): return HttpResponse(response.POST.get('clicked')) -
Sending items to json using dump not working properly
I am not an expert in javascript but I am trying to learn bit by bit. I am trying to add a search function for my project, so I am starting by sending the item list to JSON using the following: views.py class ItemListView(ListView): model = Item paginate_by = 12 template_name = "store/product_list.html" ordering = ['-timestamp'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["qs_json"] = json.dumps(list(Item.objects.values())) return context but I keep receiving an error Object of type Decimal is not JSON serializable My question: Why am I receiving this error although I am following a tutorial and this error didn't show up and how do I fix it? -
Django order by ID on Union
I'm trying to order this queryset union by specified ID using Case and When, but I keep getting this error on both SQLite and Postgres with Django 3.1, Py 3.8 (and PG 12.3, not sure about SQLite): django.db.utils.DatabaseError: ORDER BY term does not match any column in the result set. This is the test case: _values = ["id", "parent_id", "parent__title", "created"] class TestBlah(TestCase): def test_order_by(self): a = A.objects.create() b = C.objects.create(parent=B.objects.create()) asd = ( A.objects.annotate( parent_id=models.Value(-1, output_field=models.BigIntegerField()), parent__title=models.Value("", output_field=models.CharField()) ).values(*_values).union(C.objects.values(*_values)) .order_by(models.Case(*[models.When(pk=obj.id, then=i) for i, obj in enumerate([b, a])])) ) My models: from django.db import models class Base(models.Model): id = models.BigAutoField(primary_key=True) created = models.DateTimeField(auto_now_add=True) class Meta: abstract = True class A(Base): ... class B(models.Model): id = models.BigAutoField(primary_key=True) title = models.CharField(max_length=255) class C(Base): parent = models.ForeignKey(B, on_delete=models.CASCADE) It seems like the queryset is not yet evaluated and it's simply Django verifying everything. Anyone know what's up? -
Escape colon in a DismaxString in Scorched/Sunburnt/Solr
I'm using scorched for interfacing my Django code with my Solr instance: response = si.query(DismaxString(querydict.get('q')).execute() I'm using DismaxString because I want to be able to do exact searches (strings within "") and DismaxString doesn't escape characters. Nevertheless, in my data I have colons (e.g. Col: Mackay's Reel) and I don't want Solr to interpret that colon as a 'field' query: "metadata":[ "error-class","org.apache.solr.common.SolrException", "root-error-class","org.apache.solr.common.SolrException"], "msg":"undefined field Col" How can I esccape all the colons and still retaining the unescaping of "? -
Use checkboxes with custom Django form
I'm trying to get Checkboxes to work with my custom form but experiencing some issues. A similar approach using Select inputs works fine, thought it would be similar. By doing {{ form.answer }} I get it to render in my template, but nothing is being saved once I press submit. The column is an integer field since I want to store values between 1-5, and not just true or false answer = models.IntegerField(default=None, null=False) Worth mentioning is that this particular column will store only one value, so the MultipleChoiceField() might be misleading. Will need to change that to the correct one whichever that is later on. My form class EditProfile(UserChangeForm): USER_OPTIONS = ( ('1', 'apple'), ('2', 'banana'), ('3', 'orange'), ('4', 'pear'), ) answer = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=USER_OPTIONS) class Meta: model = Person fields = ( 'answer', ) exclude = ( 'password', ) Any clues or feedback would be appreciated! -
Creating drop down menu in html and css (strange error)
Before you read: please do not judge me on every little thing. I am a beginner to this sort of thing and I am just trying to get some practice. Only comment my mistakes if they are either relevant to the conversation or truly helpful. I've looked over and over at my code and stackoverflow answers but nothing has what I need. I want to create a dropdown menu (you hover on a button and multiple links appear in a vertical line below it). I have been having trouble because the links are horizontal instead of vertical when I hover. I have no idea why. I thought this may be because the display style on my nav bar is set to inline, but I used id's in my css, so that should override the navbar classes. I'm very confused. Someone please help. Here is the relevant code (yes, I am using django): <style> #dropdown {display: none;position: relative;background-color: #dde000; padding: 0px;z-index: 1; left: 970px; top:45px;} #drop:hover #dropdown {display:block;} div.navbar {border: 2px outset gray; position: relative; margin-left:-21px; height:45px; background: #dddddd; margin-top:-6px; left: 15px;} .navbar a {height: 23px; display:inline; text-decoration: none; color: black; padding: 10px; float: left; background: #dddddd; padding-top:12px;} .navbar a:hover {background: … -
Django Storages [file upload to was s3]
I am using django storages library for upload my files to s3. I want to understand how this file uploads works , does the file uploads to s3 folder directly or it uploads to my server and then goes to s3? How does the file upload works in django storages. If I upload multiple files , will they use bandwidth of my server of will they be directly uploaded to s3 and will not slow the speed of my server. Thank you -
Populating django model with objects from other model
I'm new to django, but working on an app for a volunteer sailing organization in my local area. Not sure how to ask this question since it's fairly general but I want the following to happen based on two models; Yacht class (boat name, skipper, color, etc.) Race_Event class (event date, time results for each boat) Step 1: The user will need to create a Race_Event each week. I want the boats from the Yacht model to be loaded into the Race_Event. Step 2: The user will enter race times for each boat. Is there a way to pre-load objects from one model into another? With a ForeignKey the user has to add the boats each time. Any direction for me to research would be helpful. Thanks -
how do I save properly manytomany field in django?
I am trying to save an m2m field where my JSON takes an array where of tactics where it should store n times tactics appear in the list, but how can I do this properly? in my following case, it should be stored two times since the technique is shared in two tactics, but how do I achieve the following? for technique in src_techniques: for data_technique in technique: techniques = { technique_id = data_technique['technique_id'] technique_name = data_technique['technique_name'] tactics = data_technique['tactics'] } Technique.objects.get_or_create(**techniques) src_techniques [{"id":1,"source_name":"mitre-attack","tactic_id":"TA0009","tactic_url":"https://attack.mitre.org/tactics/TA0009","tactic_name":"Collection"}] src_techniques [{'technique_id': 'T1548', 'technique': 'Abuse Elevation Control Mechanism', 'url': 'https://attack.mitre.org/techniques/T1548', 'tactic': ['Collection', 'Defense Evasion']}] models class Technique(models.Model): technique_id = models.CharField(max_length=10) technique_name = models.CharField(max_length=40) tactics = models.ManyToManyField(Tactic, blank=True, null=True) class Tactic(models.Model): tactic_name = models.CharField(max_length=100) -
Trying to load data into databse through web browser: save() prohibited to prevent data loss due to unsaved related object 'ship'
I'm at a total loss as to why I get this error. When I run similar code in the python shell I never get this error but when I try to do this through the web browser I get this error. Any idea why this happens? FYI, I'm a total beginner. Models: from django.contrib.auth.models import User class Hull (models.Model): hull = models.CharField(max_length = 33, ) def __str__(self): return self.hull class Hull_Spec(models.Model): ship = models.ForeignKey(Hull, on_delete=models.CASCADE) speed = models.FloatField() depth = models.FloatField() remarks = models.CharField(max_length =300) def __str__(self): return self.remarks views def new_ship (response): x = Hull x.objects.create(hull = response.POST.get('ship')) Z = Hull(hull = response.POST.get('ship')) Z.hull_spec_set.create(speed = response.POST.get('speed'), depth = response.POST.get('depth'), remarks = response.POST.get('remarks')).save() return HttpResponse('Success') html user interface <div> <form action = '/new_ship/' method = 'POST'> {% csrf_token %} <table> <col> <tr> <td><input type = 'text' name = 'ship'>Hull</input></td> <td><input type = 'text' name = 'speed'>Speed</input></td> </tr> <tr> <td><input type = 'text' name = 'depth'>Depth</input></td> <td><input type = 'text' name = 'remarks'>Remarks</input></td> </tr> <tr> <td><input type="submit" value="Submit Fields" id = 'button_1'></td> </tr> </col> </table> </form> </div>