Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What would be the most efficient way to iterate over two different models in django project
I am working on a django website. I am having a products page in my templates in which there are multiple categories and there are multiple products under each category. These are my models.py: class Category(models.Model): type=models.CharField(max_length=30) class Product(models.Model): category = models.ForeignKey(Category, on_delete = models.CASCADE) productid=models.CharField(max_length=30) name=models.CharField(max_length=30) and this is my current view.py: def category(request,sort): b="" if sort=="all": b="timeadded" elif sort=="new": b="-timeadded" context = { 'types' : Category.objects.all(), 'prods': Product.objects.filter().order_by(b), 'cartItems':[], } if request.user.is_authenticated: customer=request.user.customer order, created=Order.objects.get_or_create(customer=customer, complete=False) cartItems=order.get_cart_items, items=order.orderitem_set.all() context['list_cart'] = order.orderitem_set.values_list('product__id', flat=True) return render(request,"category.html",context) This view takes care of whether the product is already in customers cart or not. Currently to show these products I was iterating like this: {% for type in types %} {% for product in prods %} {% if product.type.id == type.id %}} //Display the details {% endif %} {% endfor %} {% endfor %} Initially this was working fine for me when I hadnt added many products but now when I was testing with around ~400 products it is loading up very slowly.The reason might be that I am iterating over all products for all categories. Please tell me a more efficient way to work this up which also keeps in mind whether … -
What is patching cycle on server and how does it affects my django app on automatic reboot?
I have a django app that i am going to upload on my institute's server . They had sent me a form asking for configurations and their is i question which says: "Your new server will be included in our standard O/S patching cycle which may require an automatic server reboot. Please indicate if that's not suitable ?" But i couldn't got what does that mean since i have little to know experience of deployment stuff. How the above mentioned "server patching" will affect my web app and should my everything just come back online on reboot ? Thanks in advance -
How much slower will my (Django) web app become if I put it in a wrapper to make it a hybrid app?
I build a responsive web app using Django and I would like to use a wrapper (like Cordova or PhoneGap) to be able to make my content available in the App Store and Play Store. But after having done some research I am having doubts. I read a lot about hybrid apps being slow and that it is difficult to resolve bugs. Is it worth it to build a wrapper for my web app? Or should I start learning to build a native app? -
What is wrong with the logic? Why is the output in console always "RENT"? python list loop
This code is a part of my Django view code where i'm taking a voice input and extracting parameters from them to perform query over my Model Database. output = "apartment for sale for exactly 45 lakh taka" #splitting the string command = output.split() #looping every element in command after the split() for j in range(len(command)): if command[j] == 'rent' or 'Rent': category = 'RENT' else: category = 'NUll' print(category) #Console Output = "RENT" #This is what appears in console when there is no 'rent' or 'Rent' in my input string #What should I do so that the code below works properly? #looping every element in command after the split() for j in range(len(command)): #Sould be False for the this command if command[j] == 'rent' or 'Rent': category = 'RENT' print(category) elif command[j] == 'sale' or 'Sale': #This should be True and Category should be assigned the value 'SALE' category = 'SALE' print(category) #Same happens for this as well. The Output in console is always "RENT" -
I want my success message in alert and error messages in span using django ajax submit form
My view: This is my django view. It will return json. @csrf_exempt def usersignup(request): if request.method == 'POST': userform = SignUpForm(request.POST) profileform = ProfileForm(request.POST) if userform.is_valid() and profileform.is_valid(): username = userform.cleaned_data['username'] first_name = userform.cleaned_data['first_name'] last_name = userform.cleaned_data['last_name'] email = userform.cleaned_data['email'] password = userform.cleaned_data['password'] user = User.objects.create_user(username,email,password) user.save() gender = profileform.cleaned_data['gender'] birth_date = profileform.cleaned_data['birth_date'] profile = Profile(gender=gender, birth_date=birth_date, user=user) profile.save() datauserform = userform.cleaned_data dataprofileform = profileform.cleaned_data data = {'result': 'success', 'message': 'Registered Successfully'} return JsonResponse(data) elif not userform.is_valid(): userformerrors = userform.errors data = { 'result': 'error', 'message': userformerrors} return JsonResponse(data) elif not profileform.is_valid(): profileformerrors = profileform.errors data = { 'result': 'error', 'message': profileformerrors} return JsonResponse(data) elif not request.user.id: userform = SignUpForm() profileform = ProfileForm() return render(request, 'register.html', {'userform': userform, 'profileform':profileform}) My js: My js script i want my success message alert and error message in span how. Console is ok it will return error and success message but how i display. <script> $(document).ready(function () { var $myForm = $('#myform') $myForm.submit(function (event) { event.preventDefault() var $formData = $(this).serialize() var $thisURL = $myForm.attr('data-url') || window.location.href // or set your own url $.ajax({ method: "POST", url: $thisURL, data: $formData, success: handleFormSuccess, }) }) function handleFormSuccess(data, textStatus, jqXHR) { if (data.result == 'success') { console.log(data.message); … -
django: values() dictionnary with many to many relationship
I'm trying (for training purposes) to make an application for a library catalogue. I took the decision to make a Person model for all people involved in creation of the book and join it with Book model through intermediary model (since one book may have several authors, redactors, translators etc), which would describe the role of this person. Now I'm trying to make search function. My goal is to display a list of all book which meets search criteria, but have all copies which share the authors and the title, as one row with the number indicating the number of copies. So, I understand, I should use annotate with Count on values() dictionnary. But I'm not able to get all information I need while using values(). If I make a query searching by the book title, I have all creators in the values() dictionnary. But if the search criteria is author, the values dictionnary keeps only the name which was used to filter, so if the book has two or three authors, I don't get their names. Here are my models (for Book model only the relevant fields, to make shorter): class Person(models.Model): name = models.CharField(max_length=128, blank=True) born = models.CharField(max_length=64, … -
Remove unwanted th, td and tr tags from Django generated form
I finished an auction app with a search form in the navbar. The search form model is in my forms.py file (it isn't a ModelForm because I don't need to save the search form data in any database model) : class SearchForm(forms.Form): search = forms.CharField(label="", min_length=1, max_length=50, widget=forms.TextInput (attrs={'class':'form-control mr-sm-2', 'placeholder':'Name or category', 'type':'search', 'aria-label':'Search' })) And the form is rendered in my layout.html like this : <form class="form-inline my-2 my-lg-0" action="{% url 'auctions:search' %}" method="POST"> {% csrf_token %} {{ searchform }} <button class="btn btn-outline-light my-2 my-sm-0" type="submit">Search</button> </form> Search Form There is no issue with the rendered form (the style is like I wanted it to be), but when I look at the source code of the rendered page, there is some unwated tr, td and th tags : <form class="form-inline my-2 my-lg-0" action="/search" method="POST"> <input type="hidden" name="csrfmiddlewaretoken" value="glVkeNbCkWjiInGZ2cwORkXSu48otl5TPnJAAGxzdhzzdKFSSMxJVyRk9oK0HNmk"> <tr><th><label for="id_search">Search:</label></th><td><input type="search" name="search" class="form-control mr-sm-2" placeholder="Name or category" aria-label="Search" maxlength="50" minlength="1" required id="id_search"></td></tr> <button class="btn btn-outline-light my-2 my-sm-0" type="submit">Search</button> </form> Those tags are causing errors in the W3C validator, so I had a few questions about this issue : 1 . Is it important ? I am new to programming and i don't know if this will cause serious … -
Custom domain for SAAS project using Django
I am trying to make a portfolio website. The link structure is example.com/portfolio/[user-choice]/ Now I want the user to be able to connect the user domain with their portfolio page. Example: If I own myname.com and have a portfolio at example.com/portfolio/myname then what changes do I need to make on myname.com and the changes I need to make on my Django app? If connecting to example.com/portfolio/myname is not possible then how can I connect it to myname.example.com? Also, there will some parameters in the URL like example.com/portfolio/myname/?name=myname I really don't have any idea how to go on with it. Thanks. -
My login and register forms take take too long to redirect after submit
I am currently developing a website with Django that requires a user to register and sign in. For some reason, after having developed the login and register mechanisms enter code here about a month ago and tested them many times, when I submit the form, it may take up to 10 minutes to redirect me to the next page. This problem showed up today. urls.py from django.urls import path from django.contrib.auth import views as auth_views from . import views from users import views as users_views urlpatterns = [ path('', views.home, name="home"), path('about/', views.about, name="about"), path('register/', users_views.register, name="register"), path('login/', auth_views.LoginView.as_view(template_name='users/login.html', authentication_form=MyAuthForm), name="login"), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name="logout") ] views.py from django.shortcuts import render, redirect from django.contrib import messages from users.forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username} successfully! Now login') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.forms.widgets import PasswordInput, TextInput, EmailInput class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] def __init__(self, *args, **kwargs): super(UserRegisterForm, self).__init__(*args, **kwargs) self.fields['username'].widget = forms.TextInput(attrs={'placeholder': 'Username'}) self.fields['username'].label … -
django how show detail page in modal
I have a problem. I'm beginner in django and python and i need help. I have a page with list of cars and all cars have button with info. Now this button redirect me to another page but i want to open this detail view not in new page but in modal at the same page. I tried many solutions but none of them didn't work in my case. This is my page wiht list of cars car_list.html . It's about car_detailURL. {% extends 'main/main.html' %} {% block title %} Lista samochodów {% endblock %} {% load static %} {% block content %} {% for carTEMP in cars %} <div class="card bg-light mb-3"> <h5 class="card-header"> {{carTEMP}} </h5> <div class="card-body"> <img src="/media/{{carTEMP.car_photo}}"> <div class="row"> <div class="col-sm-auto"> <p>Data produkcji: {{carTEMP.car_date_of_prod}}</p> <p>Numer rejestracyjny: {{carTEMP.car_registration_nr}}</p> </div> <div class="col-sm-auto"> <a href="{% url 'car_detailURL' carTEMP.id %}"><i class="fas fa-2x fa-info-circle"></i></a> <a href="{% url 'edit_carURL' carTEMP.id %}"><i class="fas fa-2x fa-edit"></i></a> <a href="{% url 'delete_carURL' carTEMP.id %}"><i class="fas fa-2x fa-trash-alt"></i></a> </div> </div> </div> </div> {% endfor %} {% include "main/pagination.html" with page=cars %} {% endblock %} And this is car_detail.html which i want to display in modal. {% extends "main/main.html" %} {% load static %} {% block title %} … -
Django - models.py models.E006 passing argument to a function
My class is from django.db import models from .dir import my_func class Upload(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to='images') img_content = my_func(image) def __str__(self): return self.title and I'm not able to pass the image because of an E006 error is there a way to avoid it? because I can call the function but I need to know the name of the newly uploaded image. thanks in advnace -
how to handle Django inline with bootstrap 4
<link href="{% static '/assets/plugins/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet" type="text/css" /> after add this line in django base.html inline style not working propery any help -
Can't see tinymce features
I am partly new to django and completely new to tinymce. I add these lines to my form and I don't see the tinymce features in textarea. <form method="post"> {% csrf_token %} {{ form.as_p }} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} <script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script> <script>tinymce.init({ selector:'textarea' });</script> <button type="submit" class="button">Save changes</button> </form> -
JS access every single element in forloop
I want a button in for loop can run the same function independently for click the hidden while click the , but no response after clicked. html for-loop: {% for order_item in orders %} <a class="btn btn-warning" >Upload File</a> <input type="file" id="img-file{{ forloop.counter }}" hidden="hidden"/> <button type="button" onclick="function upload_img({{ forloop.counter }}){}">Upload</button> {% endfor %} js: <script> function upload_img(x) { const realFileBtn = document.getElementById('img-file'+x); realFileBtn.click() } </script> -
CSRF_COOKIE_SAMESITE equivalent for django 1.6.5
I am trying to launch my application which was written using django 1.6.5 version, in a salesforce webtab iframe. I was getting a "CSRF cookie not set" error while trying to login. I understood through the console logs that in the latest version of Chrome, only allows the cookies which are set with 'secure'=True and samesite=None. I understood that these settings can be added in the settings.py in later versions of django SESSION_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True But this does not work in django 1.6.5 version. I have been trying to find out how to apply these settings in my version. -
static file on django
I'm trying to load static files in my project to the html template. Any help would be appreciated. Below is my code structure. On setting.py STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR,'static/'), ] on my base.html {% load static %} <img src="{% static 'images/log.png' %}" alt="My image"> when I checked the source (src="/static/images/log.png") it only return the error message 'images\log.png' could not be found. An indication that the folder is empty. -
Django Rest Framework Scope Throttling on function based view
Wanted to ask if someone knows a way or a workaround to how to set different throttle scopes for different request methods in a function-based view. For example @api_view(['GET', 'POST']) def someFunction(request): if request.method == 'GET': # set scope for get requests elif request.method == 'POST': # set scope for post requests I tried looking around, but all answers are for class-based views only. Would appreciate the help, thanks. -
Is there any simple way to append the dataTables data using Ajax json response?
my json response are in the following format, [{"directory":"random_code","name":"random_code1","mailing_name":"random_code","address":"random_code","statutory":"random_code","state":"random_code","pincode":"random_code","telephone_num":"random_code","email":"random_code","currency_symbol":"h","maintain":"random_code","financial_year":"random_code1","books_beginning":"random_code1","educational_mode":"hj","vault_password":"hj","security_control":"h","curreny_formal_name":"jh","num_decimal_places":"jh","symbol_suffixed":"j","currency_symbol_decimal":"h","amount_in_millions":"jhj","space_between_symbol_amount":"h","decimal_places_for_printing_amount_in_words":"jhj"},{"directory":"random_code","name":"random_code2","mailing_name":"random_code","address":"jh","statutory":"jh","state":"jhjhjh","pincode":"jh","telephone_num":"jh","email":"jhj","currency_symbol":"hj","maintain":"hj","financial_year":"random_code2","books_beginning":"random_code2","educational_mode":"h","vault_password":"hj","security_control":"hj","curreny_formal_name":"jh","num_decimal_places":"jhj","symbol_suffixed":"hjh","currency_symbol_decimal":"jh","amount_in_millions":"jh","space_between_symbol_amount":"jh","decimal_places_for_printing_amount_in_words":"jhh"}] my code in the script tag is the following, <script> $(function () { $(document).ready(function () { $.ajax({ url : "http://127.0.0.1:8000/api/company/", dataType : "json", type : 'GET', success: function (data) { var trHTML = ''; $.each(data, function (i, item) { trHTML += '<tr><td>' + item.name + '</td><td>' + item.financial_year + '</td><td>' + item.books_beginning + '</td><td><a href="/company_app/edit/1/" class="btn ink-reaction btn-floating-action btn-warning"><i class="md md-edit"></i> </a><a href="/order/delete/1/" class="btn ink-reaction btn-floating-action btn-danger" onclick="return confirm(\'Are you sure you want to delete this?\')"><i class="md md-delete"></i> </a><a href="/order/1/" class="btn ink-reaction btn-floating-action btn-primary"><i class="md md-print"></i> </a></td></tr>'; }); $('#datatable2').append(trHTML); } }); }); }); </script> but it's not adding in dataTable, can anyone help me to append the same inside of datatable ? I'm noob in datatables. -
Javascript stooped working while CSS is working correctly
I have been implementing java-script with Django and they have been working fine.But i have this project where CSS is running and JS is not,I have tried to debug ,have a look but am not making progress. index page {%load static%} <script src="{%static 'js/main.js' %}" text="text/javascript"></script> <script src="{%static 'js/modernizr.js '%}" text="text/javascript"></script> <script src="{%static 'js/jquery-1.11.3.min.js' %}" text="text/javascript"></script> <script src="{%static 'js/jquery-migrate-1.2.1.min.js' %}" text="text/javascript"></script> <script src="{%static 'js/plugins.js' %}" text="text/javascript"></script> Settings STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static'), ] STATIC_URL = '/static/' Urls urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) What am i missing? -
Django REST API - serializer with different format for read and write?
I'm using DRF to run some AJAX backend endpoints. I have these two models: class Quiz(models.Model): title = models.CharField(max_length=50) class Team(models.Model): name = models.CharField(max_length=50) quiz = models.ForeignKey('Quiz', on_delete=models.CASCADE, related_name='teams') I'm then using DRF's generics to create a basic read/write endpoint: class TeamList(generics.ListCreateAPIView): queryset = Team.objects.all() serializer_class = TeamSerializer and a ModelSerializer class TeamSerializer(serializers.ModelSerializer): class Meta: model = Team fields = ['id', 'name', 'quiz'] I can POST it some JSON with a quiz ID to create a team: {"quiz": 123, "name": "My Team Name"} But I'd like the GET version to include the quiz title: {"quiz": {"id": 123, "title": "My Quiz Title"}, "id": 234, "name": "My Team Name"} What's the best way to do that? Have two Serializers and override the ListCreateAPIView.list() method? -
How to add custom query parameter to Django 3 admin to change data column in list_display
Say I have models for Student, Course and Grade. I would like to add a column to the Student admin to show their grades for a certain course and being able to select which course to display. I was thinking about selecting the course with a query parameter 'course'. Example: /admin/student/?course=maths # Shows all students and their grade in 'maths' /admin/student/?course=english # Shows all students and their grade in 'english' I encountered the following problems though: Adding query parameters that are not a field of the model get removed How to get the query parameter values within a ModelAdmin instance? Please help! As a bonus it would also be great to know if there is a way to add a UI element to choose this course. But this is not completely necessary. -
Cannot compile file because "launch:program name lecture3\a.exe does not exist, I am new to Django and VS code
enter image description here Hello, I am new to django and VS code and I built my project using django, I opened it and attempted to run the file however it is giving me this error and jumps right to my launch.json file. Can anyone tell me what is wrong? 1 -
Django indexes the wrong url in google
Why are pages that contain variables in the url indexed google by django? How to prevent it? For example, the website www.pagename.com/?var=aaa is indexed even though it does not exist. I don't have such a link anywhere in the code. And I don't want it because it has a bad effect on seo. what can I do ? -
Django automatically changes camel case
I am using models.IntegerChoices as Enum in Django, but it is saved in DB in a changed way. class FruitsEnum(models.IntegerChoices): Apple = 1 RedApple = 2 GreenApple = 3 LongBanana = 4 DragonFruit = 5 But it is saved in database like this : [('0','Apple'),('1','Redapple'),('2','Greenapple')...] As you see the word 'apple' is not uppercase in two-word combinations. How Can I achive this : [('0','Apple'),('1','RedApple'),('2','GreenApple')...] -
Django TabularInline through relationship
Let's say I have the following models: class A(models.Model): pass class B(models.Model): a = models.ForeignKey("A") class C(models.Model): b = models.ForeignKey("B") I can have a TabularInline widget showing all Bs of a particular A like this: class AAdmin(admin.ModelAdmin): inlines = [BInline] class BInline(admin.TabularInline): model = B How can I have a TabularInline widget showing all Cs of a particular A? (all Cs of all Bs of a particular A) I guess I'm looking for something like: class AAmin(admin.ModelAdmin): inlines = [CInline] class CInline(admin.TabularInline): model = C.through.B Note: I know about the existence of django-nested-admin. this package will show all Cs grouped by every Bs, which is not what I want. I want to show only Cs, without any references to Bs.