Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change the color of a div based on database value change in django?
I'm building a simple web application using Django. This is the view I am using for retreiving data from a db and sending it to my html page. It uses a model (TLabsRampsStationsInfo), thus a table of my db. "f_hold_state" is a column with boolean values that represent either ON or OFF. views.py def statoPostazioni(request): valori = {} for i,el in enumerate(TLabsRampsStationsInfo.objects.all()): valori[i+1] = "lime" if el.f_hold_state == 1 else "red" return render(request,"postazioni.html",{"valori": valori}) This is a portion of my html code, where the values returned by the view are used to change the color of some divs. This is a image of the result in html postazioni.html <div class="elem"> <div class="boxetto des" style="background-color: {{valori.1}}"></div> <div class="boxetto sis" style="background-color: {{valori.2}}"></div> </div> <div class="elem"> <div class="boxetto des" style="background-color: {{valori.3}}"></div> <div class="boxetto sis" style="background-color: {{valori.4}}"></div> </div> The context: when a value of "f_hold_state" change so the color does, but to see that I need to reload the page every time, how can I update the colors without reloading the page? -
How can I put Variables in URL's using django-qr-code
I've been trying to generate URL's on a detailpage for my app. I want the url of the QR-Code to be a link to the detail page of the item. What i have right now is this: <img src="{% qr_url_from_text "localhost:8000/items/{{item.id}}" %}" alt="QR-Code for the item"> the Problem with this is, that i want to give item.id as part of the url. But it's not seen as variable, so when i scan the qr-code, it opens the page http://localhost:8000/items/{{item.id}}, but i want it to have the actual id (e.g. 4) in the url, not {{item.id}} as string. Is there any way to put variables in those URL names? Thank you already -
Join tables using django raw query
what's wrong with the below query? I want to get the feedback_date from pages_dcb table for all the dials that are in the pages_dataupload table where the registration date of the dials are in the 2022. SELECT pages_dataupload.Dial, pages_dataupload.Registration_Date FROM pages_dataupload WHERE pages_dataupload.Registration_Date >= '2022-01-01' LEFT JOIN ( SELECT pages_bdc.Dial, pages_bdc.feedback_date ) on pages_dataupload.Dial = pages_bdc.Dial; Error Execution finished with errors. Result: near "LEFT": syntax error At line 1: SELECT pages_dataupload.Dial, pages_dataupload.Registration_Date FROM pages_dataupload WHERE pages_dataupload.Registration_Date >= '2022-01-01' LEFT -
Django - custom queryset
I have a table like this: class myTable(models.Model): a = models.IntegerField(blank = True, default = 0) b = models.IntegerField(blank = True, default = 0) c = models.IntegerField(blank = True, default = 0) d = models.IntegerField(blank = True, default = 0) I would like to write a view that create a custom queryset with only one tuple which is constituted field by field by the maximum value present among all the tuples. id a b c d 0 2 4 1 7 1 3 1 6 3 2 8 4 2 1 The view should return 1 tuple with a=8, b=4, c=6 and d=7 How can I do that? Thanks -
ModuleNotFoundError: No module named 'taggit', All the setting is done
I followed the tutorial and install django-tagit I think all the settings have been set, but the error says that the module cannot be found. pip install django-taggit #pip list >>> django-taggit #settings.py INSTALLED_APPS = [ 'taggit', ] TAGGIT_CASE_INSENSITIVE = True TAGGIT_LIMIT = 20 #models.py from taggit.managers import TaggableManager class TweetModel(models.Model): class Meta: db_table = "tweet" author = models.ForeignKey(UserModel, on_delete=models.CASCADE) content = models.CharField(max_length=256) tags = TaggableManager(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I ran and installed a virtual environment Taggit is well stored in the library folder. -
Ok now that I have Form Designer AI plugged in, I do not see what the link to fill in the form is [closed]
I can create forms in Admin afer plugging in Form Designer but do not see how to enter data into those forms -
Django: Reimplementing Argon2PasswordHasher with key
In my Django project, I need to modify Argon2PasswordHasher to be able to encrypt with the key (SECRET_KEY) imported from settings.py. I learned that key should be an optional parameter in Argon2, so I have to introduce it in this algorithm. I tried to modify it including a key param in the params method but it didn't work. How can I do? class Argon2PasswordHasher(BasePasswordHasher): Secure password hashing using the argon2 algorithm. This is the winner of the Password Hashing Competition 2013-2015 (https://password-hashing.net). It requires the argon2-cffi library which depends on native C code and might cause portability issues. """ algorithm = 'argon2' library = 'argon2' time_cost = 2 memory_cost = 102400 parallelism = 8 def encode(self, password, salt): argon2 = self._load_library() params = self.params() data = argon2.low_level.hash_secret( password.encode(), salt.encode(), time_cost=params.time_cost, memory_cost=params.memory_cost, parallelism=params.parallelism, hash_len=params.hash_len, type=params.type, ) return self.algorithm + data.decode('ascii') def decode(self, encoded): argon2 = self._load_library() algorithm, rest = encoded.split('$', 1) assert algorithm == self.algorithm params = argon2.extract_parameters('$' + rest) variety, *_, b64salt, hash = rest.split('$') # Add padding. b64salt += '=' * (-len(b64salt) % 4) salt = base64.b64decode(b64salt).decode('latin1') return { 'algorithm': algorithm, 'hash': hash, 'memory_cost': params.memory_cost, 'parallelism': params.parallelism, 'salt': salt, 'time_cost': params.time_cost, 'variety': variety, 'version': params.version, 'params': params, } def … -
HTMX dynamic search with back button in a web browser
I wanted to use the dynamic search by htmx in djnago but I have a problem: the search works but after entering DetailView of the searched item and returning to ListView with the back button in a web browser,there is search data in the inputs, but filter does not work, I have a full list. Search form: <form id="serach_form" hx-post = "{% url 'geo_service:filter-ots' %}" hx-target='#results' hx-trigger="change"> {% csrf_token %} <div class="row g-3 align-items-center pb-4"> <div class="col-6"> <input type="text" id="search_name_input" hx-post = "{% url 'geo_service:filter-ots' %}" hx-target='#results' hx-trigger="keyup changed delay:500ms" name="ots_search_name" class="form-control" placeholder="OTS Name input"> </div> <div class="col-auto"> <div class="form-check form-check-inline"> <input class="form-check-input" type="checkbox" id="inlineCheckbox1" name="ots_search_otdrSupported" value="option1" checked> <label class="form-check-label" for="inlineCheckbox1">otdrSupported</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="checkbox" name="ots_search_fiberAscStatus" id="inlineCheckbox2" value="option2" > <label class="form-check-label" for="inlineCheckbox2">fiberAscStatus</label> </div> </div> </div> </form> Views: class OtsListView(LoginRequiredMixin, generic.ListView): template_name = 'geo_service/ots_list.html' queryset = ConnectionOts.objects.filter(active = True, otdrSupported = "Boolean_true") def filter_ots(request): ots_search_name = request.POST.get('ots_search_name') ots_search_otdrSupported = request.POST.get('ots_search_otdrSupported') ots_search_fiberAscStatus = request.POST.get('ots_search_fiberAscStatus') condition = Q(guiLabel__icontains = ots_search_name) if ots_search_otdrSupported: condition &= Q(otdrSupported = "Boolean_true") if ots_search_fiberAscStatus: condition &= Q(fiberAscStatus = "Boolean_true") results = ConnectionOts.objects.filter(condition) context = {'object_list': results} return render(request, 'geo_service/partials/ots_results.html',context) I tried to manually force an event to make htmx work but it doesn't work. var … -
How can I tell Django to translate (i18n) a file which is not one of the predefined files of a Django app?
I added a python file to the Django app directory. This file is not taken into account when I call manage.py makemessages my_app > migrations > templates - __init__.py - admin.py - forms.py - models.py - my_additional_file.py - ... I use gettext from django.utils.translation like in the all the other python files. Is there an additional configuration where I can include such files? I could not find anything in the documentation. -
Image is not showing, what is wrong over here?
{% extends "base.html" %} {% block content %} <!--Grid row--> <div class="row wow fadeIn"> <!--Grid column--> <div class="col-md-6 mb-4"> **<img src= "/media_root/Brush_Head.png" class="img-fluid" alt="" >** this image is not showing </div> <!--Grid column--> <!--Grid column--> <div class="col-md-6 mb-4"> <!--Content--> <div class="p-4"> <div class="mb-3"> <a href=""> <span class="badge purple mr-1">{{ object.get_category_display }}</span> </a> </div> The bold marked image is not displaying in the webpage, previously it was a link of picture from bootstrap.Please help, Thanks is advcance. -
How to run a migration for a specific app in Django
What I need I added an new app in my project and a separate database for it. I have created the Models for that app and now I need to migrate this models in this separate database app name - authors_app database name - authors My code python3 manage.py makemigrations authors_app It creates the 0001_initial.py file which contains only models from my authors_app. So this step is OK python3 manage.py migrate authors_app 0001_initial --database=authors And this command runs not only my migrations from authors_app, but also migrations from my other app Problem I need to migrate only migrations from authors_app. But the migrate command runs the migrations from all apps Question How can I run migrate for only authors_app -
You are trying to add a non-nullable field 'id' to contact_info without a defaultt
I am using the command python manage.py makemigrations However, I get this error: You are trying to add a non-nullable field 'id' to contact_info without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows) 2) Quit, and let me add a default in models.py Here is models.py: class Posts(models.Model): id = models.AutoField(primary_key=True) post_uesr = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True,related_name='create_user') post_title = models.CharField(max_length=200) post_description = models.TextField(max_length=800, null=True, blank=True) post_likes = models.IntegerField(default=0) post_date = models.DateTimeField(default=datetime.now) def __str__(self): return f'{self.post_uesr}' -
Calculate json data with Jquery
Im using django and store data as json and want to use it dynamicaly in then frontend to calculate it based on some factors. It is only integers, how can I calculate the values, this is how I "fetch" it var $table = $('#table'); var mydata = [ { a:"{{Ansicht.SON_Sprache_1 }}" }, ]; $(function () { $('#table').bootstrapTable({ data: mydata }); }); now i would like to make something like var $table = $('#table'); var mydata = [ { a:"{{Ansicht.SON_Sprache_1 }}" }, ]; $(function () { $('#table').bootstrapTable({ data: mydata **+** other data and so on }); }); -
Django how to add a field to a model that relies on the pk being created first
I am trying to add a hashid that is based on the pk of my model class ExampleModel(models.Model): hash_id = models.CharField(max_length=30) How the hash_id is created.. Assume 15454 is the pk of my object. from hashids import Hashids hashids = Hashids(salt='example salt') hashids.encode(15454) 'Eo6v' The main reason I want to store the hash_id in the model is because I don't want to recompute it everytime or if my salt changes in the future for some reason. Is there a way to automatically generate this field when the object is created since it needs the PK to be created first? -
how to install psyciog2 in a shared hosting `Cpanel` host
how to install psycog2 in a shared hosting Cpanel host, as am running a Django application on this host and I need to connect to Postgres database am using python 3.7.12, I've tried normally install using pip install psycog2 and it failed, also tried to do pip install psycog2-binary and it failed too. ERROR: It appears you are missing some prerequisite to build the package from source. You may install a binary package by installing 'psycopg2-binary' from PyPI. If you want to install psycopg2 from source, please install the packages required for the build and try again. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). error: command '/usr/bin/gcc' failed: Permission denied [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: legacy-install-failure × Encountered error while trying to install package. ╰─> psycopg2-binary PLEASE NOTE THAT I DON'T HAVE SUDO PERMISSION ON THIS SERVER -
Django middleware when using msal for authentication
I Have implemented oauth2 login for users in a django app using the msal library following this guide https://medium.com/@madhok.simran8/how-to-setup-azure-oauth-2-0-sso-in-django-with-microsoft-graph-api-d2639b8f7e36. However Im not able to set the request.user variable right, which in turn means i cant check if request.user.is_authenticated. I Believe this should be solved using the proper middleware, but Im not sure how to set it up. This is my current middleware: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -
Check Data Availability with 0 % when data is not received on the date
I've created Data Availability (Which means if you select dates from_date to to_date, you'll get a table on that date on how much % of data will be received). If data is available on that selected date then I got that data in %. but if data is not received on a selected date then I want to add 0% data received. In the above Image, I've selected from date (03-09-2022) and to date (06-09-2022) but received only those dates for which data is available. In the table, I want to add 03-09-2022, and 04-09-2022 dates with 0% data. I've written this code in views.py final_data = dict() for key, values in data.items(): final_data[key]= dict() for key1, value in values.items(): total_data_count = len(value) percentage_data = (total_data_count * 100)/1440 available_data = str(percentage_data)[:5] final_data[key].setdefault(key1,available_data) Here key1 is the date and available_data is the calculated data in %. How can I get the selected date if data is not available? -
Print all values from dictionary in python [duplicate]
I have a dictionary a = {'a': 1, 'b': [2,3,[5,6]]} I need to get an output : [1,2,3,5,6] a['b'] : has a nested list contains both integer value and list -
how to get library steganography spread spectrum method DSSS
So i was searching library for encryption audio, using steganography spread spectrum. i want hide password to audio. the method spread spectrum i want to use is DSSS. i will implementation it using django (python). anyone know the library? i was searching for long but not get the library. i was tried searching but what i always found just paper, not the library. i need fast as can. i don't know how to search it again i was try with keywords: library spread spectrum audio, library spread spectrum "audio", library spread spectrum "audio" django -
Django permission_required decorator doesn't redirect back after login
My request handlers have a permission_required decorator to force the user to login. Like so: @permission_required("main.view_things", login_url="admin/login") def homepage(request): # ... This works fine. But if a login is required, the login page doesn't redirect back to the original page (here: homepage), but to some page in admin. Is there an easy fix, since this seems to be a pretty standard situation? -
Django MultiValueField and MultiWidget ChoiceField custom choices
I am trying to create a form that allows students to request courses, and I have been working on the time selection field, I would like the field to select a day of the week and a time of the day, but the hours of each course is different, so I would like to provide the available times in the form of the course instead of the field definition, this is what I tried: class ClassTimeWidgit(forms.MultiWidget): def __init__(self, time, attrs=None) -> None: widgets = [ forms.Select(choices=[ ('Monday', 'Monday'), ('Tuesday', 'Tuesday'), ('Wednesday', 'Wednesday'), ('Thursday', 'Thursday'), ('Friday', 'Friday'), ('Saturday', 'Saturday'), ('Sunday', 'Sunday'), ], attrs={'style':'width:130px'}), forms.Select(choices=time, attrs={'style':'width:130px'}) ] super(ClassTimeWidgit, self).__init__(widgets, attrs) def decompress(self, value): if value: return value.split(' ') return ['', ''] class ClassTimeField(forms.MultiValueField): widget = ClassTimeWidgit def __init__(self, time, **kwargs) -> None: f = ( forms.ChoiceField(choices=[ ('Monday', 'Monday'), ('Tuesday', 'Tuesday'), ('Wednesday', 'Wednesday'), ('Thursday', 'Thursday'), ('Friday', 'Friday'), ('Saturday', 'Saturday'), ('Sunday', 'Sunday'), ] ), forms.ChoiceField(choices=time) ) super().__init__(fields=f, require_all_fields=True, **kwargs) def compress(self, data_list): return ' '.join(data_list) class RequestCourseForm(forms.ModelForm): teacher = forms.ModelChoiceField(queryset=User.objects.filter(profile__teacher_status=True)) class_count = forms.IntegerField(widget=forms.Select(choices=[(10,10), (20,20)])) class_time = ClassTimeField(time=[(f'{i}:00', f'{i}:00') for i in range(8,21)]) class Meta: model = Request fields = ['teacher', 'class_count', 'class_time'] I am trying to make it so I can set the available … -
How to append a list inside of a dict from a JSONFeild in django
I want to use get_or_create() to search for an object. If it doesn't exist, it gets created. If it does exist, I want to update its metadata which is stored as a JSONFeild. Lets say we have this class and object: Class Customer(models.Model): first_name = models.CharField(max_length=32, blank=True, db_index=True) last_name = models.CharField(max_length=32, blank=True, db_index=True) metadata = models.JSONField(default=dict, blank=True) Customer.objects.create( first_name="John", last_name="Doe", metadata ={ "customer_created":"2022_08_06", "address_list":["123 Street"], }, ) Now we want to add another customer, but if it already exists, we just want to append the list in metadata["address_list"] obj, created = Customer.objects.get_or_create( first_name="John", last_name="Doe", defaults={ 'metadata':{ "customer_created": "2022_09_26", "adress_list": ["321 Avenue"], } ) Would obj.medata["address_list"].append(["321 Avenue"]) work or do I need to copy the list, append it, then update metadata? Which is correct? if not created: obj.medata["address_list"].append(["321 Avenue"]) or if not created: addresses = obj.medata["address_list"] addresses.append(["321 Avenue"]) obj.medata["address_list"] = addresses I'm new to django; is there a better way to do this? I am not allowed to change the Customer class but I can change how I structure the metadata dict -
Django Rest Framework - admin email has empty traceback
Getting empty stack trace from Admin Emails for 500 errors in Django Rest Framework (DRF): Exception Location: , line , in From DRF source code I can see: {% if lastframe %} <tr> <th>Exception Location:</th> <td><span class="fname">{{ lastframe.filename }}</span>, line {{ lastframe.lineno }}, in {{ lastframe.function }}</td> </tr>{% endif %} So this must have something to do with our custom exception handler where we shape the JSON response data to match a legacy system? def custom_exception_handler(exc, context): """ https://github.com/HackSoftware/Django-Styleguide#errors--exception-handling Format the error before passing to CustomJSONRenderer """ if isinstance(exc, DjangoValidationError): exc = exceptions.ValidationError(as_serializer_error(exc)) if isinstance(exc, Http404): exc = exceptions.NotFound() if isinstance(exc, PermissionDenied): exc = exceptions.PermissionDenied() # Call REST framework's default exception handler first, # to get the standard error response. response = exception_handler(exc, context) # Unknown error occured! if response is None: if exc: response.data = { "error": { "client_message": "Whoops, something went wrong", "developer_message": "".join( traceback.TracebackException.from_exception(exc).format() ), # "developer_message": str(exc), } } response.status_code = 500 return response response.data = { "error": { "client_message": "Whoops, something went awry", "developer_message": "unknown exception handling error - response is None", } } response.status_code = 500 return response errors = [] message = response.data.get("detail") if not message: for field, value in response.data.items(): errors.append(f"{field} : … -
In Python how to plot pie chart using plotly
I am trying to plot using plotly. I am using the go command. I can design bar charts, but when I am trying pie using the go command. i got error I am sharing here my code and bar graph image. I want to convert bar graph into a pie. df2 = df.groupby(pd.to_datetime(df.MeterReading_DateTime).dt.hour).agg({'ACT_IMP_TOT': 'sum'}).reset_index() print(df2) #x = df2['MeterReading_DateTime'] #y = df2['ACT_IMP_TOT'] data_plots = go.Bar(x=df2['MeterReading_DateTime'], y= df2['ACT_IMP_TOT'],marker = {'color' : '#0f4054'}) #data_plots = px.pie(values=random_x, names=names) layout = {'title': '','xaxis': {'title': 'Date and time'},'yaxis': {'title': 'Total Import(KWH)'},'plot_bgcolor':'#E8E8E8'} fig = {'data': data_plots, 'layout': layout} plot_div = offline.plot(fig, output_type='div') return plot_div -
Django REST Framework (AttributeError : Got AttributeError when attempting to get a value for field " " on serializer " ")
Got AttributeError : when attempting to get a value for field Firstname serializer NameSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute Firstname. serializers.py from rest_framework import serializers from .models import Name, ForeName class NameSerializer(serializers.ModelSerializer): class Meta: model = Name fields = '__all__' class ForeNameSerializer(serializers.ModelSerializer): forenames = NameSerializer(many=True, read_only=True) class Meta: model = ForeName fields= '__all__' models.py from django.db import models import uuid # create your models here class ForeName(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Forename = models.CharField(max_length=30) def __str__(self): return self.Forename class Name(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Firstname = models.ForeignKey(ForeName, on_delete=models.PROTECT, related_name="forenames") views.py from rest_framework.decorators import api_view from rest_framework.response import Response from .serializers import NameSerializer from .models import Name # Create your views here. @api_view(['GET']) def names_list(request): names = Name.objects.all() myname = NameSerializer(names) return Response({"restult": { "Forename" : myname.data, }