Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django How To Add Number From Other Object
How can i add an int value inside of a field in multiple object to be displayed in another object. Lets say that i need to add all of the item that the customer have ordered previously and store them inside of all_previous_orders. Result.json [ { "customer_name": "John Doe", "order": [ { "order_name": "fruit", "how_many_order": 10, }, { "order_name": "car", "how_many_order": 1, }, ], "all_previous_orders": 11 }, ] Models.py class Customer(models.Model): customer_name = models.CharField(max_length=100) class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) order_name = models.CharField(max_length=100) how_many_order = models.IntegerField(default=0) Serializers.py class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = '__all__' class CustomerSerializer(serializers.ModelSerializer): orders = OrderSerializer(many=True, read_only=True, required=False) class Meta: model = Customer fields = '__all__' -
Django Forum | Post Question | Save Data in JavaScript Variable doesn't work
I'm currently making a Forum using Django and I have a problem. When making the "Post Question" Page. I want to save the title, description, etc. in a javascript variable because you enter the data through several pages. (see here: Post Question Title & here Post Question Description). Using this JavaScript Code: ` let post = []; function next() { let title = document.getElementById("title"); if(title.value == "" || title.value == " "){ alert("Please fill out the title field"); } else { post[0] = title.value link(); } } function next_description(){ let description = document.getElementById("description"); if(description.value == "" || description.value == " "){ alert("Please fill out the description field") } else { post[1] = description.value console.log("Title: " + post[0], "\nDescription: "+ post[1]) } } function next_tags(){ link_tags(); } function finish(){ link_finish(); } ` For test purposes I am logging the Data from the JavaScript Array when clicking the Next button in the Description File. Looking in the Dev Tools I see this: Title: undefined Description: Hello World! Why so? And How can I implement this better? -
How to annotate the sum of 2 columns in Django, when one needs to be filtered and the other parsed first?
I have x, a ManyToManyField that I want filtered by name. This can be achieved by count1 = Q(x__name__contains=UNSUPPORTED_FORMATS) I also have y, a JSONField which is really a list. I want to count the elements inside as well, after I filter out irrelevant elements. Can be achieved by count2 = len(list(filter(lambda y: not y.endswith(tuple(UNSUPPORTED_FORMATS)), object.y))) Now I'd like to annotate an entire queryset of object, with a column that equals count1 + count2 How can I create this annotation? -
Multiple choice in model
ANIMALS = (('dog','dog'), ('cat','cat')) class Owner(models.Model): animal = models.Charfield(choices=ANIMALS, max_length=10) My problem is how I can do if I have both ? -
Django-filer problem when retrieve uploaded image in Django admin interface or any http|s request
I'm a noob in Django framework, sorry for misunderstanding in some concepts. Currently, I'm trying to set up a Django app with django-filer. Django filer was installed commonly and migrations were done according to documentation. The installed apps list was updated with filer, mptt, and easy_thumbnails. The allowed host was updated with the IP of the host, debug flag was set to true and timezones and language code were also updated, as shown below. According to documentation, that's all for a basic setup of Django filer. from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True ALLOWED_HOSTS = ["192.168.230.98"] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'filer', 'mptt', 'easy_thumbnails' ] 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', ] ROOT_URLCONF = 'filerTest.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'filerTest.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } USE_I18N = True USE_TZ = True STATIC_URL = 'static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' Two images were uploaded through the Django admin interface. After images are upload, the Django admin interface can't retrieve they. Chrome development console showed … -
How to get element id with foreignkey in admin.py
I have a question. Can i pass the data for filtering another field(manytomany) in admin.py ? I need to get linked foreignkey id value. Models.py class Pansions(models.Model): ...... category = models.ForeignKey(Category, null=True, on_delete=models.PROTECT, related_name='cards', verbose_name='Category') ...... Admin.py class PansionatAdmin(admin.ModelAdmin): ..... fields = ('title', 'slug', 'category', 'tags') .... def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "tags": kwargs["queryset"] = Tag.objects.filter(category__id = "GET ID FOREIGNKEY_FIELD (caterogy)") return super().formfield_for_manytomany(db_field, request, **kwargs) I try to get data from models.py, but it not happen. Is it possible? -
Selenium chromdriver keeps on giving me error
I have been able to make use of selenium chrome for a sometime. I have tried to catch an error using try: #check if it already exist before doing anything webdriver.driver except: chromeBrowser=ChromeDriverManager().install() ....... some other code here The above code works very well, it catches the error and loads the browser without any problem. Suddenly it started giving me this error and it does not go beyond that. It does not even go into the internet at all. ERROR: The system was unable to find the specified registry key or value. Exception in thread Thread-1: Traceback (most recent call last): File "C:\Users\pure_spring\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\pure_spring\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\python_src\school\school\host\views.py", line 2333, in loopTest chromeBrowser = ChromeDriverManager().install() File "C:\python_src\venv\lib\site-packages\webdriver_manager\chrome.py", line 23, in __init__ self.driver = ChromeDriver(name=name, File "C:\python_src\venv\lib\site-packages\webdriver_manager\driver.py", line 54, in __init__ self.browser_version = chrome_version(chrome_type) File "C:\python_src\venv\lib\site-packages\webdriver_manager\utils.py", line 155, in chrome_version raise ValueError(f'Could not get version for Chrome with this command: {cmd}') ValueError: Could not get version for Chrome with this command: reg query "HKEY_CURRENT_USER\Software\Google\Chrome\BLBe acon" /v version --- Logging error --- Traceback (most recent call last): File "C:\Users\pure_spring\AppData\Local\Programs\Python\Python38\lib\logging\__init__.py", line 1081, in emit msg = self.format(record) File "C:\Users\pure_spring\AppData\Local\Programs\Python\Python38\lib\logging\__init__.py", line 925, in format … -
My html elements are not in the proper place
I am using bootstrap classes and for some reason they are not working. This is the combined templates. The ones that are switching are <div class="col-md-8"> and <div class="col-md-4" style="margin: 0;"> {% load static %} {% csrf_token %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="viewport"> <meta name="Description" content="Yoder Blog is a Custom Blog made with html css javascript and most of all python. In this version of Yoder Blog, I use django. This is a Blog mainly used by the, as you guessed it, Yoders."> <meta name="KeyWords" content="Yoder Blog, yoder blog, jdswebsites.xyz, jdoder"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="shortcut icon" href="{% static 'favicon.ico' %}" type="image/x-icon"> <link rel="stylesheet" type="text/css" href="{% static 'main.css' %}"> {% if user.is_authenticated %} {% if user.profile.theme %} <link rel="stylesheet" type="text/css" href="{% static 'light.css' %}"> {% else %} <link rel="stylesheet" type="text/css" href="{% static 'dark.css' %}"> {% endif %} {% else %} <link rel="stylesheet" type="text/css" href="{% static 'light.css' %}"> {% endif %} {% if title %} <title>Yoder Blog - {{ title }}</title> {% else %} <title>Yoder Blog</title> {% endif %} </head> <body> {% csrf_token %} <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> … -
Better way to add multiple field to this model?
In my Django project I have a model for a drinks recipe that allows up to 10 ingredients plus their amount. I am wondering if it's possible to make this in a more DRY way than I do now? This is the model I am using currently: class Recipe(models.Model): ingr_name1 = models.CharField(max_length=250, verbose_name='Ingredient') ingr_amount1 = models.DecimalField(max_digits=5, decimal_places=1, verbose_name='Amount') ingr_name2 = models.CharField(max_length=250, blank=True, null=True, verbose_name='Ingredient') ingr_amount2 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name3 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount3 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name4 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount4 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name5 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount5 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name6 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount6 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name7 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount7 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name8 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount8 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name9 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount9 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name10 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount10 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') drink_name = models.CharField(max_length=250,blank=True, null=True, verbose_name='Drink name') drink_story = models.TextField() drink_picture = ResizedImageField(upload_to='drinks/', null=True, blank=True) def __str__(self): return self.drink_name -
Django wizard form goes to the prev step instead of next step
I have a 3 step form. So when I'm at the second step and hit enter, it goes to the prev step instead of next step. This is my set up: forms.py class ContactForm1(forms.Form): subject = forms.CharField(max_length=100) class ContactForm2(forms.Form): sender = forms.CharField(max_length=100) class ContactForm3(forms.Form): message = forms.CharField(widget=forms.Textarea) views.py class Prueba(SessionWizardView): template_name = 'start.html' form_list = [ContactForm1, ContactForm2, ContactForm3] def done(self, form_list, **kwargs): return render(self.request, 'done.html', { 'form_data': [form.cleaned_data for form in form_list], }) urls.py urlpatterns = [ path('prueba', Prueba.as_view(), name='prueba') ] start.html <form action="" method="post"> {% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form.as_table }} {% endfor %} {% else %} {{ wizard.form }} {% endif %} </table> {% if wizard.steps.prev %} <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button> <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button> {% endif %} <input id='btncont' type="submit" value="Continuar"/> </form> I've use this jquery code but doesn't work because when I press enter, goes to the prev step. $(document).ready(function(){ $('#id_1-sender').keypress(function(e){ if(e.keyCode==13) $('#btncont').click(); }); }); -
How to iterate javascript function in rows?
I created a search and highlight field for my model objects. The page takes a text input and filtering the objects like Documents.objects.filter(content) I'm using read more and highlight functions to highlight the input word and show the a part of the long content. But I can't click some read mores on the row. For example I can't click 1st and 3rd row (it returns javascriot:void(0) but there is no action) but I can click the other rows. I couldn't find why? <td> <div id="highlights" > <div class="row"> <div class="col-md-12" > <div class="box"> <p class="countParawords-{{ forloop.counter }}" id="paragraph-{{ forloop.counter }}"> {{ document.content }} </p> </div> </div> <input id="typed-text-{{ forloop.counter }}" type="text" class="hidden_input" placeholder="Type text" value="{{ key_word }}"> </div> </div> </td> <script> {% for doc in documents %} var opar = document.getElementById('paragraph-{{ forloop.counter }}').innerHTML; $(document).ready(function() { var maxLength = 300; var moretxt = "...Read More"; var lesstxt = "...Read Less"; $(".countParawords-{{ forloop.counter }}").each(function() { if(opar) { var paragraph = (document.getElementById('paragraph-{{ forloop.counter }}')); var search = document.getElementById('typed-text-{{ forloop.counter }}').value; search = search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); var re = new RegExp(search, 'g'); if (search.length > 0) paragraph.innerHTML = opar.replace(re, `<span style="background: #cead00">$&</span>`); } else{ console.log("No data") } var myStr = paragraph.innerHTML if ($.trim(myStr).length > maxLength) … -
Having trouble accessing a Django database from a Python project
I’m trying to do a rudimentary connect to a database I created in a Django project (in PyCharm) from another (new) Python project in PyCharm and struggling to even get a list of tables displaying from Python. Could anyone advise on what I might be doing wrong, am I setting the name of the database incorrectly or do I need to do some step before this to connect a name to the database? I have the following connection (right panel): And my code is as follows (copied from an example): import sqlite3 try: # Making a connection between sqlite3 # database and Python Program sqliteConnection = sqlite3.connect('identifier.sqlite') # If sqlite3 makes a connection with python # program then it will print "Connected to SQLite" # Otherwise it will show errors print("Connected to SQLite") # Getting all tables from sqlite_master sql_query = """SELECT name FROM sqlite_master WHERE type='table';""" # Creating cursor object using connection object cursor = sqliteConnection.cursor() # executing our sql query cursor.execute(sql_query) print("List of tables\n") # printing all tables list print(cursor.fetchall()) except sqlite3.Error as error: print("Failed to execute the above query", error) finally: # Inside Finally Block, If connection is # open, we need to close it if sqliteConnection: … -
Cannot create URL for blob! error in react native
I am trying to send a formdata consisting of image to backend server. However I am getting cannot create url for blob error This is my code for selecting file: const selectFile = async () => { // Opening Document Picker to select one file try { const res = await DocumentPicker.pickSingle({ type: [DocumentPicker.types.allFiles], }); console.log('res simple', res); console.log('res : ' + JSON.stringify(res)); //fetch uri from the response const fileUri = res.uri; console.log('res : ' + fileUri); setSingleFile(res); // handleAcceptedFiles(res); } catch (err) { setSingleFile(null); if (DocumentPicker.isCancel(err)) { ToastAndroid.show('Canceled', ToastAndroid.SHORT); } else { alert('Unknown Error: ' + JSON.stringify(err)); throw err; } } }; And this for getting the blob: useEffect(() => { if (singleFile != null) { getData(); } }, [singleFile]); const getData = async () => { console.log('inside getData'); // console.log("singleFile",singleFile) console.log('singlefile', singleFile.uri); const response= await fetch(singleFile.uri) const blob = await response.blob() console.log('blob', typeof(blob)); const ur= URL.createObjectURL(blob) console.log('ur', ur); setBlob(blob); } -
Template error iterating through dict in jinja template
Here's my code {% for key, value in dictionary.items() %} <a class="dropdown-item" id={{key}}>{{value}}</a> {% endfor %} This is my dictionary dictionary ={"A":"A tab", "B":"B tab","C":"C tab"} I'm using python3 with jinja templates, here's the error I'm facing Django Version: 3.2.12 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '()' from 'dictionary.items()' -
Filling the database table at the expense of the other two Django
I have 3 models based on which I want to build my forms on the site: class Fields(models.Model): shortName = models.CharField(max_length=40) fullName = models.CharField(max_length=40) type = models.CharField(max_length=40) created_at = models.DateTimeField(default=datetime.utcnow()) modified_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = 'Field' verbose_name_plural = 'Fields' class Forms(models.Model): name = models.CharField(max_length=40) created_at = models.DateTimeField(default=datetime.utcnow()) modified_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = 'Form' verbose_name_plural = 'Forms' class FormFields(models.Model): formID = models.IntegerField() fieldID = models.IntegerField() class Meta: verbose_name = 'FormField' verbose_name_plural = 'FormFields' The editing of the form is planned only through the admin panel, in fields I will store all possible fields, and in forms the forms are available for use, in ormfields I want to attach fields to forms Is there any way for me when creating a record in the forms to immediately select the fields there and have it automatically added to the formfields? I tried to implement it through a filter-horizontal, but it didn't work, maybe I specified something wrong: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import * class FormsInline(admin.StackedInline): model = Forms filter_horizontal = ('Fields',) class CustomFields(UserAdmin): save_on_top = True list_display = ('shortName') inlines = [FormsInline] admin.site.register(Fields) admin.site.register(Forms, CustomFields) admin.site.register(FormFields) -
Creating a desktop app with plotly-python
I have been researching for a way to create a desktop app with plotly dynamic graphs. I have been thinking about these following options: using django, and creating the desktop app with electron.js creating an embebbed browser with PyQt5 and running the graphs from it I would like to know if one of these options is possible, or another way of running plotly in a desktop app. -
JQuery / AJAX - Async view - eventlisteners not responding and .remove() is not respecting the selection
it is my first time writing JQuery/AJAX and (silly me) I'm tryng to do something quite complex actually (or at least it is for me lol). Basically I am making an infinte carousel. I am sending the paginated data through a Django view, and I am using JQuery to load it asycronously (so to not refresh the page continuously and lose the previous content). This is the relevant code (I am not including any django related code, because everything there is working just fine, the issue is in the HTML/JS. However if you want to take a look at it, just let me know) HTML <main> <div id="outside-container"> <div id="inside-container" class="infinite-container"> {% for city in cities %} {% get_weather city.name 'metric' 'it' as weather_info %} <div class="items"> <div class="data-div"> <ul> <li><b>{% destructure weather_info 'location' 'city' %}</b> </li> <li class="weather">{% destructure weather_info 'weather' 'description' %}</li> <img src="{% destructure weather_info 'weather' 'icon' %}"> <li>{% destructure weather_info 'main' 'temperature' %}</li> <li>{% destructure weather_info 'location' 'time'%}</li> </ul> </div> <img loading="lazy" class="carousel-img" src="{{city.image.url}}"> </div> {% endfor %} </div> </div> <div id="directions"> <a id="right-button">Right</a> <a id="next-slide" href="?page=2">Next</a> </div> </main> CSS body { margin: 0; padding: 0; background: linear-gradient(-45deg, #4699f8, #fff2f7, #23a6d5, #1779e9); background-size: 400% 400%; animation: … -
Django give a Like Button using JS and DOM result ->404
I got problem with 'live' like unlike button in Django and JavaScript DOM after button is clicked I got an error POST http://127.0.0.1:8000/like/24 404 (Not Found) likePost @ javascripts.js:24 (anonymous) @ javascripts.js:40 javascripts.js:7 I don't know if the problem is in the 'await fetch' function or maybe I used the wrong class or id somewhere. Where to start? javascript.js const reloadPostHTML = async (postId) => { const homePageResponse = await fetch(window.location.href); const newHTML = await homePageResponse.text(); const newDocument = new DOMParser().parseFromString(newHTML, "text/html"); console.log(newDocument) const newPostElem = newDocument .querySelector(`[data-post-id='${postId}']`) .closest(".post"); const oldPostElem = document .querySelector(`[data-post-id='${postId}']`) .closest(".post"); oldPostElem.innerHTML = newPostElem.innerHTML; makeLikeButton(oldPostElem.querySelector(".like-button-wrapper")); }; const likePost = async (postId, csrfToken) => { await fetch(`/like/${postId}`, { method: 'POST', credentials: 'include', headers: { "X-CSRFToken": csrfToken } }); reloadPostHTML(postId); }; const makeLikeButton = (elem) => { elem.querySelector('button').addEventListener("click", (event) => { event.preventDefault(); const postId = elem.dataset.postId; const csrfToken = elem.dataset.csrfToken; likePost(postId, csrfToken); }); }; const makeLikeButtons = () => { for (let elem of document.getElementsByClassName("like-button-wrapper")) { makeLikeButton(elem); } }; makeLikeButtons(); urls.py path( 'article_detail/<int:pk>/', login_required( ArticleDetail.as_view(template_name = "web/article_detail_view.html") ), name='article_detail' ), path('like/<int:pk>', views.like, name='like'), -
'ConnectionHandler' object has no attribute cursor
I'm trying to execute a store procedure from django After searching I found using 'connection.cursor' can do that But djagno give me the error 'ConnectionHandler' object has no attribute cursor Can someone tell me why My code: def newproduct(request): if(request.method == 'POST'): data = NewProductForm(request.POST) if(data.is_valid()): p_data = data.cleaned_data with connections.cursor() as cursor: query = 'EXEC product.newproduct @product_id={0}, @product_name={1}, @product_desc={2}, @price={3},@amount={4}, @category_id={5}, @admin_id={6},@product_img={7}'.format(p_data['product_id'], p_data['product_name'], p_data['product_desc'], p_data['price'],p_data['amount'], p_data['category_id'], p_data['admin_id'], p_data['product_img'] cursor.execute(query) return HttpResponse('ok') else: return HttpResponse('Notvalid') I cannot find any solution about this problem -
Django sharing a lock between workers gunicorn
I am trying to loop inside a view function and I don’t want another worker to run the same loop. For which i am using Lock() but i am unable to achieve this. from multiprocessing import Lock import time lock = Lock() def loop_func(request): lock.acquire() # loop start for i in range(0,100): print ("did work ", i) time.sleep(1) finally: lock.release() can someone help me if there is a way where i can make the shared lock for all workers so that lock will wait till the other worker to finish and enter the loop -
Automate update of models based on conditions
I have a model class Session(models.Model): name = models.CharField(max_length=12) active = models.BooleanField(default=False) date = models.DateField() startTime = models.TimeField() The active field is set based on the date and start time. For eg - Suppose during the creation of an object, the date is for tomorrow, and let there be any time, I want to know the process and not the code on how and what to study to make this object active on that particular date and time. BY default the active field is False, or should I change the way I'm thinking to implement it? Thanks -
Postgres not using trgm index with Concat
I created a trigram index on full name where full_name = first_name || ' ' || last_name. CREATE INDEX "user_full_name_trgm" ON "user" using gin (upper(first_name || ' ' || last_name) gin_trgm_ops); I am using django queryset to filter over fullname. queryset = queryset.annotate(full_name=Concat("first_name", Value(" "), "last_name")) queryset = queryset.filter(full_name__istartswith=full_name) which generates WHERE clause as WHERE (UPPER(CONCAT("user"."first_name", CONCAT(' ', "user"."last_name"))::text) LIKE UPPER('mike%') The explain analyse shows that its not using user_full_name_trgm index. However when I use pipe to join the strings, the index is being used. WHERE (UPPER(first_name || ' ' || last_name) LIKE UPPER('mike%') How can I make django query to use the index? Can I modify query.annotate in such a way that it creates sql query without Concat? Or can I create index in such a way that it is used even with concat? -
call a property decorator through value in django module
I am having issue for the property decorator throug values from the models, The models is class Bills(models.Model): salesPerson = models.ForeignKey(User, on_delete = models.SET_NULL, null=True) purchasedPerson = models.ForeignKey(Members, on_delete = models.PROTECT, null=True) cash = models.BooleanField(default=True) totalAmount = models.IntegerField() advance = models.IntegerField(null=True, blank=True) remarks = models.CharField(max_length = 200, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) class Meta: ordering = ['-update', '-created'] def __str__(self): return str(self.purchasedPerson) @property def balance(self): return 0 if self.cash == True else self.totalAmount - self.advance i am working on the union method, to display credit bills and any paid transaction are there i am calling the method as bill_trans = Bills.objects.filter(purchasedPerson__id__contains = pk, cash = False).values( 'purchasedPerson__name', 'cash', 'totalAmount', 'remarks', 'created') in the place of total amount i needed balance property is that possible or there is there any other method to make union for the class MemberTrans(models.Model): purchasedPerson = models.ForeignKey(Members, on_delete = models.PROTECT, null=True) paid = models.BooleanField(default=False) amount = models.IntegerField() remarks = models.CharField(max_length = 200) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) class Meta: ordering = ['-update', '-created'] def __str__(self): return str(self.purchasedPerson) mem_trans = MemberTrans.objects.filter(purchasedPerson__id__contains = pk).values( 'purchasedPerson__name', 'paid', 'amount', 'remarks', 'created' ) Bill_trans should union with mem_trans -
django.db.utils.operationalerror unable to open database file
I have been struggling finding a solution to my issue "django.db.utils.operationalerror unable to open database file ". I have changed permissions and set my path to an absolute one yet still have the same error. this is my settings.py file """ Django settings for bastionblog project. Generated by 'django-admin startproject' using Django 4.1.3. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path import os from main import constants # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIRS = os.path.join(BASE_DIR,'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = constants.SECRET_KEY # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['77.68.125.183'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main' ] 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', ] ROOT_URLCONF = 'bastionblog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIRS], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'bastionblog.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES … -
How to validate Child model (StackedInline) fields based on a value of Parent model's field in Django?
I have following structure. models.py class Parent(models.Model): PROVIDER1 = "Provider1" PROVIDER2= "Provider2" PROVIDERS= ( (PROVIDER1, "Test Provider One"), (PROVIDER2, "Test Provider Two"), ) provider = models.CharField( choices=PROVIDERS, max_length=255, default=PROVIDER1, ) # Few more parent fields will be here class Child(models.Model): some_field= models.CharField(max_length=255) # Few more fields will be here parent = models.ForeignKey( Parent, on_delete=models.CASCADE ) admin.py class ChildFormset(BaseInlineFormSet): def clean(self): super().clean() for form in self.forms: if not form.is_valid(): return # errors exist, so return class ChildInline(admin.StackedInline): model = Child formset = ChildFormset extra = 1 min_num = 1 validate_min = True max_num = 1 can_delete = False @admin.register(Parent) class Parent(admin.ModelAdmin): form = ParentForm inlines = [ ChildInline, ] forms.py class ParentForm(forms.ModelForm): class Meta: model = Parent fields = "__all__" def clean(self): cleaned_data = super().clean() # How to access Child model's fields values here to validate them? class Media: # Custom JS to show/hide provider specific fields/divs js = ("js/mycustom.js",) Requirement: When user choose Provider 1 in the Parent I would like to do following Display Child Model's fields (Inline). Validate Child model's fields on submit. I was able to use custom JavaScript for first requirement (hiding and showing fields). But for second requirement I am not able to get the …