Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2.2 compatibility with PostgreSQL
I'm working on a Django app on a Linux server and found out the existing PostgreSQL isn't supported by Django. If Postgres is upgraded to the most recent version (looks like v 12), will it be compatible with Django 2.2 and psycopg2 version 2.8.5? Is there a "too new" version of Postgres that I should worry about for either Django or psycopg2? I've tried to answer this question for myself using the relevant Django docs and psycopg docs, and I think everything will be okay, but I haven't found a definitive answer. I just don't want to have to make the system administrator uninstall and reinstall and older version of Postgres. -
Django-sitetree item.is_current always returns False
I have the following code in my nav.html: ..... {% sitetree_menu from "menu" include "trunk" template "nav/nav-item.html" %} ..... and following in my nav-item.html file: {% load sitetree %} <ul class="navbar-nav"> {% for item in sitetree_items %} <li class="nav-item"> <a href="{% sitetree_url for item %}" class="nav-link {% if item.has_children %}dropdown-toggle{% endif %} {% if item.is_current or item.in_current_branch %} active {% endif %}">{{item.title_resolved}} </a> {% if item.has_children %} {% sitetree_children of item for menu template 'nav/nav-sub-item.html' %} {%endif%} </li> {% endfor %} </ul> All features of sitetree are working well but item.is_current always returns False. I can't understand what the problem is. Has anybody experienced such kind of problem? -
Django - referencing value from template in views.py
I have a Pandas dataframe that I am displaying as an HTML table. I turned the first column of that table into a column of clickable buttons that return a unique value and link to a webpage with information regarding the selected topic. The col. was turned into a button with the following format: '<button type="submit" name="info" value=' + df['Name:'] + '>More Info</button>' However, in order to display the unique page when the button is clicked I need to be able to reference the button "value" I have tried referencing the button value from my view in the following ways: if request.POST.get('info', ''): value = info.value return redirect('detail') if request.POST.get('info'): value = value return redirect('detail') However, neither "value" or "info" can be called. Does anyone know how I can reference the value of the button from my views.py? -
django & postgres timezone localtime vs utc
I save a datetime to my postgres db, when I then display it on my website it's wrong... In my models.py: datetime_start = models.DateTimeField() In postgres the time is saved like this: utc+2h: In my django I made following settings: USE_TZ = True TIME_ZONE = 'Europe/Paris' In my template I get the time, for testing I display once the utc and once the localtime: <th> Start </th> <td>{{activity.datetime_start |utc|date:"d.m.Y H:i"}}</td> <td>{{activity.datetime_start |localtime|date:"d.m.Y H:i"}}</td> And here the output on my website: Why this output is wrong? The utc time should be: 06:00 And the localtime should be: 08:00 I'm confused, what did I make wrong with the timezones and times? Does django interpret the postgres time wrong? -
File Type conversion in Django
I have started doing a project that converts file from one type to another like from .pdf to .doc etc. But in django I'm not able to access the file and pass it to the conversion program. Python has library for conversion of files, but how to do it and can it be done? Thank you!! -
Nesting If statements to detect request value in Django views
I am trying to get third button to work on a simple app I am making. I set up if statements to detect the value of the request for two buttons, but I am getting stuck on how to configure the logic statement to get a third parameter through. My issue is that I need to have the form filled with any data before the subscriptions button will work properly. When the form is blank the app will indicate the form needs to be filled out. I am not familiar with javascript to have the buttons run from that. My hope is that I can learn how to configure the if statement to have the subscriptions call work without the form being filled out. Below is the UI as and the views.py def. The Amount and Delete functions work fine. It is just the subscription button that won't work until I put literally any data into the two text fields fields. def usage(request): if request.method == 'POST': form = UsageForm(request.POST) if form.is_valid(): if request.POST.get('subscription') == 'Subscription': dt = datetime.today() month = dt.month year = dt.year day = calendar.monthrange(year, month)[1] eom = str(month) + "/" + str(day) + "/" + str(year) … -
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?