Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I add a custom filter in a django child model?
I'm pretty new to django and I'm working on an existing app that I did not write. The app handles some document management activities and whenever a document thumbnail is displayed, it currently displays all associated metadata. In my case, some of the metadata rows are unwanted (guid's are not very human friendly) and I therefore want to exclude some of the metadata. There are principally three tables, one for Documents, One for Metadata types, and a join table that ties them together. The guts of the join table are like so: class DocumentMetadata(models.Model): document = models.ForeignKey( on_delete=models.CASCADE, related_name='metadata', to=Document, verbose_name=_('Document') ) metadata_type = models.ForeignKey( on_delete=models.CASCADE, to=MetadataType, verbose_name=_('Type') ) value = models.CharField( blank=True, db_index=True, ), max_length=255, null=True, verbose_name=_('Value') ) The current code does this as it builds the thumbnail: queryset=context['object'].metadata.all() I've got a test version like so: context['object'].metadata.exclude(name__endswith='_Id') I have a convention where the guid metadata field name ends in _Id, and this filter works fine and does what I want it to do right now. I don't like it though. In future, I want to add a human_readable boolean field to the metadata type table and there are other places in the code base where I'll want to sift … -
JavaScript dropdown hidden in a css grid column
I have an admin header from Django which is divided in 2 columns with css grid. I included a JavaScript dropdown effect on the user icon to show other elements like "Change Password" and "Log Out" but the problem is that dropdown stays hidden inside the column, doesn't show outside. How can I fix this? Thanks in advance, A newbie in web development Images attached will show exactly the situation described above: Forced height of header to show the dropdown: Below you can find partial Django code: {% load i18n static %}<!DOCTYPE html> {% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %} <html lang="{{ LANGUAGE_CODE|default:"en-us" }}" {% if LANGUAGE_BIDI %}dir="rtl"{% endif %}> <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" type="text/css" href="{% block stylesheet %}{% static "admin/css/base.css" %}{% endblock %}"> {% block extrastyle %}{% endblock %} {% if LANGUAGE_BIDI %}<link rel="stylesheet" type="text/css" href="{% block stylesheet_rtl %}{% static "admin/css/rtl.css" %}{% endblock %}">{% endif %} {% block extrahead %} {{ block.super }} <script> /* When the user clicks on the button, toggle between hiding and showing the dropdown content */ function openDropdown() { document.getElementById("myDropdown").classList.toggle("show"); } // Close the dropdown if the user clicks outside of it window.onclick = function(event) { if … -
Save a list of strings in django sql-lite database from view
I want to save a list of strings in django sql-lite database from view. Here is my piece of code def home(request): if request.method=='POST': tags=request.POST['tag'] tweets=scrape(tags) tweets=preprocessing(tweets) tweet=Tweet() tweet.text='save the tweet' tweet.save() return render(request,'home.html',{"tweet":tweets}) else: all_tweets=Tweet.objects.all return render(request,'home.html',{"old_tweet":all_tweets}) The following three-line can save a single string (tweet) in my database tweet=Tweet() tweet.text='save the tweet' tweet.save() But I have a list of strings (tweets) that I want to save in the database. I want to save the output of preprocessing(tweets) which is a list in my database. If I use a loop, I think it makes the process too much slow. So is there any efficient way. Thanks -
How do I insert multiple blocks into the base.html in Django?
Possibly I'm misunderstanding the inheritance of templates in Django, but why doesn't the below code work? Both child templates are inheriting from the parent template with different block names. base.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>test</h1> {% block index %}{% endblock %} {% block nav %}{% endblock %} </body> </html> index.html {% extends 'blog/base.html' %} {% block index %} <h1>This is the index.html page</h1> {% endblock %} nav.html {% extends 'blog/base.html' %} {% block nav %} <h1>This is the nav.html</h1> {% endblock %} I'm trying to grasp the concept of using multiple blocks so that I can place them on the templates that I need. -
django-ckeditor jquery call to display real-time editing
I am creating a django app that uses a RichTextField from django-ckeditor. I'm displaying a side-by-side of what the form will look like once submitted by using jQuery for my input fields. When transitioning from a TextField to RichTextField my jQuery function stopped working. // project.js // old keyup function for TextField var textInput = $('#id_text'); function setText(value) { $('#preview-text').text(value) } setText(textInput.val()) textInput.keyup(function () { var newText = $(this).val() setText(newText) } I have attempted this: // project.js // new jQuery function var textInput = CKEDITOR.instances['id_text'].getData(); function setText(value) { $('#preview-text').text(value) } setText(textInput) // removed .val() as this caused a TypeError: textInput.val is not a function textInput.keyup(function () { var newText = $(this).val() setText(newText) } This gives me TypeError: textInput.keyup is not a function. I would like to continue using the .keyup() function as a prompt for updating the side-by-side preview, but it appears it will need to be reworked. // project.js var textInput = $('textarea#id_text'); // specifying textarea yields [object Object] in HTML function setText(value) { $('#preview-text').text(value) } setText(textInput) textInput.keyup(function () { var newText = $(this).val() setText(newText) } The above function yields [object Object] in the <span id='preview-text'></span>. Previous post I used for the CKEDITOR.instance[].getData() call here. Any insights into how … -
How save selected option in django template?
After submitting the form, I can't save selected choice. Please help. <select id="category" class="form-control" name="category"> {% for option in categories %} <option value="{{option.name}}" {% if option.name == 'I don't know what's dynamic value write here(or how get value of POST-parameter' %}selected{% endif %}> {{ option.name }} </option> {% endfor %} </select> -
Catch post_save signal
Django 3.0.5. apps.py from django.apps import AppConfig from django.db.models.signals import post_save from django.dispatch import receiver class NewsConfig(AppConfig): name = 'news' def ready(self): from .models import News # Breakpoint 0 @receiver(post_save, sender=News) def handle_news_save(sender, **kwargs): print("Working") a = 0 # Breakpoint 1 models.py class News(models.Model): news_text = models.TextField() settings.py INSTALLED_APPS = [ ... 'news.apps.NewsConfig', ] The problem At Breakpoint 0 the interpreter stops when I run the application. That is at the next line Django gets to know that I'm catching the signal. But when I save an instance of News in admin site, at Breakpoint 1 the interpreter doesn't stop. And, of course, no printing happens. Could you help me catch the signal? -
Python Django SyntaxError: invalid syntax
I try today crete my first own site ,but i have error . When i run manage.py : File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax In folder have : mysite/ manage.py mysite/ asgi.py __init__.py settings.py urls.py wsgi.py Maybe I wrong insall django or its another error ? Thanks -
Djnago: how to sum value for a specific field
I have the following situation Sottocategoria | Quantità type_1 | 100.00 type_2 | 100.00 type_1 | 100.00 I would to obtain a new table that give me the following view: Sottocategoria | Quantità type_1 | 200.00 type_2 | 100.00 here my models.py with "quantita" and "sottocategoria" fields' situation: class Tipologia(models.Model): nome= models.CharField('Categoria', max_length=30) class Sottocategoria(models.Model): tipologia = models.ForeignKey(Tipologia, on_delete=models.CASCADE) name = models.CharField( max_length=30) class Materiale(models.Model): conto = models.CharField('Conto', max_length=30, choices=( ('MATERIA PRIMA', 'MATERIA PRIMA'), ('SUSSIDIARIA', 'SUSSIDIARIA'), )) tipologia = models.ForeignKey(Tipologia, on_delete=models.SET_NULL, null=True) sottocategoria = models.ForeignKey(Sottocategoria, on_delete=models.SET_NULL, null=True) quantita=models.DecimalField('Quantità',max_digits=5) -
Django Python, Pass a dictionary and print it's content in html template
I have this function just for learning and want to print out the xxxxx and yyyyy on the html page. I have tried everything but the best I can get is aaa bbb def index(request): template = loader.get_template('bsapp/index.html') listan = {'aaa':'xxxxxx','bbb':'yyyyyy'} context = { 'listan': listan } return HttpResponse(template.render(context, request)) This is the html page, how would I write it?: {% for item in listan %} {{ item }}<br> {% endfor %} -
Save anonymous user data and map with the user after registeration or login in django
Hello I have an app where user come he get list of items he select item as many he wish then he click on "add to cart " where he get redirect to page where he sees the item selected and total price , Now to proceed further i want user to login or register and after he login or register he gets map with the item and price he selected and data get save in database i have an app which works perfect for login user but i want it for anonymous user who first select items and then go for registeration/login. models.py class UserSelectTest(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) testselected = models.TextField() class UserTest(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255) email = models.EmailField() number = models.IntegerField() location = models.CharField(max_length=255) time = models.IntegerField() totalprice = models.CharField(max_length=255,null=True) test_submitted = models.BooleanField() views.py def ResultTest(request): var = request.POST.get('selectedTests') abc = UserSelectTest() abc.user = request.user abc.testselected = request.POST['selectedTests'] abc.save() def PostTest(request): if request.method == 'POST': test = UserTest() test.user = request.user test.name = request.POST['name'] test.email = request.POST['email'] test.number = request.POST['number'] test.location = request.POST['location'] test.time = request.POST['time'] test.totalprice = request.POST['price'] test.test_submitted = True test.save() I views i have two function where "ResultTest" stores the … -
How to submit value when link is clicked?
I want to print id of link when it clicked. I have tried below code but being naive i do not know what is wrong?? -
Why isn't Django passing ImageField data via ListView to a template?
This is my first programming project, and first question on StackOverflow - so please be gentle! I've been good and checked all the relevant existing questions and answers - apologies in advance if I've missed it. I have a model that contains images: models.py class Image(models.Model): image = models.ImageField(upload_to='portfolio-images/', blank=False, null=False) uploaded_by = get_user_model() uploaded = models.DateTimeField(auto_now_add=True, editable=False) alt_text = models.CharField(verbose_name='Alternate text', max_length=200, blank=True, null=True) def __str__(self): return self.alt_text def get_absolute_url(self): return reverse('image_detail', args=[str(self.alt_text)]) Which is handled by these views: views.py class ImageDetailView(DetailView): model = Image context_object_name = 'image' template_name = 'image_detail.html' class ImageListView(ListView): model = Image context_object_name = 'images' template_name = 'image_list.html' Now when these are passed to their relevant templates, the DetailView works as it should - passes the url to the template using this code, and the image renders in the browser. image_detail.html ... <img src="{{ image.image.url }}" alt="{{ image.alt_text }}"> ... But the ListView does not pass the url or alt-text into the template. Here's the code I use to call it in the template: image_list.html {% for image in images %} <img src="{{ images.image.url }}" alt="{{ images.alt_text }}"> {% endfor %} Weirdly, it is getting a response from the database, as the loop creates 5 … -
My table is becoming very wide because of a table row item is a long url
I am working with Django and Bootstrap to create this table. {% extends "jsonparser/base.html" %} {% block content %} {% if data %} <h1>{{ data }}</h1> {% else %} <table class="table table-hover"> <thead> <tr> <th scope="col">Property</th> <th scope="col">Actual Value</th> </tr> </thead> <tbody> <tr> {% for list in adobe %} <tr> {% for i in list %} <td>{{i}}</td> {% endfor %} </tr> {% endfor %} </tr> </tbody> </table> {% endif %} {% endblock content %} Right now when I view the output, the table is very long horizontally because of one of the properties I am printing is a very long URL. -
Django : Find 'difference' between two models
Say I have two models as follows - class DID_Definition_Model(models.Model): # DID to Region-Carrier Mapping did_number= models.CharField(max_length=32, validators=[alphanumeric], primary_key=True) class DID_Number_Assignment_Model(models.Model): #DID Number Assignment did_selector = models.ForeignKey(DID_Definition_Model, on_delete=models.CASCADE, primary_key=True, unique=True) I want to report on the 'difference' in entries, (possibly via difference method) which may be available in DID_Definition_Model did_number field but not in DID_Number_Assignment_Model did_selector field. In my failing attempt my thought process was to create a query which will contain all entries of did_number. Then repeat the same procedure to get all entries of did_selector. Finally compare the two queries using difference method. But I kind of got stuck at the first stage - getattr(DID_Definition_Model, did_number) Traceback (most recent call last): File "", line 1, in NameError: name 'did_number' is not defined * But the above is simply not possible as did_number is a valid field of DID_Definition_Model Any guidance will be helpful as I have been through multiple message boards and could not seem to find any way out. -
How to print extracted dictionary values in input fields of html (placeholder)
I am quite new to django and struggling to do something very simple.I am working on django based pdf data extraction project.in this project i am taking invoice pdf from user and then extracting fields like issuer, invoice_number, date, amount, currency, other.and then save those data into database.everything works fine but the only thing is i want to print extracted data in html forms input fields.guys could you please help me this is the flow input invoice.pdf --> extract button --> print values in inputs fields of html form --> submit after pdf extraction i got this dictionary {'issuer': 'Freefiber', 'amount': 29.99, 'date': '02/07/2015', 'invoice_number': '562044387', 'currency': 'EUR', 'other': {'amount_untaxed': 24.99, 'date_due': '02/08/2015', 'vat': 'FR60421938861', 'line_number': 'FO10479674', 'client_id': '10577874', 'desc': 'Invoice from Free'}} expected output here is my code views.py from django.shortcuts import render, redirect, HttpResponse from .models import InvoiceList import os from .forms import browse from .models import handle_uploaded_file from invoice2data import extract_data # Create your views here. def index(request): invoices = InvoiceList.objects.all() context = { 'invoices': invoices, } return (render(request, 'index.html', context)) def create(request): print(request.POST) issuer = request.GET['issuer'] invoice_number = request.GET['invoice_number'] date = request.GET['date'] amount = request.GET['amount'] currency = request.GET['currency'] other = request.GET['other'] invoice_details = InvoiceList(issuer=issuer, invoice_number=invoice_number, date=date,amount=amount,currency=currency,other=other) … -
Django login redirects to login page
During development I was able to login and logout just fine. However in production I am experiencing some headaches. When I login the page just reloads. I have it set to redirect to the home page upon login and all I have needed before was this: urls.py urlpatterns = [ path("", include('main.urls')), path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), # For /accounts/login page ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) templates/registration/login.html {% extends "base.html" %} {% block content %} <div class="container"> <div class="card"> {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success"><i class="fas fa-sign-in-alt"></i> Login</button> <input type="hidden" name="next" value="{{ next }}" /> </form> {# Assumes you setup the password_reset view in your URLconf #} <p><a href="{% url 'password_reset' %}">Lost password?</a></p> </div> </div> {% endblock content %} -
Django Static Refer To Wrong URL
I am using Django (v. 3.0.5). I am trying to load the image from database (from FileField) When I use <p>{{ post.profile_image.url }}</p> in HTML it returns me a good path (static/user_profile/user_1_default_profile_image.png) but when I put this into the img tag <img src="{{ post.profile_image.url }}" alt="image"> I have an 404 error GET /profile/static/user_profile/user_1_default_profile_image.png HTTP/1.1 404 2598" Template URL: profile/ Of course I used {% load static %} tag above the <img src="{{ post.profile_image.url }}" alt="image"> tag and I also configured the static files STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] PS Sorry for my broken English -
Migration error on github actions with Django
I’m having trouble getting github actions to work with a django app. When I try to run migrations it fails, though if I install it as a new app on my computer the migrations run fine. I’m brand new to github actions so I don’t really know what I’m doing, but I’ve been struggling with this for a bit today and figured I’d ask. Here is my actions file: https://gist.github.com/pjhoberman/8333df201176bfc00e506ed7d8b4977a#file-django-yml-L52 - it’s failing at the highlighted line 52. And the error is cumbersome and in full here: https://gist.github.com/pjhoberman/8a8ebd9838a9901e1c9929c219549f50 But is basically this: psycopg2.errors.UndefinedTable: relation "listings_category" does not exist ...ory"."slug", "listings_category"."parent_id" FROM "listings_... -
Django I18n - issues with translating in Python code
I decided to add an English translation to my Russian language website. I decided to start with translating strings in my Python code. This is how I tried to do it: (project name)/settings.py: MIDDLEWARE = [ # ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', # ... ] # ... LANGUAGE_CODE = 'en' TIME_ZONE = 'Europe/Moscow' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), ] LANGUAGES = [ ('en', 'English'), ('ru', 'Русский'), ] (app name)/views.py: from django.contrib import messages from django.utils.translation import gettext as _ # ... # in a function based view messages.success(request, _("Тема изменена успешно!")) Then, I run: python3 manage.py makemessages --ignore="venv" --ignore="collectedstatic" -l en This creates file in conf/locale/en/LC_MESSAGES called django.po. When I open it, it contains this: # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2020-04-24 21:08+0300\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <LL@li.org>\n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: front/views.py:29 msgid "Тема изменена успешно!" msgstr "" I change the last msgstr … -
Serving media files in Chunks
I have huge video files (size: 200mb average) stored in my media folder. I fetch those files using os.listdir and then store them in dictionary, with respect to storing filename, date (fetch from file) and time (fetched from file) against each file in the dir '../media/videos/'. Refer to code below: file_names = [os.path.join('../media/videos/',fn) for fn in os.listdir(path) if fn.startswith(example_20_Apr_20)] file_names_final=[] for item in file_names: tmp=item.split("-") file_names_final.append({'file_name':item,'date':"-".join(tmp[-6:-3]),'time':"-".join(tmp[-3:-1])}) print(file_names_final) #for debugging Then i place those files in the template. Refer to code section below: {% for i in files %} <div class="col"> <div class="alert-card clickable-feed-wrapper"> <div class="old-feeds-video-wrapper"> <video class="video-container" preload="auto"> <source src="{{ i.file_name }}#t=0.5" type="video/mp4"> </video> </div> <div class="alert-details"> <span class="h">Location : <span class="d feed-location-info">{{location}}</span></span><br/> <span class="h"><span class="d feed-pilot-info"></span></span> <span class="h">Date : <span class="d feed-time-info">{{i.date}}</span></span><br/> <span class="h">Time (24h): <span class="d feed-time-info">{{i.time}}</span></span> </div> </div> </div> {% endfor %} FYI, im passing file_names_final in context as files The problem that I'm running into is, when I try to stream the files from external network, I just can't load the huge files that may size around 200mb, however i'm able to stream the files that are roughly within the 10mb to 50mb ballpark. This may primarily be due to the internet connectivity, and it is … -
How to upload files in Django without using form
Trying to upload a file without using forms.py, I tried with these codes but it only saves the location into the corresponding model, file is not saved in the media folder and can't able to open it in admin. upload_file.html <form id="" method="post" action="#"> {% csrf_token %} <div class="formin"> <input type="text" name="desc" id="desc" placeholder="Description" /><br> <input type="file" id="myFile" name="filename"> <input type="submit" value="Upload" /> </div> </form> models.py class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.description views.py def form_upload_view(request): if request.method == "POST": descrip = request.POST.get("desc") file = request.POST['filename'].data print(file) obj = Document(description=descrip, document=file) obj.save() return HttpResponse("<h1>Success</h1>") else: return render(request, "upload/upload_file.html", {}) In the document FileField after the submission of the form the location of file http://127.0.0.1:8000/media/index.jpeg is stored. But this file in local machine is not reflected in media folder. -
Running an external python script when a user does something on a django website
I want to build some sort of django app that can react to a change in an SQL database and handle all activate some external python scripts. I, being a django noob, have no idea to do this but I have few ideas and am looking for some help. My first idea is to have a script simply react to a change in an SQL database. I would just have a script running and check if the size of the database changes. If it does, then it will read the latest entry and do something with that data. My second idea is to simply activate a python script when someone clicks a certain button on the website. I also have no idea how to execute this plan. If any of these ideas are dumb, or there is a better way to do things, please let me know. If these ideas are viable, then please let me know what I can research to make these happen. I have been searching and searching and have been able to either find nothing or not understand what I have found Thanks! -
MySQL query not visualizing on Django HTML page
I'm currently trying to take specific queries of databases and display them on an HTML page. I'm working on the Django framework with mySQL as the DB. I've run the queries successfully in mySQL and the server isn't giving me any errors so I'm lost as where to go next. My views.py file where I have the queries from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.decorators import login_required from student.models import StudentDetails, CourseDetails from django.db import connection from django.core.paginator import Paginator def dictfetchall(cursor): "Return all rows from a cursor as a dict" columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for row in cursor.fetchall() ] # Create your views here. @login_required def home(request): cursor = connection.cursor() cursor.execute("SELECT COUNT(*) 'totalstudents' FROM student_studentdetails") cursor.execute("SELECT COUNT(*) 'totalseniors' FROM student_studentdetails WHERE year='Senior' ") cursor.execute("SELECT COUNT(*) 'totaljuniors' FROM student_studentdetails WHERE year='Junior' ") cursor.execute("SELECT COUNT(*) 'totalfreshman' FROM student_studentdetails WHERE year='Freshman' ") cursor.execute("SELECT COUNT(*) 'coursecount' FROM student_coursedetails") cursor.execute("SELECT AVG(GPA) 'averagegpa' FROM student_studentdetails") homedata = dictfetchall(cursor) return render(request, 'student/home.html', {'data' : homedata}) My home.html where they should be loading. The aesthetics of how they are displayed is secondary right now, I'm still trying to figure out how to pull the data without having … -
Django different 'exact Item lookups' multiple times optimizations
I have an table with the attributes (id, email, score, date_added, state, fk, etc.) which is stored into a MySql database. Currently the data will be ingested in an additive manner where the same entry (new id) can be added, but with a more recent date and changed state (to maintain history). I use a single Django endpoint that will accept a single entry to ingest. This endpoint first checks if it is a new email, or already existed by querying model.objects.filter(email__iexact=email).first(). This query is used so that the remaining row data fk, etc. can be copied without reprocessing. Is there a way to optimize and increase the speed of this process/lookup (possibly with Django caching or simple adjustments)? If it's not possible, what are the biggest design limitations that would need to be changed to allow for database query improvements/optimizations. Notes: The table likely to become too large to store as a python dict, I have currently tried wrapping the single entry call with a batch_ingest method that uses an atomic transaction and the entire batch to reduce the write at each call; This seems to help reduce disk usage while processing, but doesn't reduce the lookup time per …