Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I communicate with a websocket within a Django API GET request?
I'm trying to get a response from a websocket server (implemented with websockets and asyncio) from within a Django REST API method. Something of the following structure: Django App (This does not work, but illustrates the idea) class AnAPI(views.APIView): async def get(self, request): try: timeout = 5 try: ws_conn = await asyncio.wait_for(websockets.connect(WS_STRING), timeout) except ConnectionTimeoutError as e: <.....> await ws_conn.send(...) response = await ws_conn.recv() ws_conn.close() return Response(...) except Exception as e: print(e) return Response(...) WS Server ws_server = websockets.serve(...) asyncio.get_event_loop().run_until_complete(ws_server) asyncio.get_event_loop().run_forever() Apparently, this makes the Django GET method return a <class 'coroutine'> AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'coroutine'>` Any pointers would be much appreciated! -
Django ORM pass model method value in aggregate
This is my models: class Bill(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='user_bill' ) flat_rent = models.DecimalField( max_digits=6, decimal_places=2, default=0.00 ) gas_bill = models.DecimalField( max_digits=6, decimal_places=2, default=0.00 ) # Also i have many such decimalField here that calculated in get_total =========================================== def get_total(self): total = self.flat_rent + self.gas_bill return total I am trying to pass this get_total mehtod value here: user_wise = User.objects.filter( id=request.user.id ).aggregate( get_total=Sum('user_bill__get_total') ) in my case, i have to query everything from user with related_name, that is why i am aggregate the model method here. Can anyone help how can i pass this get_total method in aggrigate? I dont want to pass like this. Bill.objects.get(user__id=request.user.id).get_total Can anyone help to achieve this? Thanks for your help -
Django- 2nd App within project, page not found
I can not figure out what I am doing wrong within the second app my project called 'weather'. The first part, 'home', works fine. I made it so that an empty url '' and a url with '/home/' both map to the home page. Even the link I created in my navigation bar to the home page works, but the same is not true for the weather link. I end up getting 'Page not found 404' Error. Here is an overview: Project structure I included the app 'weather' in the settings installed apps. Here urls.py file in the main project folder: from django.contrib import admin from django.urls import path, include from weather import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('', include('weather.urls')), ] The urls.py file for my weather app: from weather import views from django.urls import path urlpatterns = [ path('', views.GetWeather.as_view(), name='weather'), ] The views.py for the weather app: from django.views import generic import requests from django.shortcuts import render from .models import City from .forms import CityForm class GetWeather(generic.ListView): queryset = City.objects.order_by('-requested') template_name = 'weather.html' def index(request): url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=c5a079de62bccff63d64ac8989f87e37' form = CityForm() cities = City.objects.all() weather_data = [] for city in cities: r = requests.get(url.format(city)).json() city_weather … -
Django: Saving instance only if it does not exist already
I only want to save an instance of Location if the address does not exist already. Currently when you try to save with an address that already exists you receive a BAD REQUEST. How can I override the save function to achieve this? And would this be the right way to do it? current model: class Location(models.Model): latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True) longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True) address = models.CharField(max_length=150, unique=True) field_quality = models.DecimalField( max_digits=3, decimal_places=1, null=True,) field_availability = models.DecimalField( max_digits=3, decimal_places=1, null=True,) place_id = models.CharField(max_length=200, null=True) def save(self, *args, **kwargs): if self.objects.filter(address=[self.address]).exists(): pass else: super().save(*args, **kwargs) -
REST API ?? Django?
I have a following requirement and was looking for some direction. Purpose - Create a website framework where suppliers can enter the information about material characteristics for every order they supply. I store that information in SQL and attach it to the physical order. I trace the material usage and adjust the process according to the characteristics associated with the Order. I am familiar with SQL, python and bit of java. I started learning Django and thought that It might could be something workable but just wanted to make sure I choose the right direction. Any leads will be much appreciated. -
My friends can't send video files from chrome. 403 error occured
Recently I made a video converting application, and deployed to nginx. And there's a problem that my friends can't send video files(axios form-data type) from chrome browser. (403 INCOMPLETE_CHUNKED_FILE error) But In my computer, I can send a video file from chrome to nginx deployed django application, and send back the converted video file url. I tried 1. chmod 777 web application contained directory 2. change uwsgi chmod-socket 660 -> 666 3. client_max_body_size 1M -> 50M 4. set ec2 80port //uwsgi.ini [uwsgi] uid=django base=/var/www/fileconvert home=%(base)/venv chdir=%(base) module=config.wsgi:application env=DJANGO_SETTINGS_MODULE=config.settings master=true processes=5 socket=%(base)/run/uwsgi.sock logto=%(base)/logs/uwsgi.log chown-socket=%(uid):www-data chmod-socket=666 vacuum=true //uwsgi.service [Unit] Description=uWSGI Emperor service [Service] ExecStart=/var/www/fileconvert/venv/bin/uwsgi --emperor /var/www/fileconvert/run User=django Group=www-data Restart=on-failure KillSignal=SIGQUIT Type=notify NotifyAccess=all StandardError=syslog [Install] WantedBy=multi-user.target // sites-available/fileconvert upstream django{ server unix:/var/www/fileconvert/run/uwsgi.sock; } server { listen 80; server_name ec2_public_domain; charset utf-8; client_max_body_size 50M; location / { include /etc/nginx/uwsgi_params; uwsgi_pass django; } } I want to know how to get data from another computer without error 403. Thanks! -
TypeError: expected str, bytes or os.PathLike object, not method
I'm trying to upload a file uploaded from HTML form via POST to Google Drive. I was able to get the file name, file temp path, but it throws this error and the file is eventually not uploaded to Google Drive. @method_decorator(csrf_exempt, name='dispatch') class Submit(MissionSubmission): def get(self, request, mission_id): mission = MissionDetail.objects.all().filter(id=mission_id)[0] mission = newline_aware(mission) return render(request, 'home/submit.html', {'mission': mission}) def post(self, request, mission_id): request.upload_handlers = [TemporaryFileUploadHandler(request=request)] return self._post(request, mission_id) @method_decorator(csrf_protect) def _post(self, request, mission_id): uploaded_file = request.FILES['filename'] print(uploaded_file.name) print(uploaded_file.size) print(uploaded_file.temporary_file_path()) print(uploaded_file.content_type) file_metadata = {'name': uploaded_file.name} media = MediaFileUpload(uploaded_file.temporary_file_path, mimetype=uploaded_file.content_type) file = drive.files().create(body=file_metadata, media_body=media, fields='id').execute() print('File ID: %s' % file.get('id')) return HttpResponse("Hi") Anyone knows what's wrong? -
How can I restore the database contents
I back up the database by below command: docker exec -it kiwi_web /Kiwi/manage.py dumpdata --all --indent 2 > database.json then, upgrade running Kiwi TCMS containers and restore the database by executing the following commands: [1.cd Kiwi/ 2.git pull 3.docker-compose down 4.docker pull kiwitcms/kiwi 5.docker pull centos/mariadb 6.docker volume rm kiwi_db_data 7.docker exec -it kiwi_web /Kiwi/manage.py migrate 8.docker-compose up -d ] until now, it's fine. when I delete data from all tables [docker exec -it kiwi_web /bin/bash -c '/Kiwi/manage.py sqlflush | /Kiwi/manage.py dbshell'] it shows "CommandError: You appear not to have the 'mysql' program installed or on your path." I don't know how to fix it. If I restore database command directly, it shows "django.db.utils.IntegrityError: Problem installing fixture '-': Could not load contenttypes.ContentType(pk=1): (1062, "Duplicate entry 'admin-logentry' for key 'django_content_type_app_label_model_76bd3d3b_uniq'")". So, what should I do to restore the database contents ? -
Is it okay to use Function Based Views and Class Based Views Combined in a Django Project?
I am actually working in a project in Django, let's say i want to add a new patient to my database, we are collecting all its data but there is a field in that patient model which requires to insert their relatives info, Parents, sons and so on, for that i want to show two forms in that view, one to create the patient own info and other to create their relatives and link those relatives to the patient, i've been looking for how to show two forms in a class based view but i can not find an answer is there any way or its impossible to do so? and my next question is... is correct to use a function based view to show my forms and use detail views, to show info, updateview to update a patient for example, a deleteview? -
Django Object Sorting Changer
I am working on a project so that I can learn django. I have a model with an image, name field, and birthday field and I am just displaying them as 'cards'. I have them displayed properly now and can sort them with the dictsort in my view template. How can I add functionality to switch sorting methods (name, birthday..). I'm wanting to use some radio buttons at the top of my page that will allow the user to change sorting methods. Would I implement this with django forms? Here's the code that sorts my cards {% for villager in villager_list|dictsort:"birthday" %} -
Slicing a object_list in Django template
I want to slice object_list to display the result which I have attached. layout I'm not sure where I have to write a slice. This is the code I wrote. in list_html {% include "layout.html" with object_list=object_list number_of_columns=4 %} layout.html <div class="flex"> {% for object in object_list %} {% if forloop.counter0|divisibleby:number_of_columns and not forloop.first %} </div> <div class="flex"> {% endif %} <div class="grid grid-cols{% widthratio 12 number_of_columns 1 %}"> {% getattribute object attribute %} </div> {% endfor %} </div> What should I do? Can anyone help me? Thank you very much -
Why Django makes 2 inner joins with AND clauses instead or a single inner join with OR?
Good evening to all, I'm following the django docs on making queries, and this example showed up: Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008) I was hoping that the corresponding SQL query to this involved only one inner join and a OR clause, since the corresponding results are entries that either satisfy one or both of the conditions. Nevertheless, this is what an inspection to the queryset's query returned: >>> qs = Blog.objects.filter(entry__headline__contains='Hello').filter(entry__pub_date__year=2008) >>> print(qs.query) SELECT "blog_blog"."id", "blog_blog"."name", "blog_blog"."tagline" FROM "blog_blog" INNER JOIN "blog_entry" ON ("blog_blog"."id" = "blog_entry"."blog_id") INNER JOIN "blog_entry" T3 ON ("blog_blog"."id" = T3."blog_id") WHERE ("blog_entry"."headline" LIKE %Hello% ESCAPE '\' AND T3."pub_date" BETWEEN 2008-01-01 AND 2008-12-31) You can see that it makes TWO inner joins. Wouldn't the result be the same as: SELECT "blog_blog"."id", "blog_blog"."name", "blog_blog"."tagline" FROM "blog_blog" INNER JOIN "blog_entry" ON ("blog_blog"."id" = "blog_entry"."blog_id") WHERE ("blog_entry"."headline" LIKE %Lennon% ESCAPE '\' OR "blog_entry"."pub_date" BETWEEN 2008-01-01 AND 2008-12-31) ? And this later query AFAIK is faster. (added line breaks for readability) -
django stripe Fetch promise with pending state
I'm new to Stripe, so just following the stripe docs to setup a subscription feature for my website. I have hit major road blocks and not able to find any resource or similar questions to address it. Any help is appreciated. For the front-end portion of the code, it looks like the fetch is submitting data, but its state remains 'pending'. So, either no form is being submitted or the form is submitted but not received in the server-side. Here is my front-end code <!-- HTML Form --> {####################### CREDIT CARD (STRIPE) #######################} {% if credit_card %} <div class="credit-card"> <h3>Your Credit Card Information</h3> <form id="subscription-form">{% csrf_token %} <div id="card-element" class="MyCardElement"> <!-- Elements will create input elements here --> </div> <!-- We'll put the error messages in this element --> <div id="card-errors" role="alert"></div> <button type="submit" class="btn btn-primary btn-block mt-3">Subscribe</button> </form> </div> {% endif %} Then, in my checkout.js file: var stripe = Stripe('<testPublishableKey>'); var elements = stripe.elements(); var submissionURL = document.querySelector("[data-redirect]").getAttribute('data-redirect'); var customerEmail = document.querySelector("[data-email]").getAttribute('data-email'); var style = { base: { color: "#32325d", fontFamily: '"Helvetica Neue", Helvetica, sans-serif', fontSmoothing: "antialiased", fontSize: "16px", "::placeholder": { color: "#aab7c4" } }, invalid: { color: "#fa755a", iconColor: "#fa755a" } }; var cardElement = elements.create("card", { … -
Gdal GeoDjango Windows : “django.contrib.gis.gdal.error.GDALException: OGR failure.”
I use Windows 10 (x64), Python 3.8, Django 3.0.5 ,QGIS3.10 after installing geodjango and osgeo4w, when I run the code I could access to the map (leaflet) and add a marker to it but when I am trying to see the mark that I already marked and the title of it I got an error like that django.contrib.gis.gdal.error.GDALException: OGR failure I have tried looking at similar questions, but none of the solutions have worked. by the way, Also, i have added to my Django project settings: if os.name == 'nt': import platform OSGEO4W = r"C:\OSGeo4W" if '64' in platform.architecture()[0]: OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj" os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH'] Full traceback: Internal Server Error: /admin/firstproject/incidence/5/change/ Traceback (most recent call last): File "C:\Users\M-ALMASRI\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\M-ALMASRI\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\M-ALMASRI\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response response = response.render() File "C:\Users\M-ALMASRI\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\M-ALMASRI\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\response.py", line 83, in rendered_content return template.render(context, self._request) File "C:\Users\M-ALMASRI\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\M-ALMASRI\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 171, … -
TypeError: 'Review' object is not iterable Django Object not iteratble
I am trying to get all object from a many to many field in my course model and filter them based on the course code. Basically, I am trying to return all the reviews for courses with same course code. But I get the error: TypeError: 'Review' object is not iterable and it returns nothing. When I print it out I get: ]> which is a query set but I do not know why it is not returning anything in my course model I have the method: def get_reviews(self): return Course.course_reviews.through.objects.filter(course__course_code=self.course_code,course__course_university=self.course_university,course__course_instructor=self.course_instructor) and the many to many link with review model is: course_reviews = models.ManyToManyField(Review, blank=True, related_name='course_reviews') Why isnt it returning anything in my template? I am confused on what the issue is here. -
Create new for loop from for loop in Django
If you look at the piece of code below, you will understand exactly what I want. Enough even if I only get the number of cars that comply with this condition. Or it would be great if we could create a new loop from cars that comply with this condition. {% for car in cars %} {% if car.color == 'white' %} create new for loop from white cars or give me the numbers of white cars {% endif %} {% endfor %} -
upgraded from django 1.1 to 2.2, - (error) post_detail_view() got an unexpected keyword argument 'day'
(models.py) from django.utils import timezone class Post(models.Model): publish=models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse ('post_detail',args= [self.publish.year,self.publish.strftime('%m'),self.publish.strftime('%d'),self.slug]) views.py def post_detail_view(request,year,month,post): post=get_object_or_404(Post,slug=post,status='published',publish__year='year',publish__month='month',publish__day='day') return render(request,'blog/post_detail.html',{'post':post}) ** gives error as -- post_detail_view() got an unexpected keyword argument 'day' please help url.py re_path('(?P\d{4})/(?P\d{2})/(?P\d{2})/(?P[-\w]+)/$',views.post_detail_view,name='post_detail') -
Django SECRET_KEY setting must not be empty with github workflow
I have a GitHub workflow for Django and when it gets to migrating the database it gives the error django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. the secret key is stored in a .env file and loaded with from dotenv import load_dotenv load_dotenv() from pathlib import Path env_path = Path('.') / '.env' load_dotenv(dotenv_path=env_path) SECRET_KEY = os.getenv("secret_key") when I run manage.py on my PC it loads the key and runs the server, but GitHub gives the error above. How do I stop this error from happening? -
Django: How to separate model choices and display based on user input?
basically I have a form, in which I select a Make and Model etc. Inside my models.py I have this: MAKES = ( ('', ''), ('FORD', 'Ford'), ('AUDI', 'Audi'), ) MODELS = ( ('', ''), ('CMAX', 'C-Max'), ('FOCUS', 'Focus'), ('A3', 'A3'), ('A4', 'A4'), ) class Query(models.Model): MAKE = models.CharField(max_length = 50, choices=MAKES) MODEL = models.CharField(max_length = 50, choices=MODELS) class Average(models.Model): class Meta: db_table = 'ford_cmax' make = models.CharField(max_length = 15) model = models.CharField(max_length = 20) forms.py MAKE = forms.ChoiceField(choices=MAKES, required=True ) MODEL = forms.ChoiceField(choices=MODELS, required=True ) class Meta: model = Query fields = ['MAKE', 'MODEL'] Once I go onto the website, I am able to select Ford A3 or Audi Focus for example, how can I prevent this and display the Model choices based on the selected Make? So for example when I select Ford as the make, I'd only have two choices (C-Max , Focus) rather than all 4. -
Proxy backend through frontend using istio or nginx
I'm trying to figure out the best way to integrate Istio into my app, which consists of a React frontend (served by Nginx) and a Django Rest Framework API. I was able to get it to work using the following nginx config and istio-specific kubernetes files: server { listen 80; root /app/build; location / { try_files $uri $uri/ /index.html; } } # Source: myapp/gateway.yaml apiVersion: networking.istio.io/v1alpha3 kind: Gateway metadata: name: myapp-gateway spec: selector: istio: ingressgateway # use istio default controller servers: - port: number: 80 name: http protocol: HTTP hosts: - '*' - port: number: 443 name: https protocol: HTTP hosts: - '*' --- # Source: myapp/virtual-service.yaml apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: myapp spec: hosts: - '*' gateways: - myapp-gateway http: - match: - port: 80 route: - destination: host: frontend-svc port: number: 80 - match: - port: 443 route: - destination: host: backend-svc port: number: 8000 And the frontend can hit the backend at localhost:443. Note, I'm serving the backend on port 443 (instead of 8000) because of some issue regarding the istio gateway not working with any port other than 80 and 443. Regardless, this approach exposes BOTH the frontend and backend outside of the cluster, which … -
Model object that's currently being edited via admin interface appears in the popup window for add related object
I have two models that, for simplicity, I'll call Post (as in a blog post) and Tag (as in tags used to categorize blog posts). Tags are related to Posts via a ManyToManyField. Users can assign tags to posts. I also use an inline so that tags can be added or created from posts within the built-in admin interface. But a problem arises if a user clicks "Add another Tag-post relationship", clicks the "+" to add another tag from within the change post form (using the popup window), then assigns that tag to the post they're already editing. Example: In the "change post" form of the admin interface, under the tag inline section, user clicks "Add another Tag-post relationship". User clicks "+" to add another tag. New window pops up with create tag form. User names this tag "Demo Tag". In this form, the user selects the "Demo Posts" post under the posts field. User saves the tag which closes the window. "Demo Tag" now appears under the select box in the tag inline. When the post is now saved, this results in the validation error: Tag-post relationship with this Tag and Post already exists. This is because the user … -
Save new user in django user model and custom user model
Having trouble saving both the user to the built-in auth_user django model and my custom user model. My code saves the user to the django model but not my Account model. models.py class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=10) addressNumber = models.CharField(max_length=20) accountImage = models.CharField(max_length=999) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): address = forms.CharField(max_length=255) addressNumber = forms.CharField(max_length=255) image = forms.CharField(max_length=255) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'address', 'addressNumber', 'image' ) and views.py from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect from myAccount.forms.userForm import AccountForm from myAccount.models import Account from myAccount.forms.forms import SignUpForm def register(request): form = SignUpForm(data=request.POST) if request.method == 'POST': if form.is_valid(): account = form.save() account.refresh_from_db() # load the profile instance created by the signal account.address = form.cleaned_data.get('address') account.addressNumber = form.cleaned_data.get('addressNumber') account.addressImage = form.cleaned_data.get('accountImage') account.save() raw_password = form.cleaned_data.get('password1') return redirect('login') return render(request, 'myAccount/register.html', {'form': form}) @login_required def seePurchasehistory(request): return render(request, 'myAccount/pruchaseHistory.html') @login_required def accountInfo(request): account = Account.objects.filter(user=request.user).first() if request.method == 'POST': form = AccountForm(instance=AccountForm, data=request.POST) if form.is_valid(): account = form.save(commit=False) account.user = request.user account.save() return redirect('homepage-index') return render(request, 'myAccount/accountInfo.html', { 'form': … -
XMLHttpRequest Blocked: CORS Header problem with Django Project running with WSGI on bitnami / lightsail
I'm requesting a Django json view from an angular app. I'm using django-cors-header. Everything worked on AWS ec2. Now I moved to AWS lightsail (bitnami), and the browser shows the message Access to XMLHttpRequest at 'https://serve.myapp.de/search/' from origin 'https://myapp.de' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. I added myapp.de to CORS_ORIGIN_WHITELIST, and I tried to use CORS_ORIGIN_ALLOW_ALL option of django-cors-headers library, But it changes nothing. I had to add Header set Access-Control-Allow-Origin "https://myapp.de" Header set Access-Control-Allow-Methods "GET, OPTIONS, POST, PUT" Header set Access-Control-Allow-Headers "origin, x-requested-with, content-type, accept, authorization" Header set Access-Control-Allow-Credentials "true" To my apache config to get it running. And now django-cors-header does nothing anymore. It seems to me, like the apache does not give the CORS information to the django app. Do I have to add a specific apache config, to give the CORS infos to the django app? What is wrong? On all other servers this worked without a problem. -
Streaming a large file with Django
How to serve multiple files in a zip with Django? I can serve a single file with FileResponse: >>> from django.http import FileResponse >>> response = FileResponse(open('myfile.png', 'rb')) but, what if I need to send multiple files? How to generate a zip immediately? Imagine 3,000 images of 5 MB each. Note: this is a self-answer question, and the repos are mine. I had this problem a few weeks ago and couldn't find the right answer. -
django no such column: userdash_assetlist.user_id
I am trying to access my view page/template when I get the following error. no such column: userdash_assetlist.user_id I am pretty sure it is failing to access the object here. {% for td in user.assetlist.all %} I'm not sure what I broke. It was working under a previous config and broke at some point during changes. $ cat userdash/templates/userdash/view.html {% extends 'userdash/base.html' %} {% block title %} View Assets page {% endblock %} {% load crispy_forms_tags %} {% block content %} <h3>Your Assets Page</h3> {% for td in user.assetlist.all %} <p><a href="/{{td.id}}">{{td.name}}</a></p> {% endfor %} {% endblock %} $ cat userdash/models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class AssetList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="assetlist", null=True) name = models.CharField(max_length=200) def __str__(self): return self.name class Items(models.Model): assetlist = models.ForeignKey(AssetList, on_delete=models.CASCADE) user_asset = models.CharField(max_length=300) sell_asset = models.BooleanField() def __str__(self): return self.user_asset $ cat userdash/views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .models import AssetList, Items from .forms import CreateNewTrade # Create your views here. #def index(response): # return HttpResponse("<h1>Hello Dark World!</h1>") def userdash(response, id): ls = AssetList.objects.get(id=id) if response.method == "POST": print(response.POST) if response.POST.get("save"): for item in ls.items_set.all(): if response.POST.get("c" + str(item.id)) == …