Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Search bar for django
I have a page where the staff is able to see the staff they have enter, but if the lists get too long, it is hard to find the stuff they wanted, hence, I want to create a search bar and a button so that they can search for the stuff easily and display it in a card form as shown below, how do I do that? This is how my website looks like (in the url it will show q=76464 but it just wont display q=76464) views.py def outgoinggallery(request): user = request.user query = request.GET.get('q') category = request.GET.get('category') if category == None: alloutgoinglru = OutgoingLRU.objects.filter(category__user=user) else: alloutgoinglru = OutgoingLRU.objects.filter( category__name=category, category__user=user) if query: return OutgoingLRU.objects.filter(title__icontains=query) else: return OutgoingLRU.objects.all() categories = Category.objects.filter(user=user) context = {'categories': categories, 'alloutgoinglru': alloutgoinglru} return render(request, 'Outgoing/outgoinggallery.html', context) outgoinggallery.html {% extends "logisticbase.html" %} {% block content %} <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <style> td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; border-radius: 15px; } .image-thumbail { height: 200px; object-fit: cover; } .list-group-item a { text-decoration: none; color: black; } </style> <br> <div style="padding-left:16px"> <div class="row"> <div class="col-md-9"> <div class="row"> <h5>View Outgoing LRU</h5> <div class="col-md-7"> <form method="GET" action="" id="searchform"> <input … -
Django compress string data
I have a django model having: raw_data = models.TextField(_("raw_data"), default='') It just storing some raw data which can be 1K - 200K. I have 50 millions rows. I need to decrease size of data in database. How can I tell what consume most data over all database ? Should I use a string compression before storing the data ? 2.1 I saw here: Text compression in PostgreSQL that it get compressed anyway, is that true ? 2.2 I did some python code compression, I am not sure if changing bytes to string type can cause in lossing data: def shrink_raw_data(username): follower_data = get_string_from_database() text = json.dumps(follower_data).encode('utf-8') # outputs as a bytes # Checking size of text text_size = sys.getsizeof(text) print("\nsize of original text", text_size) # Compressing text compressed = str(zlib.compress(text, 9)) # store String in database # Checking size of text after compression csize = sys.getsizeof(compressed) print("\nsize of compressed text", csize) # Decompressing text decompressed = zlib.decompress(compressed) # Checking size of text after decompression dsize = sys.getsizeof(decompressed) print("\nsize of decompressed text", dsize) print("\nDifference of size= ", text_size - csize) follower_data_reload = json.loads(decompressed) print(follower_data_reload == follower_data) I am not sure about "str(zlib.compress(text, 9))" since my data is stored as string in … -
Why does my ModelForm with CheckboxSelectMultiple widget not validate?
I have a SelectCategoryForm which renders a queryset of Model Category that stores the different categories. The Model UserCategoryFilter stores the filter selected and saved by a user. # Form class SelectCategoryForm(forms.Form): choices = forms.ModelMultipleChoiceField(queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple) # Models class Category(models.Model): poller_category = models.CharField(max_length=30) category_color = models.CharField(max_length=15, blank=True) def __str__(self): return str(self.poller_category) class UserCategoryFilter(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) categories_selected = models.ForeignKey(Category, on_delete=models.CASCADE) # View @require_POST def save_category_filter(request): # User logged in? if request.user.is_authenticated: # Get the form instance filter_form = SelectCategoryForm(request.POST) # Form validation if filter_form.is_valid(): Now when I select some categories in the template and submit, the view validates the form as invalid. -
type object 'ArticleSitemap' has no attribute 'filter' Sitemap
I am working with the Django sitemap framework. Trying to improve SEO stuff for my blog, I have expanded my Article model in models.py and introduced sitemaps.py in one of the Django apps named MArticles. But I have faced an Attribute Error: type object 'ArticleSitemap' has no attribute 'filter'. Below are my python files. In sitemaps.py from django.contrib.sitemaps import Sitemap from .models import Article class ArticleSitemap(Sitemap): changefreq = "weekly" priority = 0.8 def items(self): return Article.modelmanager.all() def lastmodified(self, obj): return obj.last_updated In models.py from django.db import models import datetime from EHub.models import * from django.contrib.auth.models import User from django.utils import timezone from django.urls import reverse from mptt.models import MPTTModel, TreeForeignKey from taggit.managers import TaggableManager from ckeditor_uploader.fields import RichTextUploadingField # Create your models here. class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return str(self.name) class IpModel(models.Model): ip=models.CharField(max_length=100,null=True) def __str__(self): return str(self.ip) class Article(models.Model): options=( ('draft','Draft'), ('published','Published'), ) def get_absolute_url(self): return reverse('MArticles:article_detail',kwargs={'pk':self.id,'slug':self.slug}) class CustomManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status ='published') title=models.CharField(max_length=250,null=True) thumbnail = models.ImageField(upload_to="thumnails/%y",null=True,blank=True) description = RichTextUploadingField(null=True,blank=True, config_name='sourcecode',) author=models.ForeignKey(User,on_delete=models.CASCADE,related_name='blog_posts') slug=models.SlugField(null=True,unique=True) tags=TaggableManager() category = models.ManyToManyField(Category,blank=True) publish_date = models.DateField(default = datetime.date.today) last_updated=models.DateTimeField(default=timezone.now) views=models.ManyToManyField(IpModel,related_name="post_views",blank=True) featured = models.BooleanField(default=False) status=models.CharField(max_length=10,choices=options,default='draft') previous_post = models.ForeignKey('self', related_name='previous', on_delete=models.SET_NULL, blank=True, null=True) next_post = models.ForeignKey('self', related_name='next', on_delete=models.SET_NULL, blank=True, null=True) objects = models.Manager() modelmanager = … -
Something wrong with django json serializer
i try looking for answers but so far to no avail, basically i try to return django model as json however, it seem that the serializer convert it to string instead my code is as follow: view.py from django.shortcuts import render from screener.models import maintable from .models import Messages from django.http import JsonResponse from django.core import serializers from datetime import datetime import json def infiniteScroll(request, room_name): dateFilter=request.GET.get('date') dateFilter=dateFilter[5:len(dateFilter)-4] dateFilter=datetime.strptime(dateFilter, '%d %b %Y %H:%M:%S') data=serializers.serialize('json', reversed(Messages.objects.filter(room=room_name).filter(date_added__lt=dateFilter).order_by('-date_added')[:2])) return JsonResponse(data, safe=False) urls.py from django.contrib import admin from django.urls import path from . import views app_name='chat' urlpatterns = [ path('<str:room_name>/', views.room, name='room'), path('<str:room_name>/hist/', views.infiniteScroll, name='infiniteScroll'), ] when i go to the site http://127.0.0.1:8000/chat/AAPL/hist/?date=Thu,%2023%20Sep%202021%2014:03:42%20GMT the result is a page with string instead: "[{\"model\": \"chat.messages\", \"pk\": 118, \"fields\": {\"username\": \"adiputra12\", \"room\": \"AAPL\", \"content\": \"hello\", \"date_added\": \"2021-09-23T13:54:30.043Z\"}}]" how can I return json instead like shown below: [{'model': 'chat.messages', 'pk': 118, 'fields': {'username': 'adiputra12', 'room': 'AAPL', 'content': 'hello', 'date_added': '2021-09-23T13:54:30.043Z'}] -
Django Pass urls args directly to template like TemplateView, but with DetailView
I have a detail view. I require to be able to have url args in the template like what TemplateView does, e.g. if I have the following url: views.FooView.as_view(), {'page_title':'Foos of the world'}, name='foo',), Then in the template, it expects 'page_title' from the context, not view.kwargs.page_title (due to the whole sites framework). I think I tracked down the mixin for attaching urls args directly in the context to ContextMixin, However when I try add the mixin to the DetailView, e.g. class FooView(ContextMixin, DetailView): I get an error: TypeError: Cannot create a consistent method resolution order (MRO) for bases ContextMixin, DetailView I think DetailView inherits from ContextMixin, in which case why does it not provide the functionality? -
Django Question matching query does not exist
I have two models for Question and Answer, every question has several answers from the authenticated users, now i want a user can delete a specific answer that is related to him, my question has slug, and also for answers i have id field, i want to delete that answer according to the id, i have created a simple code and i think that is not correct, when i click on delete answer button i am receiving this error. ( raise self.model.DoesNotExist( questions.models.Question.DoesNotExist: Question matching query does not exist.) models.py from django.db import models from django.conf import settings class Question(models.Model): created_at = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length = 250) body = models.TextField() slug = models.SlugField(max_length = 250, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="questions") def __str__(self): return self.title class Answer(models.Model): created_at = models.DateTimeField(auto_now_add=True) description = models.TextField() question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="answers") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.author.username This code is for listing all the answers that is related to the question, and in here at the bottom i have a button for deleting the specific answer. <div class="container"> {% for answers in answer_list%} <div class="card mt-4 py-3 shadow"> <div class="card-body"> <p class="card-text">{{answers.description}}</p> <div class="row"> <div class="col col-md-auto"> Answered By: {{answers.author.username}} … -
Send Form back and from two views in Django
I am making a project that involves users being able to write inside a Form and then save it as a markdown file. I need to find a way to show the user how does the markdown he is currently writing would look already once parsed; this would be shown on a separate static page with a return button to go back to writing. This last part is giving me problems since I manage to show the user how his file would look like yet I haven't been able to find a way to render it back to the original entry form where it came from Preview HTML {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} <h1>Preview</h1> <h3>{{title}}</h3> <hr> {{preview|safe}} <form action="{% url 'new_entry' %}" method="POST"> {% csrf_token %} <input type="submit" name="return" value="Return"> </form> {% endblock %} New Entry HTML {% block title %} Encyclopedia {% endblock %} {% block body %} <h1>New Entry</h1> <div class="form-group"> <form action="{% url 'new_entry' %} " method="POST"> {{form.as_table}} {% csrf_token %} <input type="submit" value="Save" name="submit"> <input type="submit" value="Preview" name="preview"> </form> </div> {% endblock %} Views for Preview and New HTML def preview(request): #Retrieve data from the … -
how to copy my my production app data into my local host app
I deployed an app on Heroku and I have same app in my local machine now i want to copy all my deployed app data on my local app to so is there any way to do it anyway that will be very helpful because I don't know how to copy all my production data and paste it into my local machine I am using default sqlite3 Django default database -
Django redirect to detail page after authentication
here is my code class UserProfileView(DetailView): template_name = 'main/userprofile.html' context_object_name = 'userprofile' model = ProfilePersonal # def dispatch(self, request, *args, **kwargs): # if request.user.is_authenticated: # pass # else: # return redirect('/accounts/login/?next=userprofile/6') # return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) comments_connected = Review.objects.filter(profile=self.get_object()).order_by('-date_created') context["comments"] = comments_connected context['comment_form'] = ReviewForm return context def post(self, request, *args, **kwargs): if request.user.is_authenticated: new_comment = Review(content=request.POST.get('content'), rating=request.POST.get('rate'), profile=self.get_object(), user = self.request.user) else: return redirect(f'/accounts/login next=userprofile/{self.get_object()}') new_comment.save() return self.get(self, request, *args, **kwargs) Everything works fine except for the fact that if a user try to drop a comment and the user is not login in he will be be redirected to the login page but after authentication i want to redirect the user the user detail page where he was redirected from. for example if i was redirected from 127.0.0.1:8000/userprofile/6 after logging in i should be redirected to 127.0.0.1:8000/userprofile/6 in order to continue with what i was doing -
Django & Cassandra: How to give choice field to a model with Django Cassandra engine?
Hey guys I am new to Cassandra and was trying to integrate it with Django with Django Cassandra engine package. I have a choice field with some types like, TYPE = [('1', '1'), ('2', '2'), ('3', '3'),] with postgres, I can use a CharField with choices, but how can I achieve the same with Cassandra? Can anyone provide some hints? Thanks in advance. -
How to retrieve foreign field name in Django Rest Framework
I have 2 models one for a user and another for associated files for the user Models.py class IndividualUser(models.Model): membership_id = models.CharField(primary_key=True, max_length=100, default=1) profile_image = models.ImageField(blank=True, upload_to ="individual_member_profile/", null=True) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) class MemberCatalogue(models.Model): membership_id = models.ForeignKey(IndividualUser, default=None,on_delete=models.CASCADE, related_name="member_catalogue") files = models.FileField(upload_to="individualmembercatalogue/") Currently Iam getting absolute path for files. I need a filename uploaded by user for which Iam trying to get "files" field and and then split it with "/". But Iam struggling to get the files field from MemberCatalogue. My serializers look like this at the moment: class MemberCatalogueSerializer(serializers.ModelSerializer): files = serializers.FileField() class Meta: model = MemberCatalogue fields = ['id','membership_id', 'files'] class IndividualMembersSerializer(serializers.ModelSerializer): member_catalogue = MemberCatalogueSerializer(many=True) filename = serializers.SerializerMethodField('get_filename') def get_filename(self, obj): return obj.individualmember.files class Meta: model = IndividualMembers fields = "__all__" But I cant get the desired output. Expected output is like { "membership_id": "142369ca1b1484d8d9d6d87fdc8543db", "member_catalogue": [ { "id": 156, "membership_id": "142369ca1b1484d8d9d6d87fdc8543db", "files": "http://127.0.0.1:8000/individualmembercatalogue/some_file.pdf" "filename" : "some_file.pdf" } ], "profile_image": null, "firstname": "John", "lastname": "Doe", } -
File download in Django template
I am trying to download a file, but getting the download in html format, how I can get the file in its on format class Certificate(models.Model): name = models.CharField(max_length=80, blank=True, null=True) cert = models.FileField(upload_to='cert/', blank=True, null=True) def download_link(self): self.cert.url <a href="{{ obj.download_link }}" download> Download File</a> Tried the following way also but still in html format def download_link(self): path = self.cert.path filename = 'download.extension' fl = open(path, 'r') mime_type, _ = mimetypes.guess_type(path) response = HttpResponse(fl, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % filename return response -
how to test a unit test using pytest django if there is a function defined but not the class?
@api_view(['GET']) def get_search(request): search_text = get_searchText() return Reponse({"search-txt":search_text}) here, search_txt is an api for searching the text,and search_text is a variable I tried below but was unable to test the above code, from django.test import TestCase, Client class TestViews(TestCase): def setUp(self): self.client = Client() self.searchtxt_url = reverse('search-txt') def test_search_project(self): response.self.client.get(self.searchtxt_url) self.assertEquals(response.status_code, 200) what can be a possible way to test a function with api -
Django large queryset return as response efficiently
I have a model in django called "Sample" I want to query and return a large number of rows ~ 100k based on filters. However, it's taking up to 4-5 seconds to return the response and I was wondering whether I could make it faster. My current code looks like this: @api_view(['POST']) def retrieve_signal_asset_weight_ts_by_signal(request): #code to get item.id here based on request qs = Sample.objects.filter( data_date__range=[start_date, end_date], item__id = item.id).values(*columns_required) df = pd.DataFrame(list(qs), columns=columns_required) response = df .to_json(orient='records') return Response(response, status=status.HTTP_200_OK) Based on multiple test cases -- I've noticed that the slow part isn't actually getting the data from DB, it's converting it to a DataFrame and then returning as JSON. It's actually taking about 2 seconds just for this part df = pd.DataFrame(list(qs), columns=columns_required). Im looking for a faster way to convert queryset to a json which I can send as part of my "response" object! Based on this link I've tried other methods including django-pandas and using .values_list() but they seem to be slower than this, and I noticed many of the answers are quite old so I was wondering whether Django 3 has anything to make it faster. Thanks Django version : 3.2.6 -
I want user can change website language using drop-down without login but if they log in website should translate in their saved language preference
I am using a Django website in which a user can change their language using a drop-down menu. I use Django i18n for the translation of the website. Now problem is that I want a user can visit some pages of the website without login and they can change the language using a drop-down. But when a user logs in, the language of the website should change to the default language of that user's we store in their porifle section. How can I achieve this? language_form.html {% load i18n %} <form action="/i18n/setlang/?next={% url 'homepage' %}" method="post"> {% csrf_token %} <select name="language" style="padding: 4px 3px;"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_current_language_bidi as LANGUAGE_BIDI %} {% for language in LANGUAGES %} <option value="{{ language.0 }}"{% if language.0 == LANGUAGE_CODE %} selected {% endif %} "> {{ language.1 }} </option> {% endfor %} </select> {% for lang in aLANGUAGES %} {{lang.list}} {% endfor %} <input type="submit" value="Change language" style="padding: 3px 3px; margin-right: 10px;"> </form> The above code is my drop-down form for the select languages but I want user can select their preferred language in the profile section and that will be enabled automatically when they logged … -
How to correctly render a Multiplechoice ModelForm in Django
So I have two models, one to store categories and their related color and another one to store the categories selected by a user like so: # Models class Category(models.Model): poller_category = models.CharField(max_length=30) category_color = models.CharField(max_length=15) class UserCategoryFilter(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) categories_selected = models.CharField(max_length=2000) I now want to render out a MultipleSelectWidget so that the user can select categories to use as a filter. # Form class SelectCategoryForm(forms.ModelForm): choices = forms.ModelMultipleChoiceField(queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model = Category exclude = ["poller_category", "category_color"] How can I now render all of the categories and their associated color in the template? My below loop doesn't render any (Note: the form is passed to the context, if I use {{ select_form }} it renders the default one) # Template <!-- Filter form --> <div class="filter-form-wrapper"> <form method="post" action="."> {% csrf_token %} <div id="form-wrapper"> <ul> {% for item in filter_form %} <li style="color: {{ item.category_color }}">{{ item.poller_category }}</li> {% endfor %} </ul> <button class="save-button" type="submit">Save</button> </div> </form> </div> -
Django - Facebook ads (panel and targeted ads)
I would like to setup my web application so that users (businesses or other type of account) can run ads for the users (normal users) as Facebook based on user's interests, what approach should I take? Thanks! -
Django test parallel with 1 DB
I am trying to run my tests in parallel using manage.py test --parallel. By default this will use a different DB for each thread. Each process gets its own database Is it possible to only use one? Also is it a bad practice and why? -
How to loop in excel row with xlwt and django?
Here I am trying to export some report of customers in the excel format using xlwt. While exporting I am getting issue while rendering related products of customer. The current response I am getting is: The response I want is : response = HttpResponse(content_type="application/ms-excel") response["Content-Disposition"] = 'attachment; filename="report_detail.xls"' wb = xlwt.Workbook(encoding="utf-8") ws = wb.add_sheet(f"Report Detail", cell_overwrite_ok=True) row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = [ "Customer ID", "Products"] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) rows = [] for obj in qs: rows.append(obj.customer_id) prods = [(p.name, p.code) for p in obj.products.all()] rows.append(", ".join(map(str, prods))) for i, e in enumerate(rows, start=2): ws.write(int(i / 2), int(i) % 2, e) wb.save(response) return response -
Setting up a Test environment
I have currently dockerised my django+springboot application(development) and deployed in a remote server(Digital ocean). For testing purposes, I have cloned the applications and deployed at different ports. But the functionalities working in development server are getting reflected in Test server. Would like to know the general practice in cloning a development server for a test server -
How to lock the default choice without giving any options in DJANGO
I've been working with a model with has one the field as a choice field and multiple choices are provided. For eg-> The gender field is a choice field where users can choose from a drop down menu. But in a certain case, I only want the form to be open to female candidates, so the choices won't be shown, and the field will automatically be set as 'female' in the backend. How can I do this? Here are the code snippets from my code -> // models.py class RegisterUser(models.Model): GENDER_CHOICES= ( ( constants.MALE, constants.MALE_STR, ), (constants.FEMALE, constants.FEMALE_STR), ( constants.OTHERS, constants.OTHERS_STR, ), ) name = models.CharField(max_length=100) age = models.IntegerField(blank=True, null=True) college = models.CharField(max_length=100) gender = models.PositiveSmallIntegerField( choices=GENDER_CHOICES, default=constants.MALE ) // form.py class RegsiterForm(forms.Form): gender = forms.ChoiceField( label="Select Gender (default is Male)", widget=forms.Select( attrs={"class": "form-control", "placeholder": "Select Gender"} ), choices=GENDER_CHOICES, ) // views.py @login_required def publish_app_without_apk(request, **kwargs): template_name = "registerform.html" context = {} if request.method == "POST": form = form_class(request.POST) if form.is_valid(): name = form.cleaned_data.get("name") age = request.POST.get("age") college = request.POST.get("college") gender = request.POST.get("gender") -
What is the Best Way To Sync Multiple Database Table To Online Database using rest api
I have a software which store data in local sql server in multiple tables Want To give sync button and call api and transfer the data from local to live Software are install in multiple systems so it can happen data can transfer at same time what techniques i can use . So Server will not lack -
Django - Heroku - debug error 500 when deleting an object in Prod
Problem: Server Error 500 when trying to delete a user account in Prod. Scenarios: Delete a user account in Dev - works fine Create a user account in Prod - works fine Delete a user account in Prod - error 500 view.py: @login_required def account_destroy_view(request, id=None, *args, **kwargs): try: obj = request.user except request.user.DoesNotExist: raise Http404 if request.method == "POST": try: customer = StripeRecord.objects.get(user_id=obj.id) stripe.api_key = config('STRIPE_API_KEY') stripe.Customer.delete(customer.stripe_customer_id) except StripeRecord.DoesNotExist: pass obj.delete() return redirect("/") return render(request, "accounts/delete.html", {"object": obj}) accounts model.py: class User(AbstractUser): date_time = models.DateTimeField(default=datetime.datetime.now()) stripe model.py: User = settings.AUTH_USER_MODEL class StripeRecord(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) ... Heroku log: Sep 23 19:37:37 weatherapp app/web.1 10.1.24.136 - - [24/Sep/2021:02:37:36 +0000] "POST /delete/ HTTP/1.1" 500 145 "https://www.weatherapp.com/delete/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36 Edg/93.0.961.52" What I've tried & questions: I've checked Stripe logs, the object has been deleted on Stripe. So the issue isn't on the Stripe env var or integration. Tried to delete a user account directly using Django admin tool in Prod - still error 500. I suspect it's because I created the model with AbstractUser and it is a foreignkey to another model? How to get more details on the … -
HTML inserting extra characters into URL
I'm creating an ebay style website that auctions off items. I have a form that takes in the values for the listing required by the model. The form renders well but when I submit the form I get the error: <class 'TypeError'> views.py 80 ("l = Listing(title=title, description=description, url=url, user=user_id, category=category)") forms.py class NewListingForm(forms.Form): title = forms.CharField(max_length=200) description = forms.CharField(max_length=500) url = forms.URLField() bid = forms.DecimalField(decimal_places=2, max_digits=10) category = forms.ModelChoiceField(queryset=Category.objects.all()) views.py ** added around line that's throwing the error def newListing(request): try: if request.method == "POST": newListingForm = NewListingForm(request.POST) if newListingForm.is_valid(): title = newListingForm.cleaned_data['title'] description = newListingForm.cleaned_data['description'] url = newListingForm.cleaned_data['url'] bid = newListingForm.cleaned_data['bid'] category = newListingForm.cleaned_data['category'] current_user = request.user user_id = current_user.id **l = Listing(title=title, description=description, url=url, user=user_id, category=category)** l.save() b = Bid(price=bid, bid_count=0) b.listing.add(l) b.save() return HttpResponseRedirect(reverse("index")) else: newListingForm = NewListingForm() return render(request, "auctions/newListing.html", { 'form': newListingForm }) except Exception as exc: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print(exc_type, fname, exc_tb.tb_lineno) newListingForm = NewListingForm() return render(request, 'auctions/newListing.html', { 'form': newListingForm }) models.py class Listing(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=500) url = models.URLField() user = models.ForeignKey('User', on_delete=models.CASCADE, name='author') category = models.ForeignKey('Category', on_delete=models.CASCADE, name='category', default="") def __str__(self): return f'{self.id}: {self.title}' class Bid(models.Model): price = models.DecimalField(decimal_places=2, max_digits=10) bid_count = …