Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hidden field in the template
I'm trying to update (using Django's UpdateView) a field of my Model. The problem is that this field doesn't appear on the template but it is there with: input type = 'hidden' setted. How is it possible? I've already used UpdateView for other models, and I haven't had any problems so far. -
JSON_CONTAINS not working in django queryset but working fine at mysql workbench
I have a list of devices in my database, like this: id: 1, category_json: [1, 3] id: 2, category_json: [1, 4] id: 3, category_json: [4, 35] The field 'category_json' is a JSONField. I get an array of categories that the users wants from the frontend like this: categories = [3] I need to make a query in django to look up for all devices that has any of the categories above, I did this in django: category_filtering = None for category in categories: if not category_filtering: category_filtering = Q(category_json__contains=category) else: category_filtering = category_filtering | Q(category_json__contains=category) all_devices: QuerySet = Device.objects.filter(Q(status=1) & Q(company__in=companies)) & category_filtering That code above reproduces the following query: SELECT `devices`.`id`, `devices`.`serial`, `devices`.`title`, `devices`.`product_id`, `devices`.`company_id`, `devices`.`server_access_key`, `devices`.`device_local_access_key`, `devices`.`mac_address`, `devices`.`status`, `devices`.`owner_device_id`, `devices`.`connected_equipament`, `devices`.`gps_x`, `devices`.`gps_y`, `devices`.`profile_id`, `devices`.`softwareVer`, `devices`.`hardwareVer`, `devices`.`isVirtual`, `devices`.`timezone`, `devices`.`installed_phase`, `devices`.`installation_local`, `devices`.`group`, `devices`.`relay_state`, `devices`.`last_sync`, `devices`.`phases_ordering`, `devices`.`created_at`, `devices`.`installation_date`, `devices`.`installation_state`, `devices`.`last_change`, `devices`.`last_online`, `devices`.`comments`, `devices`.`enable_bbd_home`, `devices`.`enable_bbd_pro`, `devices`.`enable_tseries_analytics`, `devices`.`enable_gd_production`, `devices`.`card_profile_id`, `devices`.`firmware_app_ver`, `devices`.`firmware_metrol_ver`, `devices`.`commissioning_date`, `devices`.`state`, `devices`.`area_square_meters`, `devices`.`category`, `devices`.`local`, `devices`.`code`, `devices`.`enable_advanced_monitoring`, `devices`.`send_data`, `devices`.`olson_timezone`, `devices`.`language`, `devices`.`extra_fields`, `devices`.`category_json` FROM `devices` WHERE (`devices`.`status` = 1 AND `devices`.`company_id` IN (SELECT U0.`id` FROM `companies` U0 WHERE (U0.`id` IN (( WITH RECURSIVE ids(id) as ( select 297 as id union all select companies.id as id from ids join companies where ids.id = … -
How to I fix the image size and position on a bootstrap card template?
Good evening everyone, I am trying to avoid that the image of a card (implemented through bootstrap) shifts to the top of the card once the user sees the website from a mobile version. The problem is as follow: <div class="card mb-3" style="max-width: 540px;"> <div class="row no-gutters"> {% if post.immagine %} <div class="col-md-4"> <img src="{{ post.immagine.url }}" class="card-img" width="200" height="260"> </div> {% else %} <div class="col-md-4"> </div> {% endif %} <div class="col-md-8"> <div class="card-body"> <h5 class="card-title">{{ post.nome }} {{ post.cognome }} - </h5> <a href="{% url 'prova-detail' post.pk %}" class="btn btn-dark" style="background-color: #282d4c;">Leggi</a> <p class="card-text"></p> </div> {% else %} <div class="card-body" style="text-align:center"> <h5 class="card-title">{{ post.nome }} {{ post.cognome }}</h5> </div> </div> </div> {% endfor %} -
How do I implement a password manager web app in Django
I am creating a web based password and secret notes manager using Django. However, when a user saves a password(with username and website url), if you look at the request in the developer tools, you can see the parameters in plaintext. How do I encrypt or hash the passwords/notes that it would not be readable in the request, and how do I decrypt it so that the user can see and copy it? -
Django url path conflict
I'm new to django and stackoverflow so I ask your help because I can't figure out how to solve this problem. I'm doing a ecommerce website for educational purposes. I'm trying to achieve a full path like this: http://127.0.0.1:8000/category1/subcategory1/product1 or http://127.0.0.1:8000/category2/subcategory2/subcategory3/product2 I want to call productlistview to list all the products in any category and productdetailview for every product. What is happening is that django always calls productlistview even when I call url 'store:product_detail' and get's me the 404 error as it doesn't find the category with the product name. I'm aware that django always stops in the in the first url that matches but I'm awarding a name but it doesn't work. Here are my templates: #index.html {% recursetree menu_category %} <li> <a href="{% url 'store:product_list' cat_slug=node.full_slug %}">{{ node.name }}</a> {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} #product_list.html {% for item in product %} <a href="{% url 'store:product_detail' cat_slug=category.full_slug prod_slug=item.slug %}"><p>{{ item.name }}</p></a> {% endfor %} #urls.py app_name = 'store' urlpatterns = [ path('<path:cat_slug>', productlistview, name='product_list'), path('<path:cat_slug><slug:prod_slug>', productdetailview, name='product_detail'), ] #views.py def productlistview(request, cat_slug): category_select = get_object_or_404(Category, full_slug=cat_slug) product_list = Product.objects.filter( category__in=Category.objects.get(full_slug=cat_slug).get_descendants(include_self=True)) return render(request, "store/product_list.html", { 'category': category_select, … -
Is it possible generate a hash of result set using django orm?
I need something like this: How to generate a hash of the result set in Postgress? Is it possible using django orm? Does anyone have any reference? -
Django payment integration in poland
How to intergrate przelewy24 payment to existing django project? I dont need any other payment gateway only przelewy I need all the step by step process of doing this -
Django rolling back migration doesn't do anything. Table is still present
I am running the following command to rollback my migration in my Django project. python manage.py migrate users 0021_emailsetting The issue is that there is no effect after this command is executed. I get following result: Operations to perform: Target specific migration: 0021_emailsetting, from users Running migrations: No migrations to apply. The table is still there in the database and showmigrations also checks that particular migration as applied. I had applied python manage.py migrate users zero to make sure there isn't any previous migration causing the issue but the issue still remains after running all migrations after full rollback. -
Quiz grading in django, trouble with formsets
I am having some trouble implementing a quiz app in django. I know I risk reinventing the wheel but most of the packages and implementations I have found are 3-5 years old, and not maintained for my version of django (3.1.3) I ideally want a Quiz model that connects to different questions (multiple choice or short answer) where each multiple choice has a number of questions, one being an answer. Using a formset users are able to create quizzes with multiple questions, however this is only implemented with short answer questions. To record attempts with logged in users I have created a QuizAttempt model with a foreign key to Quiz. Each attempt has AttemptQuestions that link to each question in a quiz. It might be easier to just link the models and views below. I am having trouble showing the question and then the attempt form underneath, havent gotten around to grading either Views.py class CreateQuizView(CreateView): template_name = 'quizzes/CreateQuizView.html' form_class = QuizForm # def get_context_data(self, **kwargs): #Formset is added to context data here from an inline formset in my forms.py ... def form_valid(self, form): context = self.get_context_data() formset = context['formset'] with transaction.atomic(): form.instance.author = self.request.user self.object = form.save() if formset.is_valid(): … -
User Registration with rest auth
Using Django rest framework and rest auth registration. I m using React as the front end and would like to send a username, email from the front end and use an auto-generated password, may be from password = BaseUserManager.make_random_password(self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789') The main thing is I don't want to send password from my react app. Checked here that we can not append seializers data. How can I do this? Or any other method to achieve my requirements. -
Python Django: __init__() got an unexpected keyword argument 'request'
This is quite weird as the same code works flawlessly in my other Django app, so it must be a problem with what I've edited or the way my views.py file co-ordinates with my Form Class. Take the following: Views.py import sys import os import paramiko from google.cloud import logging from google.cloud.logging.resource import Resource from google.cloud import error_reporting from googleapiclient import discovery from oauth2client.service_account import ServiceAccountCredentials from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from .restart_es_services_confirm import ESServicesConfirm def restart_es_services_confirm(request): if request.method == 'POST': return HttpResponseRedirect('restart_es_services.html') else: request.session['systems'] = [{"host": "test", "service": "tomcat"}] form = ESServicesConfirm(request=request) form = ESServicesConfirm(request=request) return render(request, 'restart_es_services_confirm.html', {'form': form}) restart_es_services_confirm.py from django import forms from django.urls import reverse from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Row, Column, Field, Fieldset, HTML, Button class ESServicesConfirm(forms.Form): plan = forms.CharField(request=False,disabled=True,widget=forms.TextInput(attrs={}),label='') reconfirm = forms.BooleanField(required=True, label='I confirm these services can safely be restarted.',widget=forms.CheckboxInput(attrs={})) def __init__(self, *args, **kwargs): request = kwargs.pop("request") super().__init__(*args, **kwargs) systems = request.session['systems'] plan = [] for system in systems: host = system['host'] service = system['service'] plan.append("Restart " + service + " on " + host) self.fields['plan'] = plan self.helper = FormHelper() self.helper.add_input(Button('cancel', 'Cancel', css_class='button button--wide button--black', formvalidate='formnovalidate', onclick="window.location.href = '{}';".format(reverse('home')))) self.helper.add_input(Submit('deploy', 'Deploy', css_class='button button--wide button--white')) … -
django notify user three month before expire date
I have a Django app that has an expiration date field where the user has to fill up when submitting the form. What I want to do next is to have a function that checks the expiration date and automatically sends an email notification to the user three months before the expiration date. I am not sure whether it is possible to do that or not. I did some reading on Django-notification but I am not sure what's the best way to approach this. -
How to use a custom validation method taking request parameters
I have a really simple form on which I'm doing some validation: def clean(self): cleaned_data = super().clean() start = cleaned_data.get("start") end = cleaned_data.get("end") if start >= end: raise ValidationError("start should not be greater than end.") But I need to add another validation (which is based on the user making the request). I tried to add the parameter to the clean method: def clean(self, user): cleaned_data = super().clean() start = cleaned_data.get("start") end = cleaned_data.get("end") if start >= end: raise ValidationError("start should not be greater than end.") if not user.email.endswith("@example.com"): raise ValidationError("blah...") Unfortunately, I cannot call the is_valid() in the view with a parameter: if form.is_valid(request.user): .... I get the following error message: is_valid() takes 1 positional argument but 2 were given I also tried to add a new method to the form: def validate_email(self, user): if not user.email.endswith("@example.com"):: raise ValidationError("blah...") and call it from the view: if form.is_valid() and form.validate_email(request.user): obj = form.save(commit=False) obj.created_by = request.user obj.save() In that case, the exception really gets thrown and crashes the application. My goals are: to make the validation dependant on a criteria in the request to display an error message normally when the validation fails What would be the correct way to implement … -
Django: How to site wide display queryset result in base template
My django site uses a base template with left, middle and right blocks. The middle and right block are extended by detail templates that get data passed in context by several views. models.py class Participant(models.Model): name = models.CharField(max_length=64) ... class Code(models.Model): name = models.CharField(max_length=64) source = models.TextField() author = models.ForeignKey(Participant, on_delete=models.CASCADE) The left block should always display the results of participant.code_set as a list of code.name as soon as the participant is known. I previously did this by adding the pickled participant instance in the session as soon as it was known and then looping over session.participant.code_set in the base template. Is there an other way to achieve the same without using the PickleSerializer for sessions? Thanks -
Django / Ajax - Sending form data and variable at the same time
I want to send both my form data and a variable to my view with ajax: var form = $(this); var f = document.getElementById("submit-id-requestsave"); var name = (f.name) var formsend = form.append("name",name) console.log(formsend.serialize()) $.ajax({ url: '/request_new/' + track_id + '/', data: formsend.serialize(), type: 'POST', dataType: 'json' I have tried appending but I cannot see the var name when it has been serialized. What is the best practice here? -
Django admin panel logout functionality
Is there any way to logout from all devices where I have logged in as admin in Django admin panel? The site has already been deployed to heroku server -
How to use a downloaded font in a django project instead of google fonts api
I cant find a solution to my problem anywhere, so i am hoping for some help. I am new to programming and to django as well. I followed the following tutorial until the start of part 4. So far so good. Now i've found a new font online that i would like to use, instead of the google font the tutorial is using, for the django "logo" in the topbar (its called Crimson Foam). The problem is, that i have no clue how to use it in my base.html file and what to do with my css files (I've seen that you apparently need to use those). My static files are organised like so: -- static |--fonts | |--crimson_foam.ttf | |--css |-- app2.css |-- bootstrap files I've tried it like that: templates/base.html {% load static %}<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>{% block title %}Django Boards{% endblock %}</title> <link href="{% static 'fonts/crimson_foam.ttf' %}" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/app2.css' %}"> </head> Rest of the html file I tried 2 different .css file versions: static/css/app2.css Version 1: title { color:#FAB4FF; font-family: "Crimson foam"; #didnt know what to put there } Version 2: .navbar_brand { … -
How can i add new field into django query output?
there is get query query_get = get_object_or_404(My_model, id=1) i want to add new field in this out put.but do not work. when i use query_get['new_field']='1' then return that,but can not add new_field in out put. -
(index):40 Uncaught TypeError: Cannot set property 'innerHTML' of null at getanswer ((index):40) at HTMLButtonElement.onclick ((index):204)
For the below JS code, i am getting the above error <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!--to add latest version of cdn jquery--> <script> /*to get answer in the click*/ $(document).ready(function(){ $("#btn1").click(function(){ $(".btn1").show(); $(".btn1").attr("disabled",true); }); }); function getanswer() { document.getElementById("useranswer").innerHTML = ""; var e = document.getElementsByTagName('input'); for(i = 0; i<= e.length ; i++) { if(e[i].type == 'radio') { if(e[i].checked) { document.getElementById("useranswer").innerHTML += "Q" + e[i].name + "Answer you selected is :" + e[i].value+ "<br/>"; } } } } </script> The html button is <button type="submit" id="btn1" onclick="getanswer();"> submitanswer </button> This button perform form submission which contains table and rows. I have included a piece of code of that <tr> <td>{{Result.id}} ) {{Result.questions}}</td> </tr> <tr> <td><input type="radio" id="choice1" name="{{Result.id}}" class="ans" value="{{Result.choice1}}">{{Result.choice1}}</td> </tr> How to solve this error?? Can anyone help with this? The submit button not working -
How do i flash a message in django?
So, I want my django app to notify users of certain events through flashed messages. Like, an error message or a success message. I know there is a built in flash method in flask. But is there any equivalent in django? If yes, then can you please show me how to use it and style it using bootstrap. Thanks in advance. -
Django Authenticate method not working on custom Model
I am trying the build in method authenticate() to login employees but that does not seem to work. I have not used the default model User provided by django instead I have used my own model Employee here. Here is what I have in my views.py def login(request): if request.method == 'POST': password = request.POST['password'] emailid = request.POST['email'] employee = auth.authenticate(username=emailid,password=password) if employee is not None: auth.login(request,employee) return render(request,'register/html') else: messages.error(request,'Email id dosent exist') return redirect('login') else: return render(request,'employee/login.html') while my custom code does the authentication def login(request): if request.method == 'POST': password = request.POST['password'] emailid = request.POST['username'] if Employee.objects.filter(firstname=emailid).exists(): if Employee.objects.filter(password=password): messages.success(request,'Loged Out') return redirect('vacant-rooms') else: messages.error(request,'Wrong emailid') return redirect('login') else: messages.error(request,'wrong password') return redirect('login') else: return render(request,'employee/login.html') Here is my model class Employee(models.Model): firstname = models.CharField(max_length=15) lastname = models.CharField(max_length=15) age = models.IntegerField() sex = models.CharField(max_length=10) phoneno = models.IntegerField() emailid = models.CharField(max_length=25) address = models.CharField(max_length=50) salary = models.IntegerField() designation = models.CharField(max_length=10) password = models.CharField(max_length=10) aadharno = models.CharField(max_length=15) datejoined = models.DateField(default=timezone) Its a dumb question maybe butis the buit in authentication not working because I do not have a username field in my model? -
Apache2 Django NameError: name "TypeError" is not defined
I am trying to run a django application on VPS via apache2, but I get the following in the website-error file, also 400(Bad Request): Exception ignored in: <function Local.__del__ at 0x7f47273f48b0> Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/asgiref/local.py", line 96, in __del__ NameError: name 'TypeError' is not defined I successfully ran a simple website that was made with "django-admin startproject" and could be viewed, but uploading project, made with the following skeleton, produces this error: https://django-project-skeleton.readthedocs.io/en/latest/apache2_vhost.html I have tried including the python site-packages in the WSGIDaemon and by exluding them it produces the same effect. In addition to this, I have also added: <Directory /var/www/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> But again, no change -
Django form image upload - form not defiend
I'm trying to upload an Image on my Django server, then converting it to numpy array or something and do some processing then return a new image. REST seemed best choice to me. But currently I'm stuck at uploading part, processing in local drive is complete though. Here is my view : from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from PIL import Image class ImageUpView(APIView): parser_classes = (MultiPartParser, FormParser, ) def post(self, request, format=None): form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): newimg = ImageUpload(title=request.POST['title'], image=request.FILES['image']) pass return Response() #return Response(request.data.get('image')) Then my model: from django.db import models class ImageUpload(models.Model): title = models.CharField(max_length=20) image = models.ImageField(upload_to="images/", default=None) def __str__(self): return self.title And form finally: from django.db import forms class ImageUploadForm(froms.ModelForm): class Meta: model = ImageUpload fields = ['title','image'] But when I upload I get some error saying : form = ImageUploadForm(request.POST, request.FILES) NameError: name 'ImageUploadForm' is not defined Here is the Postman snap : -
Use of exclude in Django aggregation
I have a model similar to this : class Product(): tags = models.ManyToManyField(Tag) class Tag(): slug = models.CharField() class Transaction(): product = models.ForeignKey(Product) store = models.ForeignKey(Store) class Store() I would like to know if there is a way to exclude some lines when performing an aggregation. For instance, i would like to know how many transactions are related to each of my stores, but i would like to count transaction with a product containing a particular tag but exclude the transaction that contain another. For instance, let's say that i have a Coke Product whose tags are "drink" and "soda", i would like to know how to count transactions with a product that have "drink" tag but not the "soda" one. I tried this, but this not working : Store.objects.annotate( non_soda_transacion_count=Count("transactions", filter=Q(transactions__product__tags__slug="drink") & ~Q(transactions__product__tags__slug="drink") ) Do you have any clue ? I am using Django 2.2.13 -
Django migration fails 'QuerySet' object has no attribute 'objects'
I have a set of models: class DebugConf(models.Model): is_setup = models.BooleanField(default=False) debug_setup_date = models.DateTimeField() def __str__(self): return self.is_setup class Currency(models.Model): currency_name = models.CharField(max_length=100) currency_value_in_dollars = models.FloatField() currency_value_in_dollars_date = models.DateTimeField() def __str__(self): return self.currency_name class User(models.Model): user_name = models.CharField(max_length=200) user_pass = models.CharField(max_length=200) join_date = models.DateTimeField() def __str__(self): return self.user_name class Transaction(models.Model): transaction_type = models.CharField(max_length=200) transaction_amount = models.FloatField() transaction_date = models.DateTimeField() transaction_currency = models.ForeignKey(Currency, on_delete=models.CASCADE) transaction_users = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.headline a project 'crypto' and an app 'manage_crypto_currency' nested into it: The app's views contains some initialization code: views.py: if IS_DEBUG_MODE: print('[!!!INFO!!!] DEBUG MODE SET! USING GENERATED TABLES') init_debug_tables() def init_debug_tables(): # Check if debug table has already been initialized debug_conf = DebugConf.objects.all() if debug_conf.objects.exists(): return At the moment, the db is not initialized; when running: python manage.py makemigrations manage_crypto_currency in the root (project dir): I get: [!!!INFO!!!] DEBUG MODE SET! USING GENERATED TABLES Traceback (most recent call last): File "manage.py", line 24, in <module> main() File "manage.py", line 20, in main execute_from_command_line(sys.argv) File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\core\management\base.py", line 368, in execute self.check() File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = …