Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The correct way of modifying data before saving a model via the admin site
Django 4.1 models.py class Video(models.Model): phrase_id = models.IntegerField(default=-1, blank=False, null=False, validators=[MinValueValidator(0)]) # This field will be read only in the admin site. # Its only purpose is to ensure cascade deletion. _phrase = models.ForeignKey("vocabulary_phrases.Phrase", on_delete=models.CASCADE, default="", blank=True, null=True) admin.py class VideoAdmin(admin.ModelAdmin): list_display = ["phrase_id", "name", ] list_filter = ['phrase_id'] readonly_fields = ('_phrase',) form = VideoForm admin.site.register(Video, VideoAdmin) forms.py class VideoForm(ModelForm): def clean(self): if ("phrase_id" in self.changed_data) and self.cleaned_data.get("phrase_id"): phrase_id = self.cleaned_data["phrase_id"] _phrase = _get_phrase(phrase_id) self.cleaned_data["_phrase"] = _phrase return self.cleaned_data class Meta: model = Video exclude = [] In the admin site a user inserts an integer for phrase_id. Then in the admin form I wanted to substitute self.cleaned_data with Phrase instance I extract from the database. Well, the problem is that after saving, _phrase field is empty. Thid is the documentation: https://docs.djangoproject.com/en/4.1/ref/forms/validation/ It reads as follows: The form subclass’s clean() method... This method can return a completely different dictionary if it wishes, which will be used as the cleaned_data Well, I have modified the cleaned_data, but it seems to have no effect on what is saved. My idea was: data are validated before saving, substitute cleaned_data, then your own data will be saved. I seem to have been wrong. Could … -
Django button submit not work after using javascript code
This would be my Registration page. When the script html tag testscript.js code is remove or commented out, the register button works perfectly fine but when I input the testscript.js, the register button is kind of disabled. So, I think the problem is the javascript code because that's the only part of the code that blocks the function of the register button. Here's my source code: views.py: def registration(request): form = CustomUserCreationForm() print("Working Form") if request.method == 'POST': form = CustomUserCreationForm(request.POST) print("Form Submitted") if form.is_valid(): form.save() context = {'form' : form} return render(request, 'activities/index.html', context) index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="../static/CSS/styles.css"> <link rel="stylesheet" href="../static/CSS/font-awesome/css/all.min.css"> <link rel="stylesheet" href="../static/CSS/css/bootstrap.min.css"> <script src="../static/Javascript/js/jquery.min.js"></script> <title>Document</title> </head> <body> <!-- Header --> <div class="site-header" > <nav class="navbar fixed-top navbar-expand-lg navbar-dark index__navbar scrolled"> <div class="container-fluid"> <div> <img class="navbar-icon" style="margin-left:15px;" src="../static/Media/avatar.png" alt="dasma-logo"> <span id="hideHomeTitle" class="brand__name" style="color:#2c5f2dff;">Preschooler Profiling and Monitoring</span> </a> </div> </div> </nav> </div> <!-- Form --> <div class="container-fluid" id="homeBody"> <br> <div class="form"> <div class="form-toggle"></div> <div class="form-panel one"> <div class="form-header"> <h1>Login</h1> </div> <div class="form-content"> <form action=""> <div class="form-group"> <label for="">Username</label> <input type="text" id="username" name="username"> </div> <div class="form-group"> <label for="">Password</label> <input type="password" id="password" name="password"> </div> <div class="form-group"> <label … -
Paginating the response of a Django POST request
I'm using Django for my work project. What I need to get is all likes put by some user. Likes are put to transactions, so I am getting the list of all transactions in 'items' field, where the user put his like/dislike. There are some optional parameters that can be in the request: user_id (usually is taken from session), like_kind_id(1 for like/2 for dislike), include_code_and_name for like_kind (True/False), and page_size (integer number) for pagination. With the last parameter, I am facing the issues. The result should look like this: { "user_id":id, "likes":[ { "like_kind":{ "id":id, "code":like_code, "name":like_name, }, "items":[ { "transaction_id":transaction_id, "time_of":date_created, },... ] } ] } "Likes" is just array of 2 elements (like and dislike). So, my problem is that I cannot set pagination for "items" array as there can be a lot of transactions. I am getting the page_size from request.data.get("page_size") but cannot apply it so that the results will be paginated. I know that for GET-requests I need simply set pagination_class in views.py. Anyone knows how can I do the similar procedure for POST-request and set the page_size of pagination class to 'page_size' from data.request? =) This is my views.py: class LikesUserPaginationAPIView(PageNumberPagination): page_size … -
AttributeError 'function' object has no attribute 'predict'
I got error like this AttributeError 'function' object has no attribute 'predict' while I put the 'predict' in 19. I tried to change the attribute but it has the same problem. How to solve the error? AttributeError at /predict/result/ 'function' object has no attribute 'predict' I put this code in views.py def result(request): cls = joblib.load("pnn_parkinson.sav") gaussian_tf = lambda x: (1.0/tf.sqrt(2*np.pi))* tf.exp(-.5*x**2) lis = [] lis.append(request.GET['n1']) lis.append(request.GET['n2']) lis.append(request.GET['n3']) lis.append(request.GET['n4']) lis.append(request.GET['n5']) lis.append(request.GET['n6']) lis.append(request.GET['n7']) lis.append(request.GET['n8']) lis.append(request.GET['n9']) lis.append(request.GET['n10']) lis.append(request.GET['n11']) lis.append(request.GET['n12']) predict = cls.predict([[lis]]) result = "" if predict==[1]: result = "Positive Parkinson" else: "No Parkinson" return render(request, "result.html", {"result1":result, 'predict':predict, 'lis':lis}) I also put this code in predict.html <div class="form-inline container p-5 my-5 border text-dark" style="text-align:left"> <h2>Prediksi</h2> <form action = "result" method="GET"> {% csrf_token %} <div class="mb-3 row form-inline"> <label for="text" class="col-sm-2 col-form-label">MDVP:Fo(Hz)</label> <div class="col-md-4"> <input type="text" class="form-control" id="text" placeholder="Enter MDVP:Fo(Hz)" name="n1" required> </div> In the urls.py I put this code path('predict/result/', views.result, name='result'), -
How to connect a payment system in django?
I'm new to the Django framework and I don't quite understand how to connect the payment system to the site, at the same time, so that part of the payment for the product goes to the balance of the user who exposed it, and 10%-20% of the amount goes to the balance of the service. And what is the best way to connect a payment system for individuals.faces? -
Shopify Django App not working in Safari Browser
We have a shopify django app that is embedded into shopify. It works fine for mozilla and chrome, but not working in safari. We are getting internal server error when trying to load the page. This is the error we are getting: Failed to load resource: The server responded with a status of 500. -
Python Plotly Dash Django testing daylight savings time
I have a time series data base where datetime is stored in UTC. A Python Dash date picker and Text box allows selection of date and time. The pandas DataFrame is made timezone aware and used as the x axis as follows: x=df['cdatetime'].dt.tz_localize('utc').dt.tz_convert('Europe/London'), The chart and map plot the data correctly, showing times in the correct locale which is currently BST. However I want to test if it still works when daylight savings time ends and locale timezone is GMT. What is the recommended way to do this please ? -
What is *args in Django view? And how to pass parameters to *args
I am a novice in Django and I want to clear for myself in Views - what is *args parameters? I know what is *args in Python, but I mean what it contains in Django view, how to pass *args to view? I do understand **kwargs in view - it's a URL-variables captured, request it's an HTTP-request params captured. But what is *args and where it's useful? -
How can I use request.method in a django python file?
I'm trying to get the data from a POST but I can't use the 'request' it says "NameError: name 'request' is not defined". I tried using 'import request' it says that 'No module named 'request''. This code is from my views.py that working well. Is it possible to use this also in a python file? or there is another way? in my graph.py def update_extend_traces_traceselect(): if request.method == 'POST': post_data = json.loads(request.body.decode("utf-8")) value = post_data.get('data') print(value) -
My flask app shows, Method Not Allowed The method is not allowed for the requested URL
I was trying to deploy a machine learning model using Flask, but I can't identify why it won't let me perform a POST request to get my predicted value. Can someone let me know where did I go wrong with my code? I already tried putting request.method == "POST" earlier but my Flask app still throws the error. app.py from flask import Flask, render_template, request import joblib import numpy as np model = joblib.load('ml_model_diabetes') app = Flask(__name__) # A must at all times app.config['TEMPLATES_AUTO_RELOAD'] = True app.debug = True @app.route("/") def home(): return render_template('index.html') @app.route("/diabetesdetection", methods=['POST']) def diabetesDetection(): numOfPreg = request.form['numOfPreg'] glucose = request.form['glucose'] bloodPressure = request.form['bloodPressure'] skinThickness = request.form['skinThickness'] bmi = request.form['bmi'] diabPedigFunc = request.form['diabPedigFunc'] age = request.form['age'] arr = np.array([[numOfPreg, glucose, bloodPressure, skinThickness, bmi, diabPedigFunc, age]], dtype=float) pred = model.predict(arr) return render_template('diabetes.html', data=pred) @app.route("/heartdisease-detection") def heartDiseaseDetection(): return render_template('heart.html') if __name__ == "__main__": app.run(debug = True) diabetes.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors"> <meta name="generator" content="Hugo 0.101.0"> <title></title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"> <style> body { padding-top: 5rem; } .starter-template { padding: 3rem 1.5rem; text-align: center; } … -
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