Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Martor image upload only working on Mobile
The Image Upload button works fine on my cell phone, but when trying to use chrome desktop, the upload button is dead and does nothing. The part of the toolbar that is responsible for it is this: {% if 'image-upload' in toolbar_buttons %} <span class="btn btn-light markdown-selector markdown-image-upload" title="{% trans 'Upload an Image' %}"> <i class="fas fa-image"></i> <input name="markdown-image-upload" class="button" type="file" accept="image/*" title="{% trans 'Upload an Image' %}"> </span> {% endif %} Is there something about the mobile browser that makes this usable but not on the desktop? -
TemplateDoesNotExist-Already added the templates dir in settings and created inside project
I have created a project "ProTwo" and app as "appTwo" added the templates dir in the project settings and created templates folder in the project.When I render the views index.html its showing error app/views.py ''' from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): help_dict={'help_me':"HELP PAGE"} return render(request,'appTwo/help.html',context=help_dict) ''' app/urls.py ''' from django.urls import path from appTwo import views urlpatterns = [ path('',views.index,name="index"), ] ''' Project/settings.py """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIR=os.path.join(BASE_DIR,"templates") # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-0m6xzby50vk61zdun2g%oq^nkr2v0=_7il#z#qnx)=7=6q_e^p' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'appTwo', ] 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 = 'ProTwo.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR,], '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 = 'ProTwo.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', … -
Django: Saved data is not outputting to html .(I am real beginner.)
Thank you for reading. Even though data is stored in the Product, it is not output to the store.html screen. What might be the problem? I checked Product is saved with admin page. I'm so new I have no idea what I'm doing wrong. Thank you very much. views.py def store(request): global products, context data = cartData(request) cartItems = data['cartItems'] products = Product.objects.all() context = {'products': products, 'cartItems': cartItems} return render(request, 'maps/store.html', context) models.py class Product(models.Model): poiid = models.DecimalField(max_digits=7, decimal_places=2) name = models.CharField(max_length=200, null=True) price = models.CharField(max_length=7, null=True) address = models.CharField(max_length=7, null=True) digital = models.BooleanField(default=False, null=True, blank=True) def save(self, *args, **kwargs): super().save(*args, **kwargs) # Call the "real" save() method. def __str__(self): return self.name # url = '' # return url store.html {% extends 'maps/main.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-md"> <div class="card card-body"> <table class="table table-sm"> <tr> <th>poiid</th> <th>name</th> <th>category</th> <th>address</th> <th>save</th> </tr> {% for product in products %} <tr> <td>{{product.poiid}}</td> <td>{{product.name}}</td> <td>{{product.price}}</td> <td>{{product.address}}</td> <td><button data-product={{product.id}} data-action='add' class="btn btn-outline-secondary add-btn update-cart">save</button></td> </tr> {% endfor %} </table> </div> </div> </div> {% endblock content %} -
Why is my data not rendering from this.state?
I've been trying to get an array to come over into react and then display it on the browser. The data is coming over, but for some reason I cannot display it. ReactJs: import React, { Component } from "react"; export default class RegisterPage extends Component { constructor(props){ super(props); this.state = { }; this.getPlayers(); } getPlayers() { fetch('/draft/get-players') .then((response) => response.json()) .then((data) => { this.setState({ players: data, }); }); } render(){ return (<h1>{this.state.players[0].name}</h1>) } } I initially was trying to .map this into multiple lines of HTML, but through troubleshooting learned that I'm not even able to get a single element out of the array. JSON from /draft/get-players: [ { "id": 1, "name": "Aidan Hutchinson", "position": "EDGE", "EstimatedRound": 1, "college": "Michigan", "age": "SR", "TakenRound": null, "TakenPick": null }, { "id": 2, "name": "Aidan Hutchinson", "position": "EDGE", "EstimatedRound": 1, "college": "Michigan", "age": "SR", "TakenRound": null, "TakenPick": null }, { "id": 3, "name": "Kayvon Thidobeaux", "position": "EDGE", "EstimatedRound": 1, "college": "Oregon", "age": "SOPH", "TakenRound": null, "TakenPick": null }, { "id": 4, "name": "Kyle Hamilton", "position": "S", "EstimatedRound": 1, "college": "Notre Dame", "age": "JR", "TakenRound": null, "TakenPick": null }, { "id": 5, "name": "Ikem Ekwonu", "position": "OL", "EstimatedRound": 1, "college": "NC State", "age": … -
Does This Hierarchy work with ListView? Getting NoReverseMatch Error
I'm running into an issue debugging the following error: Reverse for 'tasks' with arguments '('',)' not found. 1 pattern(s) tried: ['customer/(?P[-a-zA-Z0-9_]+)/tasks/$'] However, I'm pretty certain that my url parameters are correct and without typos. The url and page worked fine with a function based view, the problem started when I changed to a ListView. Template: <a href="{% url 'customerportal:tasks' object.slug %}" class="nav-link"> I also tried: <a href="{% url 'customerportal:tasks' slug=object.slug %}" class="nav-link"> <a href="{% url 'customerportal:tasks' slug=object.slug|slugify %}" class="nav-link"> My ListView: class TaskListView(ListView): model = Task template_name = 'customerportal/tasks.html' def get_queryset(self): self.project = get_object_or_404(Project, slug=self.kwargs['slug']) return Task.objects.filter(project=self.project.id) URLs: path('<slug:slug>/', ProjectDetailView.as_view(), name='customer-portal'), path('<slug:slug>/tasks/', TaskListView.as_view(), name='tasks'), I've confirmed that I'm passing the right slug by printing it. The slug parameter is from a parent directory as seen in the urls.py above. I'm guessing ListView doesn't work this way? If not is there a way I could maintain this structure, or do I have to switch back to a function based view in order to get this to work? Thanks. -
RelatedManager object is not iterable
Whenever I run my code, I get a "RelatedManager" object is not iterable error. Here is my models.py: from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.urls import reverse class Post(models.Model): contents = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) replies = list() def __str__(self): return f'{self.author} - {self.pk} - {self.date_posted}' def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Reply(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='replies') contents = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'{self.author} - {self.date_posted}' def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Meta: ordering = ['-date_posted'] Here is my views.py: from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth.models import User from .forms import ReplyForm class PostListView(ListView): model = Post template_name = 'app/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 15 def PostDetailView(request, **kwargs): template_name = 'app/post_detail.html' post = get_object_or_404(Post, pk=kwargs['pk']) replies = post.replies new_reply = None # Reply added if request.method == 'POST': reply_form = ReplyForm(data=request.POST) if reply_form.is_valid(): # Create reply object but don't save to db yet new_reply = reply_form.save(commit=False) # Assign the current post the the reply new_reply.post = post … -
Django: How do I put data from a csv file into a datatype I created in "models.py"?
I'm learning django for the first time, I'm stuck on even the simplest screen output. I even created a data format to display in the listview in models.py, how do I add data to this now? (I've tried to save the data in admin page, but there is no output.) I want to output the data in csv, so does anyone know how to put the data in the name directly in the python file and pop it up on the screen? class Product(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name url = '' return url thank you so much! -
How To Get Google User Profile Info Using Access Token From OAuth?
I am using ReactJS on the frontend: I successfully retrieved the access token from Google's Oauth service, but it doesn't give me any profile information for the 'current user'. I tried using the /userInfo endpoint, ?access_token={my_access_token} query str, and some other solutions but I keep getting weird errors. Currently I have: const { access_token, refresh_token } = res.data; // now I have valid access_token let userInfo = await axios.get("https://www.googleapis.com/oauth2/v3/userinfo", { headers: { Authorization: `Bearer ${access_token}` } }); // ERROR WHEN MAKING THIS CALL. My specific 401 error is as follows: error message -
heroku host successfully but application error
I successfully deploy the to Heroku. but when I run Heroku open it throws Application error occurred "An error occurred in application and your page could not be served. if you are the application owner, check your logs for details my logs is here 2022-01-23T02:24:56.663017+00:00 app[api]: Initial release by user victchubxy@gmail.com 2022-01-23T02:24:56.663017+00:00 app[api]: Release v1 created by user victchubxy@gmail.com 2022-01-23T02:24:56.822006+00:00 app[api]: Release v2 created by user victchubxy@gmail.com 2022-01-23T02:24:56.822006+00:00 app[api]: Enable Logplex by user victchubxy@gmail.com 2022-01-24T02:06:26.000000+00:00 app[api]: Build started by user victchubxy@gmail.com 2022-01-24T02:06:27.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/af9da633-ce1d-4e6b-bd49-51c06b87f315/activity/builds/b6179e58-ffa5-4189-964c-63cbc70d8d08 2022-01-24T02:26:50.000000+00:00 app[api]: Build started by user victchubxy@gmail.com 2022-01-24T02:26:51.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/af9da633-ce1d-4e6b-bd49-51c06b87f315/activity/builds/8c889fa0-73c2-4257-b19d-ca893a595436 2022-01-24T03:22:22.000000+00:00 app[api]: Build started by user victchubxy@gmail.com 2022-01-24T03:22:23.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/af9da633-ce1d-4e6b-bd49-51c06b87f315/activity/builds/634953f5-1324-4dd4-afbc-35bc9296c1b8 2022-01-24T03:23:35.000000+00:00 app[api]: Build started by user victchubxy@gmail.com 2022-01-24T03:23:36.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/af9da633-ce1d-4e6b-bd49-51c06b87f315/activity/builds/9da67c75-fb7c-4178-98c9-8e05551efb06 2022-01-24T03:38:33.000000+00:00 app[api]: Build started by user victchubxy@gmail.com 2022-01-24T03:38:34.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/af9da633-ce1d-4e6b-bd49-51c06b87f315/activity/builds/b84dff51-b132-417a-aca9-cba9f79e549c 2022-01-31T02:21:07.844606+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET path="/" host=hidden-hollows-48192.herokuapp.com request_id=ef621c27-e056-43fb-af5d-feecc2a18e7f fwd="197.210.79.99" dyno= connect= service= status=502 bytes= protocol=https 2022-01-31T02:39:40.874045+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET path="/" host=hidden-hollows-48192.herokuapp.com request_id=4e6586b7-4de1-491a-a4fb-dfcfdb3820cd fwd="197.210.79.240" dyno= connect= service= status=502 bytes= protocol=http 2022-01-31T02:39:42.062534+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET … -
Django Admin Model - Foreign key is showing email, not id
I have two models - An Article Model. A Reporter Model. Just like the Django Documentation from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): return str(self.email) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): return str(self.headline) I also have registered this in my admin.py file @admin.register(Reporter) class ReporterAdmin(admin.ModelAdmin): pass @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): pass When I go to add an article in admin, the field for reporter shows me the reporters email, I want it to show me the reporters id (the id field that is created by default). -
Django custom ordering causes error for related model?
I have two models as follows: class A(models.Model): # more fields here finished_at = models.DateTimeField(db_index=True, null=True, blank=True) class Meta: ordering = [ models.F("finished_at").desc(nulls_first=True), "other_field", ] class B(models.Model): related = models.ForeignKey(A, on_delete=models.CASCADE) class Meta: # custom ordering here too And then when I try to delete A instances through the admin site, or when accessing B instances either through admin or command line it gives error: Cannot resolve keyword into field finished_at. But if I remove the ordering on model A it works fine. -
Query in Django template
I am trying to query inside a django template, but i am just not sure how to correctly phrase the query, i have two models 1-category 2-items and i am trying to get all the items of a specific category from it's ID {% for item in Category.objects.get(id=${this.id}).items.all%}{{item.name}}{%endfor%} here is the complete template: <div class="inventory-content"> <div class='category'> <div>Categories</div> <div class='category-checkbox'> {%for category in items%} <input type="checkbox" id="{{category.id}}" name="{{category.name}}" value="{{category.id}}"> <label for="{{category.name}}"> {{category.name}}</label><br> {%endfor%} </div> </div> <div class='items'></div> </div> <script> $('.category-checkbox input[type="checkbox"]').on('click', function() { if ($(this).is(':checked')) { // Add the element to the div with an id identifier $('.items').append(`<div id="item_${this.id}">{% for item in Category.objects.get(id=${this.id}).items.all%}{{item.name}}{%endfor%}</div>`); } else { // Remove the element from the div targeted by the id identifier $(`#item_${this.id}`).remove(); } }); </script> models.py: class Category(models.Model): name = models.CharField(max_length=150) vessel = models.ForeignKey(Vessel,on_delete=models.CASCADE,related_name='category') def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length=255) part_number = models.IntegerField(blank=True) ROB = models.IntegerField(default=0) category=models.ForeignKey(Category,related_name='items',on_delete=models.CASCADE) def __str__(self): return self.name also i have been told it's bad practice to write query inside the template, so if you can guide me what better way could i have achieved this ?which is querying for all items in a specific category when checked -
Do I need to create a model for a table I'm inserting through sqlalchemy in django?
I have a Command class that runs an api call to a coin market cap api and writes it into the database that I have rigged up to my django project called cryptographicdatascience. The table that the data is written to is called apis_cmc and is not defined in my models.py. My question is if I am writing straight to a table using sqlalchemy do I need to go in and create a model for the same table in my models.py file? It seems to me that the answer is no but I'm sure there is something I'm overlooking. Thanks, Justin -
The command 'pip freeze' on the linux bash shell is not showing any of the installed packages in the output
I'm using the Linux Bash shell on Windows to activate django virtual environment and I want to see if the packages I'm using in this certain project are showing up using pip freeze (just like in the tutorial I am watching, since I'm very new to Linux in general) but once I put in the command, it doesn't give me any errors it's just that it won't output any packages at all. This might be a very simple question to some of you guys but I was doing some research and I can't find anyone in the exact same circumstances I'm in, so I decided to come to SO for help. As you can see in the image, it only shows the + pip freeze. Please, any help would be appreciated. -
Single object from queryset
I need help with a little issue I am having with my project. I have a model where I have a foreign key with many entries and I would like to take just one item of these entries. In fact, my problem is something like that: I need to obtain the single mission id, in order to have other functions. The code is working fine, my problem is that I don't know the righe order to obtain the mission item from this queryset: models.py from django.db import models from flight.models import LogEntry from user.models import Instructor, Student # Create your models here. TRAINING_COURSE_CHOICES = ( ('PPL', 'PPL'), ('CPL', 'CPL'), ('IR', 'IR'), ('ATPL', 'ATPL'), ) class TrainingCourse(models.Model): name = models.CharField(max_length=20, choices=TRAINING_COURSE_CHOICES) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class StudentTrainingCourse(models.Model): training_course = models.ForeignKey( TrainingCourse, on_delete=models.PROTECT) student = models.ForeignKey(Student, on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.student.first_name + ' ' + self.student.last_name + ' ' + self.training_course.name class Mission(models.Model): name = models.CharField(max_length=200) training_course = models.ForeignKey( TrainingCourse, on_delete=models.CASCADE) note = models.TextField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.training_course.name + ' ' + self.name class StudentMission(models.Model): mission = models.ForeignKey(Mission, on_delete=models.PROTECT) student_training_course = models.ForeignKey( StudentTrainingCourse, … -
Django queryset - Add HAVING constraint after annotate(F())
I had a seemingly normal situation with adding HAVING to the query. I read here and here, but it did not help me I need add HAVING to my query MODELS : class Package(models.Model): status = models.IntegerField() class Product(models.Model): title = models.CharField(max_length=10) packages = models.ManyToManyField(Package) Products: |id|title| | - | - | | 1 | A | | 2 | B | | 3 | C | | 4 | D | Packages: |id|status| | - | - | | 1 | 1 | | 2 | 2 | | 3 | 1 | | 4 | 2 | Product_Packages: |product_id|package_id| | - | - | | 1 | 1 | | 2 | 1 | | 2 | 2 | | 3 | 2 | | 2 | 3 | | 4 | 3 | | 4 | 4 | visual pack_1 (A, B) status OK pack_2 (B, C) status not ok pack_3 (B, D) status OK pack_4 (D) status not ok My task is to select those products that have the latest package in status = 1 Expected result is : A, B my query is like this SELECT prod.title, max(tp.id) FROM "product" as prod INNER JOIN "product_packages" … -
'Uploads' object is not iterable in Django
I am trying to have each model object have it's own page with all the other model objects attached to it, using the modal id, I tried using the {{ img.queryset.all.id }} html tag to display the photo, but that didn't work. I know the problem is in either the views.py or single_page.html, and maybe the models.py but I believe that is unlikely the problem. When I click onto the photo it bring it to a page with the photo icon, it doesn't display it because the photo is unknown. While every time I use {% for x in img %} it says 'Uploads' object is not integrable. If anyone could help that would be great. modals.py class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, null = False, blank = True) first_name = models.CharField(max_length = 50, null = True, blank = True) last_name = models.CharField(max_length = 50, null = True, blank = True) phone = models.CharField(max_length = 50, null = True, blank = True) email = models.EmailField(max_length = 50, null = True, blank = True) bio = models.TextField(max_length = 300, null = True, blank = True) profile_picture = models.ImageField(default = 'default.png', upload_to = "img/%y", null = True, blank = True) … -
SQL Query Failure using Django, Djongo, and mongoDB During user registration with allauth
I am getting a failed sql exception when users attempt to register with a site I wrote in Django, using djongo to interface with mongoDB. The above exception ( Keyword: None Sub SQL: None FAILED SQL: ('SELECT (1) AS "a" FROM "account_emailaddress" WHERE ("account_emailaddress"."user_id" = %(0)s AND "account_emailaddress"."verified") LIMIT 1',) Params: ((7,),) Version: 1.3.6) was the direct cause of the following exception: 'return self.cursor.execute(sql, params)' -
relation "itouch_photo" does not exist
i have an app hosted in heroku while i did not set debug = false, when i visit the website it's throws me an error like this: relation "itouch_photo" does not exist LINE 1: ...ch_photo"."price", "itouch_photo"."location" FROM "itouch_ph... and also it highlight my template: {% for photo in photos reversed %} I did not use command prompt i developed an app through heroku dashboard. how can i slove that: the models: class Photo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.CharField(max_length=30,null=True, blank=False) image = CloudinaryField('image') description = models.TextField(null=True) date_added = models.DateTimeField(auto_now_add=True) phone = models.CharField(max_length=12, null=False, blank=False) price = models.CharField(max_length=30,blank=False) location = models.CharField(max_length=20, blank=False) def __str__(self): return str(self.category) the views: def dashboard(request): photos = Photo.objects.all() context = {'photos': photos} return render(request, 'dashboard.html', {'photos': photos} ) def home(request): photos = Photo.objects.all() context = {'photos': photos} return render(request, 'home.html', {'photos': photos} ) i think the problem is coming from this model up here -
How to handle redirect for login_required in htmx partial view?
I have two views. class IndexView(TemplateView): template_name = 'index.html' @require_POST @login_required def partial_view(request): return render(request, 'partials/stuff.html') I want the index page to be "public" but if user takes action (which triggers partial view), they should be redirected to LOGIN_URL, if not logged in. The problem is that my partial view will return the entire LOGIN_URL page. So there's a page within a page now. Is it possible to redirect the "parent" page when using partial views? -
How to upload an image from vue js to django rest framework?
I am using django-rest-framework as my backend and I want to upload an Image from the frontend(vuejs2) note: the backend works perfectly and I can upload the photo using django admin -
Django rest framework: how to make a view to delete multiple objects?
I am building a simple Photos-Albums app with Django Rest Framework (DRF). I would like to be able to delete multiple albums at once by supplying an array of ids. I am using viewsets.ModelViewSet for the basic views. class AlbumViewSet(viewsets.ModelViewSet): queryset = Album.objects.all() serializer_class = AlbumSerializer I have managed to create a view to show the albums before the delete operation by adding this function to my views.py file. @api_view(['GET', 'DELETE']) def delete_albums(request): """ GET: list all albums DELETE: delete multiple albums """ if request.method == 'GET': albums = Album.objects.all() serializer = AlbumSerializer(albums, many=True) return Response(serializer.data) elif request.method == 'DELETE': ids = request.data albums = Album.objects.filter(id__in=ids) for album in albums: album.delete() serializer = AlbumSerializer(albums, many=True) return Response(serializer.data) If I run curl -X delete -H "Content-Type: application/json" http://localhost:8000/albums/delete -d '{"data":[1,2,3]}' then it will delete albums with ids 1,2,3. This is OK, except that: It's not class-based, and I'd prefer to have everything class-based if possible I would prefer to have a form in the view that lets me input an array e.g. [1,2,3], hit a delete button, and then see the results of the query in the browser, much like when one posts a new object through the interface. Can anyone … -
Is There A Way To Improve Performance Of Data Dictionary Model To Dict Appraoch?
I am currently getting a bunch of records for formsets in my Django application with the method below... line_items = BudgetLineItem.objects.filter(budget_pk=dropdown) line_item_listofdicts = [] for line_item in line_items: line_item_dict = model_to_dict(line_item) del line_item_dict['id'] del line_item_dict['budget'] del line_item_dict['archive_budget'] del line_item_dict['new_budget'] del line_item_dict['update_budget'] line_item_listofdicts.append(line_item_dict) UpdateBudgetLineItemFormSet = inlineformset_factory(UpdateBudget, UpdateBudgetLineItem, form=UpdateBudgetLineItemForm, extra=len(line_item_listofdicts), can_delete=True, can_order=True) The good news is that it works and does what I want it to. However it's super slow. It takes about 13 seconds to render the data back to my app. Not optimal. I've spent the morning trying to do various prefetches and select_relateds but nothing has worked to improve the time it takes to render these fields back to the screen. The fields in question are largely DecimalFields and I've read that they can be a bit slower. I'm trying to use this data as "input" to my formsets in a CreateView. Again it works...but it's slow. Any ideas on how to make this approach more performant? Thanks in advance for any thoughts. -
Choose a specific manager for a related field for a model
I am in a situation where I need to use a custom manager for a related field which is different from the base_manager for the related fields. Let's say that I have a model Item which is in one to many relation with another model Purchase. Now, Item has 2 managers: objects = ItemManager() #which by default excludes the out_of_stock=True items complete = CompleteItemManager() #which gives all the items. For all the other models related to Item, ItemManager is the default one. But in Purchase, I would want to use the CompleteItemManager for the related Item. So let's say there was once a purchase for an item which is now has out_of_stock=True and we just have the id of that purchase say old_purchase_id, now if try to run the below query: purchase = Purchase.objects.filter(id=old_purchase_id) # gives error It would give an error like "Item matching query does not exist" as the manager being used for the related items is ItemManager which excludes such out of stock items. What can be done in that case? Ideally I would want something to override the manager to be used for a given related field per model, so that even if all other models … -
I'm trying to set-up Wagtail on Cloud Run
I'm trying to set-up wagtail and using the Wagtail on Cloud Run guide on https://codelabs.developers.google.com/codelabs/cloud-run-wagtail#5. I'm on step 6 and here's the errors I'm facing after executing the migrate.yaml command ''' tep #1 - "migrate": Traceback (most recent call last): Step #1 - "migrate": File "/workspace/manage.py", line 10, in Step #1 - "migrate": execute_from_command_line(sys.argv) Step #1 - "migrate": File "/layers/google.python.pip/pip/lib/python3.9/site-packages/django/core/management/init.py", line 419, in execute_from_command_line Step #1 - "migrate": utility.execute() Step #1 - "migrate": File "/layers/google.python.pip/pip/lib/python3.9/site-packages/django/core/management/init.py", line 413, in execute Step #1 - "migrate": self.fetch_co '''