Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django datetime TypeError: fromisoformat: argument must be str
Internal Server Error: /api/orders/add/ Traceback (most recent call last):strong tenter image description hereext File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\views\generic\base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\rest_framework\decorators.py", line 50, in handler return func(*args, **kwargs) File "C:\Users\kalya\OneDrive\Desktop\my app\backend\base\views\order_views.py", line 31, in addOrderItems order = Order.objects.create( File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\query.py", line 514, in create obj.save(force_insert=True, using=self.db) File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\base.py", line 806, in save self.save_base( File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\base.py", line 857, in save_base updated = self._save_table( File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\base.py", line 1000, in save_table results = self.do_insert( File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\base.py", line 1041, in do_insert return manager.insert( File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\query.py", line 1434, in insert return query.get_compiler(using=using).execute_sql(returning_fields) File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\sql\compiler.py", line 1620, in execute_sql for … -
Postgresql is not getting data from CRUD form
I am new to POSTgreSQL and I have been making a CRUD code using django,python,html,and POSTgreSQL here's my code templates\employee_register\base.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Employee Register</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.min.js" integrity="sha384-VHvPCCyXqtD5DqJeNxl2dtTyhF78xXNXdkwX1CZeRusQfRKp+tA7hAShOK/B/fQ2" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css"> </head> <body> <div class="container"> <div class="col-md-10 offset-md-1 mt-5"> <div class="jumbotron"> <h1 class="display-4">Employee Register</h1> <p class="lead-front-italic">python django project for crud implementation</p> <hr class="my-4"> {% block content %} {% endblock content %} </div> </div> </div> </body> </html> employee_form.html {% extends "employee_register/base.html" %} {% load crispy_forms_tags %} {% block content %} <form action="" method="post" autocomplete="off"> {% csrf_token %} {{form.first_name|as_crispy_field}} {{form.middle_name|as_crispy_field}} {{form.last_name|as_crispy_field}} <!-- <div class="row"> --> <!-- <div class="col-md-4"> --> {{form.emp_code|as_crispy_field}} <!-- </div> --> <!-- <div class="col-md-8"> --> {{form.department|as_crispy_field}} {{form.designation|as_crispy_field}} {{form.location|as_crispy_field}} {{form.status|as_crispy_field}} {{form.date_of_birth|as_crispy_field}} {{form.date_of_joining|as_crispy_field}} {{form.gender|as_crispy_field}} <!-- </div> --> <!-- </div> --> <button type="submit" class="btn btn-success"> <i class="fa-solid fa-database"></i>Submit </button> </form> {% endblock content %} employee_register.html {% extends "employee_register/base.html" %} {% block content %} <p>we'll show list of employee from the table</p> {% endblock content %} models.py from django.db import models class Position(models.Model): title = models.CharField(max_length=50) def __str__(self): return self.title # Create your models here. class Employee(models.Model): first_name=models.CharField(max_length=100) middle_name=models.CharField(max_length=100) … -
Increase integer when an object is created in Django
Hello I have two models Teaching Semester and Enrollments , i wanted to count the number of students in a particular course. Practically i wanted to have a registered students field which will be increased everytime when Enrollments object is created. Here is my model for Teaching Semester class TeachingSemester(models.Model): department = models.ForeignKey(Department,on_delete=models.CASCADE) program = models.ForeignKey(Program,on_delete=models.CASCADE) faculty = models.ForeignKey(FacultyData,on_delete=models.CASCADE) semester_choices = ( ('Spring' , 'Spring'), ('Fall' , 'Fall'), ('Summer' , 'Summer') ) sem_choice = models.CharField(max_length=30,choices=semester_choices,default='Spring') course_date = models.DateField(default=datetime.date.today()) section = models.CharField(max_length=5,default = 1) faculty_course = models.ForeignKey(Course,on_delete=models.CASCADE) And model of Enrollments class Enrollment(models.Model): student = models.ForeignKey(StudentData,on_delete=models.CASCADE) faculty = models.ForeignKey(TeachingSemester,on_delete=models.CASCADE) -
In booking viewset I've to list all bookings when admin is logged in and normal user can see objects created by that particular user using id =pk
given are the views.py and models.py Here in my "class BookViewSet(viewsets.ModelViewSet)" and "class BookingRetrtieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView)" I need to create functionality given in the problem statement. Problem statement for (class BookViewSet(viewsets.ModelViewSet)) (a) If Admin is logged-in display all bookings of all users and can create bookings. (b) If a regular user logged in displays records created by that particular user and can create a user too. (c) at the time of API testing how to use the simple-jwt token to verify user as I've added permission for access control. for (class BookingRetrtieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView)) (a) if Admin is logged-in get/put/delete functionality for every user's booking. (b) if a regular user logged-in get/put/delete for that particular user booking records. Note: I've tried to do this without this functionality and simply using custom permission but it's not working maybe because it cannot get user identified. permissions.py from django.contrib.auth import get_user_model from rest_framework.permissions import BasePermission User = get_user_model() class IsUserOrIsAdmin(BasePermission): """Allow access to the respective User object and to admin users.""" def has_object_permission(self, request, view, obj): return (request.user and request.user.is_staff) or ( isinstance(obj, User) and request.user == obj ) Views.py from django.shortcuts import render from django.http import Http404, JsonResponse #from django.http import HttpResponse, JsonResponse from rest_framework.views import … -
How to get two models data in for loop with filter: Django
I do have two model as below, like patient details model and patient visit model. I want to list the visits of all patients (if exist). in views.py I am passing both models data by get all. how to filter and show it in the template by using for loop. I am using two for loop it shows total number of patient multiply total number of visit which is wrong.. class patientprofile(models.Model): pat_Fname = models.CharField(max_length=100) pat_Lname = models.CharField(max_length=100, blank=True) def IntegerField(self): return self.id class visits(models.Model): pat_ID = models.ForeignKey(patientprofile, on_delete=models.CASCADE) visit_date = models.DateField(blank=False, null=False) visit_time = models.TimeField(blank=False, null=False) views.py @login_requireddef visitslist(request): patpro=patientprofile.objects.all() vis=visits.objects.all() return render(request, 'pmp/visitslist.html', {'vis':vis, 'patpro':patpro}) Template as below {% for a in vis %} <tr> <td> {{ a.visit_time }} </td> <td>{{ a.visit_date }}</td> <td>{{ patpro.id }}</td> <td>{{ patpro.pat_Fname }}</td> </td> </tr> {% endfor %} -
Why submit didn't work in my jquery script?
My html and script is like below. It's using Django and it's a Django template but I think this is a issue not related to Django. It displays a list of dir or files(if any) which are arranged in ul and li elements. When I click on any list item(li element), I expect it will trigger a submit. I can saw the alert() window, but I didn't see the post request from the server side. I have a similar snippet in another place of my project and that works, but this don't. I can't think out what I had missed? <form id="id_f_sel" action="{% url 'integratedTest:addCase' %}" method="post"> {% csrf_token %} <input type="hidden" id="id_f_clked" name="f_clked" value=""> <ul id="id_dirlist"> {%for item in dirs %} <li><img src="{% static 'image/folder.png' %}" alt="unclicked folder image"> <span class="caret">{{item}}</span></li> {%endfor%} </ul> <ul id="id_flist"> {%for item in files %} <li><img src="{% static 'image/file.png' %}" alt="file image"> <span class="caret">{{item}}</span></li> {%endfor%} </ul> </form> <script> $(document).ready(function() { $('li').on('click', function() { clk_val = $(this).text() alert(clk_val) $('#id_f_clked').val(clk_val) $('#id_f_sel').submit() }); }); </script> -
Wagtail removes style of rich text when saving and rendering
I was trying to use TinyMCE for Wagtail as my rich text editor, but Wagtail seems to be not accepting style changes on elements, although it's shown in the section it disappears when I am trying to save the draft or preview it. TinyMCE Editor Source The actual HTML that was being saved -
django_embed_video module throws error "e doesn't look like a module path"
I have been 6 hours trying to figure out why doesn't the django_embed_video module work as supposed. I followed the documentation. Created a model with VideoEmbed Field. All i am trying to achieve is to view a youtube video in my template, but i keep getting this error: detect_backend(str(backend_or_url)) File "project\venv\lib\site-packages\embed_video\backends.py", line 61, in detect_backend backend = import_string(backend_name) File "project\venv\lib\site-packages\django\utils\module_loading.py", line 27, in import_stringraise ImportError("%s doesn't look like a module path" % dotted_path) from err ImportError: e doesn't look like a module path template.html ... {% load static %} {% load embed_video_tags %} ... {% for tid, t in tests.items %} <div class="embed-responsive embed-responsive-16by9"> <!-- Bootstrap responsive layout --> {% video t.ytvideo.url %} <!-- iterate tests and get YT video of each test --> </div> {% endfor %} -
django error 'context must be a dict rather than DataFrame'
I'm working on a translator program. I want the result to appear at the bottom of the original page when the user presses the 'Submit' button. I created a function in 'views.py' and returned the result in the form of a DataFrame (I checked that this Python code itself is fine) and I got an error called 'context must be a dictator than data frame'. I tried several ways to change it to dict format, but it only caused other errors. This is my 'views.py' code and 'urls.py' code. Please let me know if there is anything wrong. views.py class Postview(View): @csrf_exempt def success(request): content = request.POST.get('content') dict = pd.read_csv("C:\\Users\\user\\jeju-dialect-translation\\jeju\\dialect\\dict2.csv", sep=",", encoding='cp949') hannanum = Hannanum() okt = Okt() nouns = hannanum.nouns(content) stem = okt.morphs(content, stem = True) tempt=[] for i in range(0, len(stem)): if (len(stem[i]) == 1): tempt.append(stem[i]) adjective = list(set(stem) - set(tempt)) results = pd.DataFrame(columns = {'siteName', 'contents'}) for i in nouns: x = dict[dict['siteName'] == i] x = x[['siteName', 'contents']] results = pd.concat([results, x], axis = 0) for i in adjective: y = dict[dict['siteName'].str.match(i)] results = pd.concat([results, y], axis = 0) context = results.drop_duplicates() return render(request, 'dialect/trans_suc.html', context) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('dialect/', views.Postview.as_view(), name='main_page'), path('trans/', … -
Best way to change the primary key for a table in an existing project?
I have an existing Django project with some important data in the database. But I would like to change the primary key of the main table. How should I do it? (I am new to Django, so any newbie advice would be appreciated). I can do it the very manual way of: creating a new table as I wanted it to be create a python script importing models library and my specific models create a loop to copy all the entries from the old model into the new do the same with linked models that rely on the old primary key (updating the relation through the new primary key) delete old tables rename new updated tables to match old tables Is my approach correct? or is there a simpler way? Some questions: I know I can create custom "migration files" but I feel like doing it manually with Django creating the migration files would be easier. is that fine? would old connection (relying on unchanged keys) tables automatically recognize the new renamed table? or will something break if I delete the old table? if doing the above, should I remove the "on delete cascade" to avoid linked entries being deleted … -
How to fix home page rendering not working?
So I have urls to redirect the user to certain pages (form and home). I have one which you can click at the top of the home page which successfully redirects you to the form page and I have the same system to bring you back to the home page from the form page except it doesnt seem to work and displays an error. Error Image Here is my home html file which works : <div class="page-title-add-button-div"> <a class="page-title-add-button-link" href="/form"> + </a> </div> Here is my form file which doesnt work : <div class="page-title-add-button-div"> <a class="page-title-add-button-link" href="/home"> + </a> </div> Here is my views file : def home(request): litinfo = info.objects.all() return render(request, 'home.html', {'litinfo': litinfo}) def form(request): return render(request, 'form.html') And finally here is my urls.py file : urlpatterns = [ path('', views.home, name='home'), path('form', views.form, name='form'), ] Thanks in advance for any solutions, im new to django and just not too sure on how to fix this issue. Edit : I've figured out that when I click on the URL in the form page it sends me to "http://(Numbers, not sure if confidential)/home" instead of "http://(Numbers, not sure if confidential)" which means it doesnt bring me back to … -
Django Subquery is redoing all the work, how to reuse subqueries in django?
The resulting query of the following is horrible. Is there a way to reuse the query or create a raw sql for the same? watches = foo_fighters.annotate(pickup_id=Subquery(boo_event.values("id")[:1]), latest_customs_status=Subquery(boo_event.values("customs_status")[:1]), latest_customs_status_label=Subquery(boo_event.values("customs_status_label")[:1]), latest_hopping_line_status=Subquery(boo_event.values("hopping_line_status")[:1]), latest_hopping_line_status_label=Subquery(boo_event.values("hopping_line_status_label")[:1]), latest_tmf_status=Subquery(boo_event.values("tmf_status")[:1]), latest_tmf_status_label=Subquery(boo_event.values("tmf_status_label")[:1]), latest_lol_status=Subquery(boo_event.values("lol_status")[:1]), latest_lol_status_label=Subquery(boo_event.values("lol_status_label")[:1]), latest_bright_status=Subquery(boo_event.values("bright_status")[:1]), latest_bright_status_label=Subquery(boo_event.values("bright_status_label")[:1]), latest_ctf_status=Subquery(boo_event.values("ctf_status")[:1]), latest_ctf_status_label=Subquery(boo_event.values("ctf_status_label")[:1]), latest_love_status=Subquery(boo_event.values("love_status")[:1]), latest_love_status_label=Subquery(boo_event.values("love_status_label")[:1]), ) -
Django pages with similar structure but different components
I have a main webpage that displays and lists all the fruits (with description, price, etc) I sell. Now, I would like to have another page .../discount which displays and list all the fruits which are True for is_discount in one of my models. Essentially, the .../discount page is just a subset of the main page. They have the same page structure and everything, except the listings in .../discount page are discounted fruit items, whereas the mainpage can have discounted and non-discounted fruit items. How would I go about tackling this problem? Thanks in advance. -
Reverse for 'edit_blog_post' with arguments '('',)' not found
I am trying to create a way to edit individual blog posts from their individual html. Here are the relevant files and trace back. I am somewhat understanding that the issue lies in blog_post.id being due to the fact that blog_post has not carried over from the for loop on blog_posts.html. I have read up on others having this issue and they all structured their pages to have the edit button being inside the original for loop, which makes sense in hindsight. BUT now that I have run into this issue, I'm determined to understand how I can solve it without going back and restructuring my pages to align with the others I saw. urls.py from django.urls import path from . import views app_name = 'blogs' urlpatterns = [ # Home page path('', views.index, name='index'), path('blog_posts/', views.blog_posts, name='blog_posts'), path('blog_posts/<int:blog_post_id>/', views.blog_post, name='blog_post'), path('new_blog_post/', views.new_blog_post, name='new_blog_post'), path('edit_blog_post/<int:blog_post_id>/', views.edit_blog_post, name='edit_blog_post'), ] views.py from .models import BlogPost from .forms import BlogPostForm def index(request): """Home page for Blog.""" return render(request, 'blogs/index.html') def blog_posts(request): """Show all Blog Posts.""" blog_posts = BlogPost.objects.order_by('date_added') context = {'blog_posts': blog_posts} return render(request, 'blogs/blog_posts.html', context) def blog_post(request, blog_post_id): """Show details of an individual blog post.""" blog_post = BlogPost.objects.get(id=blog_post_id) title = blog_post.title id … -
How to make the a variable within a Django template's conditional show up every time it needs to?
I have a Django template with text that surrounds a variable. I want both the text and variable to show up when a listing is within the CloseListing model or if request.POST.get('close') has occurred. Currently, the variables show up once request.POST.get('close') has occurred but disappears if you go to another page within the web application and then return. The text surrounding it is always visible. I think the problem is with my logic but am unsure how to fix this. Does anyone know how to fix this? views.py @login_required(login_url='login') def listing(request, id): #gets listing listing = get_object_or_404(Listings.objects, pk=id) sellar = listing.user #close listing code if sellar == request.user: closeListingButton = True else: closeListingButton = False closeListing = '' try: has_closed = get_list_or_404(CloseListing, Q(user=request.user) & Q(listings=listing)) except: has_closed = False if has_closed: closeListing = False else: closeListing = True if request.method == "POST": #close listing code if request.POST.get('close'): CloseListing.objects.create(user=request.user, listings=listing) closeListing = True closeListingButton = False add_or_remove_watchlist = True winning_bid = Bids.objects.aggregate(Max('bid')) winning_bid = Bids.objects.latest('bid') winner = winning_bid.user return render(request, "auctions/listing.html",{ "auction_listing": listing, "comments": comment_obj, "bids": bid_obj, "closeListingButton": closeListingButton, "closeListing": closeListing, "closedMessage": "This listing is closed.", "winner": winner }) return render(request, "auctions/listing.html",{ "auction_listing": listing, "closeListingButton": closeListingButton, "closeListing": closeListing }) html {% … -
My ajax request in django redirects to another page containing my response data after submit
after submiting my ajax request, it redirects me to another empty page containing my returned data i wanted it to remain in the same page after submiting the form. here is my view VIEWS.PY def LikePost(request,pk,slug): model=Post post=Post.objects.get(pk=pk,slug=slug) #if request.is_ajax(): is_like=False for like in post.post_likes.all(): if like == request.user: is_like=True break if not is_like: post.post_likes.add(request.user) if is_like: post.post_likes.remove(request.user) notify=Notification.objects.create(notification_type='LP',user=post.publisher,sender=request.user,text_preview=" some one liked your post") notify.save() likes_count=post.post_likes.count() data={ 'likes_count':likes_count, } return HttpResponse(json.dumps(data),content_type='application/json' ) and my form <form method="POST" class="likeForm" action="{% url 'like-post' post.id post.slug %}" > {% csrf_token %} <input type="hidden" value="{{ request.path }}" name="next"> <button type='submit'>like</button> and my ajax call $.each('.likeForm').on('submit', function(event){ event.preventDefault(); event.stopPropagation(); $.ajax({ type:'POST', url:$('.likeForm').attr('action'), data:{ csrfmiddlewaretoken:"{{ csrf_token }}", datatype:'json', cache:false, async:true, }, success:function(data){ $.each('.counter').text(data.likes_count) }, failure: function(){ } }) return false }) keeps redirecting to an empty page any help for this? -
How can show categories products in home page?
I want to show my all products row by row on the home page category-wise. Suppose, before starting a new row will have a heading(category name) and then will show all products according to the product category and then again will be starting a new row with a heading according to category. How can I do it? I applied the 3/4 methods but didn't work. Bellow, I've shown one of the methods. It doesn't work properly. Please help me. views.py: def home(request): all_products = Products.objects.all() context ={ "all_products":all_products, } return render(request,'home.html', context) model.py: class Category(models.Model): title = models.CharField(blank=True, null=True, max_length = 100) def __str__(self): return str(self.title) class Products(models.Model): product_image = models.ImageField(blank=True, null=True, upload_to = "1_products_img") product_title = models.CharField(blank=True, null=True, max_length = 250) product_price = models.IntegerField(blank=True, null=True) offer_price = models.IntegerField(blank=True, null=True) created_date = models.DateTimeField(blank=True, null=True, auto_now=True) product_category = models.ForeignKey(Category, related_name="categoty_related_name", on_delete=models.CASCADE, blank=True, null=True) context_processors.py: from .models import Category def categories(request): return {"categories":Category.objects.all()} template: {% for products in all_products %} <h4 class="text-start montserrat_alternates_font ">{{products.product_category}}</h4> <hr> <!--- product card ---> <div class="col mb-5"> <div class="card h-100"> <!-- Sale badge--> {% if products.offer_price != None %} <div class="badge bg-dark text-white position-absolute" style="top: 0.5rem; right: 0.5rem"> SALE </div> {% endif %} <!-- Product image--> <img … -
Django admin: filter by min and max value
I would like to add a filter to my Django admin to filter based on a floating point with range in [0, 1]. Consider the following model: class Color(models.Model): label = models.CharField(max_length=255, unique=True) confidence = models.FloatField(null=True) The value of confidence is always between 0 and 1. I found pretty easy to add a filter based on the label attribute: class AnnotationAdmin(admin.ModelAdmin): list_filter = ( ("color__label", custom_titled_filter('Color')), # ("color__confidence", custom_titled_filter('Color Confidence')), ) How can I add a filter to select the maximum and minimum values for the color confidence? E.g. select all the colors with confidence between 0.5 and 0.6. As of now, the only solution I found is to create two different filter classes extending admin.SimpleListFilter and use one to select the maximum and another one to select the minimum. Is there anything easier, maybe supported by django out of the box? -
Error in making POST request to django API
From post man, I'm trying to make POST request to an order API created using django restframework but I'm getting the following error: product = Product.objects.get(id=i['product']) TypeError: string indices must be integers The specific point where the error is located is specified in the error but I find difficulty constructing VALID json for the request body. Here is how I'm making the request on postman: { "orderItems":{ "product": {"name":"abc", "brand":"def", "image"www.example.com/img", "description":"xyz", "price":"50"}, "qty":"2", "price":"200" }, "shippingAddress": { "address":"abc", "city":"B", "postalCode":"12345", }, "paymentMethod":"monify", "itemPrice":"100" } Here is the program: class Product(models.Model): category = models.CharField(max_length=50, choices=Categories.choices, default=Categories.medications) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name="user_product", null=True) name = models.CharField(max_length=150) brand = models.CharField(max_length=255, default="brand") productClass = models.CharField(max_length=50, null=True, blank=True) image = models.ImageField(upload_to="images/products/") label = models.CharField(max_length=254, default='', blank=True, null=True) price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) stock = models.IntegerField(null=True, blank=True, default=0) dateCreated = models.DateTimeField(auto_now_add=True) class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name="user_order", null=True) paymentMethod = models.CharField(max_length=200, null=True, blank=True) dateCreated = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.dateCreated) models.py class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) image = models.CharField(max_length=200, null=True, blank=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True, blank=True) qty = models.IntegerField(null=True, blank=True, default=0) price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) def __str__(self): return str(self.name) The view I', trying to … -
Django: name 'filter_name__icontains' is not defined
I am working on custom filter in my Django (DRF) app. Basic filtering (iexact) is working: queryset = queryset.filter(**{filter_name: term.get(filter_name)}) # OK But I want to filter CharFields with icontains logic: queryset = queryset.filter(**{filter_name__icontains: term.get(filter_name)}) # ERROR Error text NameError: name 'filter_name__icontains' is not defined Question: how can I support icontains filtering in my function? My code from django.db.models import QuerySet, CharField from rest_framework.filters import BaseFilterBackend from rest_framework.request import Request class AbstractFilterBackend(BaseFilterBackend): @staticmethod def __execute_default_filters(queryset, terms: list): for term in terms: filter_name = next(iter(term.keys())) if hasattr(queryset.model, filter_name): if queryset.model._meta.get_field(filter_name).__class__ is CharField: queryset = queryset.filter(**{filter_name__icontains: term.get(filter_name)}) else: queryset = queryset.filter(**{filter_name: term.get(filter_name)}) return queryset -
Django nested forms for foreign keys
I have the following Django models: class Color(models.Model): label = models.CharField(max_length=255, unique=True) class ColorAnnotation(models.Model): color = models.ForeignKey(Color) confidence = models.FloatField() def __str__(self): return f"{self.color.label} {round(self.confidence, 2) if self.confidence else None}" class Annotation(models.Model): color = models.ForeignKey(ColorAnnotation) Since I have a lots of records, Django Admin got really slow when loading a single record of the model Annotation because it tried to load all the possible values of __str__ for ColorAnnotation. I optimized using prefetch_related and select_related but it didn't work. I solved this creating a custom froms.ModelForm: class AnnotationForm(forms.ModelForm): color = forms.ChoiceField(required=False, choices=Color.objects.values_list('id', 'label')) class Meta: model = Annotation fields = '__all__' class AnnotationAdmin(admin.ModelAdmin): list_display = ("id", "color") list_filter = ( ("color__color__label", custom_titled_filter('Color')) ) form = AnnotationForm def get_queryset(self, request): queryset = super().get_queryset(request) return queryset.prefetch_related( 'color__color', ).select_related( 'color', ).all() This works well, but it doesn't show the attribute confidence of the ColorAnnotation instance of a given Annotation: . I would like to change this so that I have the dropdown menu for the Color, but with option of changing the confidence too. I was wondering if there is a way to create a custom forms.ModelForm for the model ColorAnnotation and use it as a nested form into AnnotationForm. -
Bundle input validation and business logic errors
We recently started to replace a long-running application with a new app using a modern technology stack, drf in the backend. So, everything is new, we were justin starting, but most reqirements are old. Today we got the requirement, that the client should display all field-validation errors and business logic validation errors (if possible to process) at the same time to the user when he was trying to do write operations. Additional note is that further validations are still to come and all need to run in one call. In summary: one post/put operation with a single response, which was heavily processed and contains all validation and business logic errors. Sounded uncomfortably to me or is this easy to implement? First thought was that we can write a custom_exception_handler which waits for a ValidationError, runs all business validations and enriches the response. But this handler will grow with each endpoint which needs extra validation. (And the current application is big.) Is there a better way? How do you feel about it? Does this violate good practices? Maybe the client should do field validation too and do async calls to extra validation endpoints so that it can guide the user to … -
get name attr value for formset with appropriate prefix and formset form index
I am manually displaying modelformset_factory values in a Django template using the snippet below. One of the inputs is using the select type and I'm populating the options using another context value passed from the view after making external API calls, so there is no model relationship between the data and the form I'm trying to display. view my_form = modelformset_factory(MyModel, MyModelForm, fields=("col1", "col2"), extra=0, min_num=1, can_delete=True,) template {{ my_form.management_form }} {% for form in my_form %} <label for="{{ form.col1.id_for_label }}">{{ form.col1.label }}</label> {{ form.col1 }} <label for="{{ form.col2.id_for_label }}">{{ form.col2.label }}</label> <select id="{{ form.col2.id_for_label }}" name="{{ form.col2.name }}"> <option disabled selected value> ---- </option> {% for ctx in other_ctx %} <option value="{{ ctx.1 }}">{{ ctx.2 }}</option> {% endfor %} </select> {% endfor %} The other_ctx populating the select option is a List[Tuple] I am trying to get the name value for the col2 input using {{ form.col2.name }} but only col2 is getting returned instead of form-0-col2. I could prepend the form-0- value to the {{ form.col2.name }} but wondering if: I could do the above automatically? I'm assuming the formset should be aware of the initial formset names with appropriate formset index coming from the view. Is there … -
Django Assign json to model object
I have this function: # create a function to upload an object one to one given a json def upload_object_values(model, json_values): if json_values: # the json values contain key value that match to the model # use a copy to avoid runtime error dictionary changing size for json_value in json_values.copy(): # remove all ids in model copy if json_value[-3:] == '_id' or json_value == 'id': json_values.pop(json_value) # copy the object values only # TODO: ASSIGN json_values to the model object # save # model.save() sample json_values: {'id': 1, 'notes': 'hello', 'name': 'world', 'phone': None, 'foreign_id': 2} sample cleanedjson_values (removed id and foreign keys): {'notes': 'hello', 'name': 'world', 'phone': None} How do I assign these values to the model that I have with each key being a field with the same name in my model? -
Code inside Django template if statement appears all the time
I have a Django template that contains a message with a variable, but the words that are not in the variable appear all the time. I think it has something to do with the conditional if closeListing == True. I explicably state when I want it to be True, so I don't know what's happening. views.py @login_required(login_url='login') def listing(request, id): #gets listing listing = get_object_or_404(Listings.objects, pk=id) sellar = listing.user #close listing code if sellar == request.user: closeListingButton = True else: closeListingButton = False closeListing = '' try: has_closed = get_list_or_404(CloseListing, Q( user=request.user) & Q(listings=listing)) except: has_closed = False if has_closed: closeListing = False else: closeListing = True if request.method == "POST": #close listing code if request.POST.get('close'): CloseListing.objects.create(user=request.user, listings=listing) closeListing = True closeListingButton = False add_or_remove_watchlist = True winning_bid = Bids.objects.aggregate(Max('bid')) winning_bid = Bids.objects.latest('bid') winner = winning_bid.user return render(request, "auctions/listing.html",{ "auction_listing": listing, "comments": comment_obj, "bids": bid_obj, "closeListingButton": closeListingButton, "closeListing": closeListing, "closedMessage": "This listing is closed.", "winner": winner }) return render(request, "auctions/listing.html",{ "auction_listing": listing, "closeListingButton": closeListingButton, "closeListing": closeListing }) listing.html {% if closeListing == True %} <div>{{ closedMessage }} <br> {{ winner }} has won the auction! </div> {% endif %}