Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to dynamically load generated SVG
I am trying to load an SVG graphic during runtime to my Django webpage. The graphic will be generated on request and depends on different user inputs. If I use templates like this: {% extends "app/base.html" %} {% block content %} <h1>Internal Requirements Tree</h1> <div> {{ svg }} </div> {% endblock content %} with the corresponding view: def internal_reqs(request): with open("some/path/to/graph.svg") as f: base_image = f.readlines() # remove XML header while '<svg ' not in base_image[0]: base_image.pop(0) context = { 'title': 'Title', 'svg': '\n'.join(base_image), } return render(request, 'app/graph.html', context) the SVG source will be printed but not rendered. But if I put the same string from the svg directly into the template like this: {% extends "app/base.html" %} {% block content %} <h1>Internal Requirements Tree</h1> <div> {{ svg }} </div> <div class="center"> <svg width="570pt" height="100pt" viewBox="0.00 0.00 570.00 100.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 96)"> .... </g> </svg> </div> {% endblock content %} it will be rendered just fine. How to do it correctly? -
how can i define default value for urlls parameters in django?
views.py from django.views.generic import ListView from .models import Staff class StaffListView(ListView): model = Staff template_name = 'staff/staff_list.html' def get_queryset(self): return Staff.objects.filter(websites__path=self.kwargs['web']) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('<str:web>/staff/', include('staff.urls')), # I want to set web=chemical, if url is http://127.0.0.1:8000/staff ] -
how to do bug fix without resetting database
I have hosted my Django app in Heroku with Github. So when I do a bug fix and I re-deploy my page. My database resets. I know that my database reset because Heroku is just deploying my GitHub branch and my GitHub database is not updating with my Heroku database. So what can I do to keep my database same and I can also do modifications? and if I need how can I download or store my main Heroku database in somewhere else? note: I'm using Django default database sqlite3 -
show existing file path using javascript and django
when a user update his info the existing data should be displayed in input fields.In my problem resume file name not displaying on the right place. i want to display the file name in No file chosen place with javascript. Any way??? The Code is tooo big so i can't copy the entire code this is update resume input field <div class="form-group"> <label>Resume</label> <span style="color:#ff0000">*</span> <br> <span id="resid"></span> <input type="file" name="resume" id="resume_Id" class="form-control" required> </div> in here passing the database value to update field <a href="#editCorporateTrainers" class="edit" title="Edit" data-toggle="modal" onclick="editCorporateTrainersdetails( name = '{{ i.Name}}', email = '{{ i.Email}}', phone = '{{ i.Phone_Number}}', rate = '{{ i.Rate}}', skills = '{{ i.Skill.all}}', description = '{{ i.Description}}', resume = '{{ i.Resume}}', trainer_Id = '{{i.id}}' );" > <i class="fa fa-edit" style='color:#8773b3' data-toggle="tooltip"></i></a> </td> this is the function currently calling in script tag function editCorporateTrainersdetails(name ,email, phone ,rate ,skills ,description ,resume ,trainer_Id){ document.getElementById('name_Id').value = name; document.getElementById('email_Id').value = email; document.getElementById('phone_Id').value = phone; document.getElementById('rate_Id').value = rate; document.getElementById('skillId').value = skills; document.getElementById('description_Id').value = description; document.getElementById('trainer_Id').value = trainer_Id; document.getElementById('resid').innerHTML = resume; } -
Should I use two Postgres databases for Django on Heroku - dev & prod?
I'm quite new to Django. I'm building a Django app and want to deploy it to Heroku with Postgres database. I already installed a Postgres app on Heroku, and have my credentials. Should I have two databases - one Postgres database with its own settings locally for dev, and one that is on Heroku? The app is quite simple, so I don't necessarily need two databases, but maybe it is needed for deployment. -
Aggregate makes extra queries
In my model, I have a book and review class and I want to calculate the average rating. I use aggregate and Avg for that models.py class Book(models.Model): author = models.ManyToManyField(Author, related_name='books') title = models.CharField(max_length=200) description = models.TextField(max_length=3000) price = models.DecimalField(max_digits=6, decimal_places=2) publisher = models.CharField(max_length=200) language = models.CharField(max_length=200) pages = models.PositiveSmallIntegerField() isbn = models.CharField(max_length=13, validators=[validate_isbn(), MaxLengthValidator(13)]) cover_image = models.ImageField(upload_to='books/images') publish = models.BooleanField(default=True) @property def average_rating(self): avg_rating = Review.objects.filter(book_id=self.id).aggregate(Avg('rating')) return avg_rating['rating__avg'] def __str__(self): return self.title class Review(models.Model): RATING = [ (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), ] book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='reviews') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) description = models.TextField() rating = models.PositiveSmallIntegerField(choices=RATING, default=5) date_added = models.DateField(auto_now_add=True) objects = ReviewManager() def __str__(self): return f"{self.user.username} {self.book.title}" Now for each book, I have one extra query How can I fix this issue? -
Heroku Application Error while Deploying Django application
enter image description here Please help me with this error -
How do I set uploaded image back to default image when deleted?
I have a simple blog app, when I update an article and remove photo I want it to use default photo. it selects that image on create but when updating it throws an error. here's my Models.py code. image = models.ImageField( upload_to="uploads/articles/", null=True, blank=True, default="uploads/articles/noimage.png", ) the error I get when I remove image during update. Error during template rendering The 'image' attribute has no file associated with it. <img class='article-img' src="{{article.image.url}}" alt=""> -
How to pass JavaScript array to Django views
Background: I am trying to build a small web application, where I need to show data based on checkboxes checked by the user. I am very new to coding and somehow decided to start with Django. I did the following: I used HTML form for checkbox that does nothing on submit JavaScript for checkbox validation and to collect user input in an array. I want to pass this array variable to Django views.py so I can try to filter the data and then display to the user and I am stuck. I tried Jquery (see result_output function) but I am not able to make it work. Below are the codes. Any help will be highly appreciated. JavaScript: function nextPrev(n) { // This function will figure out which tab to display var x = document.getElementsByClassName("tab"); //exit the function if any checkbox is not checked if(n==1 && !validateFrom(currentTab)) return false; //console.log(all_filter_value[0]) //console.log(all_filter_value[1]) // Hide the current tab: x[currentTab].style.display = "none"; document.getElementsByClassName("step")[currentTab].className += " finish"; // Increase or decrease the current tab by 1: currentTab = currentTab + n; // if you have reached the end of the form... : if (currentTab >= x.length) { //...the form gets submitted: document.getElementById("questbox").style.display="none"; result_output(); return false; … -
Django filter ManyToManyField
There is a Django filter problem with ManyToManyField that bothers me. I have a task that I want the creator and selected members of the creator to view. Now I have a problem that the specified member can be viewed normally, but when the creator views it, there will be the same number of duplicate tasks as the specified member. I can't understand this problem, it is not what I expected. #views class TaskView(LoginRequiredMixin, View): def get(self, request): projecttask_all = ProjectTask.objects.filter(Q(owner=request.user.username) | Q(task_member=request.user)) print(projecttask_all) #print results <QuerySet [<ProjectTask: user1>, <ProjectTask: user1>]> // My understanding should be like <QuerySet [<ProjectTask: user1>]>, because the owner is not in projecttask_task_member,but it is not. #model class ProjectTask(models.Model): title = models.CharField(max_length=100, verbose_name='title', default='') owner = models.CharField(max_length=30, verbose_name='owner') task_member = models.ManyToManyField('UserProfile',related_name='task_member', blank=True, null=True) #mysql projecttask | id | title | owner | | -- | ----- | ----- | | 1 | test | user1 | projecttask_task_member | id | projecttask_id | userprofile_id | | -- | -------------- | -------------- | | 1 | 1 | 8 | | 2 | 1 | 9 | -
How to pass an image path to setAttribute in Django?
test.addEventListener('click',function(e){ console.log("click"); var targetElement = event.target || event.srcElement; clickedVal = targetElement.innerText; targetElement.innerText=""; input = document.createElement("input"); input.value = clickedVal; targetElement.append(input); img = document.createElement("img"); // It's not working here // "{% static 'images/confirm.svg' %}" is incorrect. Then how to correct it? img.setAttribute("src", "{% static 'images/confirm.svg' %}"); input.parentElement.append(img); }) "{% static 'images/confirm.svg' %}" is incorrect. Then how to correct it? Thanks -
I want to add like unlike feature to my blog site, everythin is okay there, like and unlike objects are being created.. But I'm getting NoReverseMatch
I want to add like unlike feature to my blog site, everythin is okay there, like and unlike objects are being created.. But I'm getting NoReverseMatch when I'm clicking the Like and Unlike..and the problem is I can't figure it out why I'm getting this...my models.py, views.py, urls.py, blog_page.html...all are attatched here.. plz try help me solve this **models.py** from email.policy import default from django.db import models from django.contrib.auth.models import User # Create your models here. class Blog(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200, verbose_name="Put a Title") blog_content = models.TextField(verbose_name="What is on your mind") blog_image = models.ImageField(upload_to="blog_images", default = "/default.png") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Comment(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name = "blog_comment" ) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name = "user_comment") comment = models.TextField() comment_date = models.DateField(auto_now_add=True) def __str__(self): return self.comment class Like(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name = "blog_liked") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name = "user_liked") class Unlike(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name = "blog_unliked") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name = "user_unliked") **views.py** from django.shortcuts import render from . models import Blog, Comment, Like, Unlike # Create your views here. def home(request): blogs = Blog.objects.all() context = {'blogs': blogs} return render(request, 'blog_app/home.html', … -
How to pass an image path to setAttribute method in the template of Django?
In the template file, I need to pass the image path "{% static 'images/confirm.svg' %}" to setAttribute method. // js test.addEventListener('click',function(e){ var targetElement = event.target || event.srcElement; clickedVal = targetElement.innerText; targetElement.innerText=""; inpt = document.createElement("input"); inpt.value = clickedVal; targetElement.append(inpt); inpt.setAttribute("images", "{% static 'images/confirm.svg' %}") }) But this didtn' work. How should I do? Thanks. -
Uploading File Failed to message the error in the website
I am using Django and would like to upload a file which will then save it to the database. I have an HTML where the user can upload the file. How can you successfully caught errors or message the error in the website like: If it is not csv format If the columns are not found or incorrect columns Date causes validation format - should be YYYY-MM-DD when the choices are unavailable View def simple_upload(request): data = None try: if request.method == 'POST': data = request.FILES['myfile'] if not data.name.endswith('.csv'): messages.warning(request, 'The wrong file type was uploaded') return HttpResponseRedirect(request.path_info) data = pd.read_csv(data, header=0, encoding="UTF-8") for index, rows in data.iterrows(): userid = rows["User ID"] generalid = rows["User ID"] date = rows["Date"] if rows["User ID"] else datetime.date.today() description = rows["Description"] if rows["Description"] else " " address = rows["Address"] if rows["Address"] else " " latitude = rows["Latitude"] if rows["Latitude"] else " " longitude = rows["Longitude"] if rows["Longitude"] else " " status = rows["Status"] if rows["Status"] else " " weather = rows["Weather"] if rows["Weather"] else " " light = rows["Light"] if rows["Light"] else " " accident_factor = rows["Accident Factor"] if rows["Accident Factor"] else " " collision_type = rows["Collision Type"] if rows["Collision Type"] else " " … -
django ModelChoiceField returns invalid form
I'm new to django and this is my first project. I'm having trouble with a form which I use to have the user pick an entry from a database table in order to redirect to another form to edit said entry. The ModelChoiceForm renders well when loading the view and the options from the database show up correctly but when I submit the form I get a UnboundLocalError saying the form is invalid and the form.errors prints <ul class="errorlist"> <li>group <ul class="errorlist"> <li>This field is required.</li> </ul> </li> <li>group_name <ul class="errorlist"> <li>This field is required.</li> </ul> </li> </ul> Here is the relevant part of my models.py: class Groups(models.Model): group = models.IntegerField(primary_key=True) group_name = models.CharField(max_length=80) def __str__(self): return self.group_name forms.py: class GroupForm(forms.ModelForm): class Meta: model = Groups fields = '__all__' labels = {'group':"ID", 'group_name':"name"} class SelectGroupForm(forms.Form): group_id = forms.ModelChoiceField(queryset=Groups.objects.all(), \ to_field_name='group', \ empty_label="Select group") views.py: if request.method=="POST": form = GroupForm(request.POST) if form.is_valid(): selected_group = form.cleaned_data['group'] redir_url = '../groupform/' + str(selected_group) + '/' return redirect(redir_url) else: print(form.errors) else: form = SelectGroupForm(request.POST) return render(request,'regular-form.html', {'form':form}) The error list suggests that the form requires all the fields from the model to be entered but I only want the one specified on the form. -
DJango fill existing formset from View
I understand that you can fill a form from a view with: initial_data = { 'box0': 'X', 'box1': 'O', 'box2': 'X' } form = myform(initial=initial_data) But, how do you do it for a formset? The below causes error "TypeError: formset_factory() got an unexpected keyword argument 'initial'" initial_data = [] for i in range(rowCount): xy = getRandomXY(3) initial_data.append({ 'box0': xy[0], 'box1': xy[1], 'box2': xy[2] }) formSet = formset_factory(myform, extra=rowCount, max_num=10, initial=initial_data) -
Django complicated grouping count
I have the models below: class Company(models.Model): .... cases = models.ManyToMany('Case') is_active = models.BooleanField(default=True) class Case(models.Model): .... is_approved = models.BooleanField(default=False) product = models.ForeignKey('Product') class Product(model.Model): .... I want to get all the products (that are linked with an approved case) grouped by companies' active status. So, the result should be like: [ {'product': 1, 'active_companies': 12, 'inactive_comapnies': 10}, {'product': 3, 'active_companies': 2, 'inactive_comapnies': 33}, {'product': 7, 'active_companies': 5, 'inactive_comapnies': 6} ] I have tried some queries starting with Company and others starting from Product, but I failed. -
Auth0 Authentication Flow (Mismatching State)
I hope whoever's reading this is having a good day! My question is as follows, I've got this specific authentication flow in my mind that is causing an exception when executing it. Given FrontEnd is hosted on domain FE (React Client), backEnd on domain BE (DJango Server) and Auth0 on A0. I need the user to land on FE, gets redirected to login form of A0 by the help of a BE endpoint, gets redirected to FE again which in turn calls BE with the state and auth code returned from A0, authenticates and saves token in the request session. def callback(request): ''' Extracts state and auth code from url, authenticates with auth0, extracts token and saves it within the request session for future calls. ''' token = oauth.auth0.authorize_access_token(request) request.session["user"] = token return {"Authenticated":True} def login(request): ''' Redirect to auth0 login screen with a callback url to frontend that extracts the given state and auth code sent by both BE and Auth0 ''' return oauth.auth0.authorize_redirect( request, "http://FrontEnd.com/authenticate") What happens when doing so is that the backend receives the state and raises a Mismatching state error request and response states do not match (state is null) Why do I want to … -
CSV upload to the correct column to Database in Django
I need help with upload of data from csv to my model in Django. I have two models: Product and Warehouse. And I get product data from Product table in Warehouse table. Originally I used product name in csv file and data were correctly uploaded to Warehouse table. But I had to add better key EAN to Product table and now when I use EAN in csv, product data are not uploaded from Product table, but they are added to both Product and Warehouse table from csv as new entry. Models.py: class Product(models.Model): ean = models.CharField("EAN", max_length=30) name = models.CharField("Product", max_length=150, null=True, blank=True) pyear = models.IntegerField("pYear", null=True, blank=True) drop = models.IntegerField("Drop", null=True, blank=True) def __str__(self): return f"{self.ean} - {self.name}" class Warehouse(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True) pieces = models.IntegerField("Quantity", null=True, blank=True) @classmethod def create_from_csv_line(cls, line): w = Warehouse() try: w.product = Product.objects.get(name=str(line["EAN"])) except Product.DoesNotExist: w.product, _ = Product.objects.get_or_create(name=str(line["EAN"])) w.pieces = int(line["Available"]) w.save() def __str__(self): return f"{self.product}, quantity: {self.pieces} Views.py: class WarehouseCSVImportView(LoginRequiredMixin, SuccessMessageMixin, FormView): template_name = "warehouse/warehouse_csv_import.html" form_class = WarehouseCSVForm def test_func(self): return self.request.user.is_superuser def post(self, request, *args, **kwargs): form: WarehouseCSVForm = WarehouseCSVForm(request.POST, request.FILES) if form.is_valid(): csv_file = form.cleaned_data["uploaded_file"] decoded_file = csv_file.read().decode('utf-8-sig') io_string = io.StringIO(decoded_file) reader = csv.DictReader(io_string, delimiter=",", skipinitialspace=True) … -
Is there a way of using Vue as SPA frontend and Django as backend to POST/PUT and Delete sqlite3 database content?
Aim: I am looking to develop a basic Vue/Ajax frontend and Django backend for a simple web API. I have one model with four fields of different types. I would like for my Django backend to respond to Ajax request methods (GET, POST, PUT and DELETE).Ideally, all my data being returned to client by web API being done using Django’s JsonReponse object, which can take a Python dictionary as input. I would like Vue to "reactively" modify pages and for the fetch API to make GET/POST/PUT/DELETE requests from client to server, so after the first page load, I do not want further page refreshes. Issues: I do not know how to make a POST request using a form that is in my Vue component (how it is meant to be linked), what would need to be fetched, how a JsonResponse object would help with adding (an object) to my default django database, similarly to how it is possible in django's admin page but in this case I am looking to change from my Vue template/component. -
Django annotate and aggregate not suport Timefild for sum
How can I make the total time sum of each user being that annotate and aggregate have no support for Timefild Models: class Pireps(models.Model): ... flight_time = models.TimeField(auto_now=False, auto_now_add=False, null=True) Views: def flight(request): ... flight_time = Pireps.objects.annotate(total_time =(Sum('flight_time')).order_by('total_time) id date create flight time 1 22/10/22 01:10:00 1 22/10/22 01:50:00 1 22/10/22 00:40:00 2 22/10/22 00:50:00 2 22/10/22 00:50:00 3 22/10/22 01:20:00 output of the result wanted like this id flight time 1 03:00:00 2 01:40:00 3 00:40:00 -
React Router not render
I tried using react router but it doesn't work. I already know that React Router Dom v6 has changed from Switch to Routes but when I run the program it just shows a blank screen. Does anyone know how to fix this? Here is my code: App.js ''' import React, {Component} from "react"; import { BrowserRouter as Router } from "react-router-dom"; import { render } from "react-dom"; import HomePage from "./HomePage"; export default class App extends Component{ render() { return ( <Router> <div> <HomePage /> </div> </Router> ); } } const appDiv = document.getElementById("app"); render(<App />,appDiv); ''' HomePage.js ''' import React,{Component} from 'react'; import RoomJoinPage from "./RoomJoinPage"; import CreateRoomPage from "./CreateRoomPage"; import { BrowserRouter as Router , Routes , Route , } from "react-router-dom" export default class HomePage extends Component{ render () { return ( <Router> <Routes> <Route path='/'> <p>This is Home Page</p> </Route> <Route path='/join' element={<RoomJoinPage />} /> <Route path='/create' element={<CreateRoomPage />} /> </Routes> </Router> ); } } ''' -
How to fix exception 404 in Django views?
I'm following this tutorial:https://www.w3schools.com/django/django_views.php After copying all the code to create the members and admin views I get this. The error page looks like this: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in myworld.urls, Django tried these URL patterns, in this order: members/ admin/ The empty path didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
Django queryset with matched all combinations
My Model: class Pattern(models.Model): name = CICharField("Pattern Name", max_length=200, unique=True) symptoms = models.ManyToManyField(Symptom, through='PatternSymptom', related_name='patterns') tongue_colour = models.ManyToManyField(Color, verbose_name="Tongue Body Colour", blank=True, related_name='patterns') tongue_shape = models.ManyToManyField(Shape, verbose_name="Tongue Body Shape", blank=True, related_name='patterns') tongue_quality = models.ManyToManyField(Quality, verbose_name="Tongue Body Features", blank=True, related_name='patterns') Color, Shape, Quality Model: class Color(models.Model): name = CICharField(max_length=300, unique=True) On the front-end, Users can select multiple Symptoms, Colour, Shape, Quality to find pattern and that will pass to Pattern model as symptoms_selected params. I have the following get_queryset on Pattern > views.py def get_queryset(self): params = self.request.query_params query_symptoms = self.request.GET.getlist('symptoms_selected') tongue_colour = self.request.GET.get('tongue_colour') tongue_shape = self.request.GET.get('tongue_shape') if query_symptoms: queryset = Pattern.objects.filter( symptoms__id__in=query_symptoms ).annotate( symptom_matches=Count('symptoms') ).annotate( pattern_weight=Sum('pattern_to_symptom__priority') ).annotate( # key_count=Count('pattern_to_symptom__priority__gt=1') key_count=Count('pattern_to_symptom__priority') ).order_by('-matches','-pattern_weight','most_common') else: queryset = Pattern.objects.all().filter(is_searchable=True) if tongue_colour is not None and tongue_colour.isnumeric(): queryset = queryset.filter(tongue_colour__id__in=tongue_colour).annotate(tongue_color_matches=Count('tongue_colour')); if tongue_shape is not None and tongue_shape.isnumeric(): queryset = queryset.filter(tongue_shape__id__exact=tongue_shape).annotate(tongue_shape_matches=Count('tongue_shape')); return queryset With this code I can get, queryset with matches symptoms AND tongue_colour AND tongue_shape. But, I want to show queryset with OR/all combinations with what matched. For eg: Pattern Data: Pattern A: Got Symptoms: A, B, C, D Tongue Colour: TC1,TC2,TC5 Tongue Shape: TS1,TS3,TS5 Pattern B: Got Symptoms: A, D, P, Q Tongue Colour: TC2,TC3,TC6 Tongue Shape: TS1,TS2,TS6 Pattern C: Got Symptoms: A, … -
Inherit a custom user models fields from parent class to a child class between two different applications
Hello kings and queens! I'm working on a project and got stuck on a (for me) complicated issue. I have one model (generalpage.models) where all the common info about the users is stored. In a different app (profilesettings), I have an app where all profile page related functions will be coded. I tried to inherit the model fields from the User class in generalpage.models into profilesettings.models by simply writing UserProfile(User). When I did this, a empty forms was created in the admin panel. So basically, the information that was already stored generalpage.models were not inherited in to the profilesettings.models, I created an entire new table in the database. my questions are: Is it possible to create an abstract class for a custom user model? Is there a proper way to handle classes and create a method in profilesettings.models that fills the UserProfile form with the data already stored in database created by the User class? Can someone please explain how the information can be passed from one application to another without creating a new empty form? Filestructure: Admin panel: generalpage.models: from random import choices from secrets import choice from unittest.util import _MAX_LENGTH from django.db import models from django.contrib.auth.models import AbstractBaseUser, …