Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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, … -
Django App creates incorrect URL on production server (shared Linux server at A2 Hosting)
My Django App works correctly on localhost using python manage.py runserver. When I run this App on a shared linux server at a web hosting site (A2 Hosting) only the base url at the domain root works: https://familyrecipes.de All other URLs get modified from say: https://familyrecipes.de/recipes to https://familyrecipes.de/familyrecipes.de/recipes What could possibly add the additional 'familyrecipes.de' to the url??? In views.py I call the individual views as: # for the index view return render( request, "FamilyRecipes/index.html", context=content) # or for the recipes view return render( request, "FamilyRecipes/recipes.html", context=content) etc. My url.py: import os from django.contrib import admin from django.urls import path, re_path from django.conf.urls.static import static from django.conf import settings from . import views app_name = 'FamilyRecipes' urlpatterns = [ re_path(r"^$", views.index, name="Home Page"), re_path(r"^recipes$", views.recipes, name="Recipes"), path('recipe/<int:id>/<str:flag>', views.singleRecipe, name="Print"), path('updateRecipe/<int:id>', views.updateRecipe, name="Update Recipe"), re_path(r"^toc$", views.toc, name="Recipe TOC"), path('dashboard', views.dashboard, name="Dashboard"), path('recipeScore/<int:user>/<int:recipe>/<int:score>', views.recipeScore, name="Recipe Score"), path('recipeNote/<int:user>/<int:recipe>/<str:noteStr>', views.recipeNote, name="Recipe Note"), path('deleteRecipeNote/<int:user>/<int:recipe>', views.deleteRecipeNote, name="Delete Note"), path("logout", views.logout, name="logout"), path('admin', admin.site.urls, name="Admin Home Page"), ] on-linux-shared-hosting urlpatterns += static(settings.STATIC_URL, document_root=os.path.join(settings.BASE_DIR, 'static')) My header.html code with the menu links: <nav id="navbar" class="main-nav navbar fixed-top navbar-expand-lg bg-light"> <div class="container"> <div class="row"> <a class="navbar-brand" href="{% url 'Home Page' %}"> <h1 class="col-12 text-secondary">Family Recipes</h1> </a> </div> <button class="navbar-toggler" … -
Add product to cart using python in Django
I want to make a simple function that collects the product ID and adds it to the user's shopping cart by clicking the "add to cart" button. I have the shopping cart table and product table created but am struggling to find the correct function to add the product to the cart. Anything helps I am very new to Python and Django and am looking for some help to get me on the right track. class Cart(models.Model): cart_id = models.Charfield(primary_key=True) total = models.DecimalField(max_digits=9,decimal_places=2) quantity = models.IntegerField() products = models.ManyToManyField(Product) class Product(models.Model): prod_id = models.CharField(max_length=15, null=True) name = models.CharField(max_length=200) price = models.DecimalField(max_digits=10,decimal_places=2) description = models.TextField(max_length=1000) def cart_add(request, prod_id): item = Product.objects.get(pk=prod_id) I know this isn't much to work with but anything helps, I am just looking for some help with creating the add to cart function -
extracting model information from primary key in serializers
I've got a Favorites model which keeps track of each users' favorite NFT. I want to display the actual NFT data instead of the NFT id. I'm not quite sure how to do so as only primary keys are being returned. model class Favorites(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) nft = models.ForeignKey(NFT, on_delete=models.CASCADE) serializer class FavoritesSerializer(serializers.ModelSerializer): class Meta: model = Favorites fields = "__all__" -
Filters & foreign key error : "The QuerySet value for an exact lookup must be limited to one result using slicing."
I am trying to filter products based on the logged in user. These products are however not linked to the user directly, but to the user's company. And the user's profile is linked to the user's company. To allocate a product the allocator would follow this process: Go to RFQ model - select a product Select 1 or many Supplier Profiles A user of the Supplier Profile would then be able to see what has been allocated I would normally use the pk_id of the company to return this, but on this occasion I need to find an alternative. I am struggling to get my head around all these interactions and how can the filter() can be applied to what I am trying to achieve. The current code I came up with returns the following error: The QuerySet value for an exact lookup must be limited to one result using slicing. This is probably due to the for loop in the template. model class Supplier_Profile(models.Model): name = models.CharField('Supplier Profile', max_length=120, blank=True) class Supplier_User_Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) supplier_company = models.ForeignKey(Supplier_Profile,blank=True, null=True, on_delete=models.CASCADE) class RFQ(models.Model): rfq_name = models.ForeignKey(Product,blank=True, null=True, on_delete=models.CASCADE) suppliers_consulted = models.ManyToManyField(Supplier_Profile) views def list_supplier_response(request): supplier_profile = Supplier_Profile.objects.all() enquiries … -
Template rendering error after website deploy
my website is about eccommerce activity. As I have deployed the site I am getting several errors. For example I can enter to log in or register user , I got errors like customuser does not exist. But I clearly have a models like below and it was working fine before deploying. class CustomUser(AbstractUser): is_customer = models.BooleanField(default=False) is_merchant = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) Another significant error I got in my customer home file template which says: relation "projectapp_product" does not exist The error occuring in store.html: {% extends 'customertemplates/main.html' %} {% load static %} {% block content %} <div class="row"> {% for product in products %} <div class="col-lg-4"> <img class="thumbnail" src="{{product.imageURL}}"> <div class="box-element product"> <h6><strong>{{product.product_name}}</strong></h6> <h4 style="display: inline-block;"><strong>${{product.discount_price}}</strong></h4> <hr> <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-cart"><i class='fa fa-shopping-cart yellow-color'></i> Add to Cart</button> {% if user.is_authenticated and user.is_customer %} <button style="width:110px" class="btn btn-outline-secondary add-btn add-wishlist" data-product="{{product.id}}" data-action="add"><i class="fa fa-heart"></i> Wishlist</button> {% endif %} <a class="btn btn-outline-success" href="{% url 'product_details' product.pk %}"><i class="fa fa-eye"></i> View</a> </div> </div> {% endfor %} </div> {% endblock content %} store.views.py: def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] products = Product.objects.all() context = {'products':products, … -
Bad Request 400 Django Heroku
I have made everything to upload my application on heroku I fade yp Collectstatic fine Allowed Host OK installed gunicorn ,whitenoise The project is uploaded on github Kind Regards -
TypeError at /email/ getaddrinfo() argument 1 must be string or None
i was trying to send message to candidate using Gmail as smtp, when i click send button im seeing the above error............................................................................................................................................................................................ views.py def email(request): if request.method == 'POST': # save message to DB to_db = Email( status = request.POST.get('status'), name = request.POST.get('name'), email = request.POST.get('email'), message = request.POST.get('message'), subject = request.POST.get('subject'), ) to_db.save() #Send email form = EmailForm(request.POST) company = "TT Software Solutions" if form.is_valid(): email = form.cleaned_data["email"] subject = form.cleaned_data["subject"] message = form.cleaned_data["message"] mail = EmailMessage(subject, message, company, [email]) mail.send() messages.success(request, 'Email sent successfully') return redirect('candidates') else: form = EmailForm() return render(request, {'form':form}) models.py class Email(models.Model): # Hidden name = models.CharField(max_length=50) email = models.EmailField(max_length=50) status = models.CharField(max_length=50) # Non Hidden subject = models.CharField(max_length=50) message = models.TextField() def __str__(self): return self.name template <form class="was-validated" action="{% url 'email' %}" method="post"> {% csrf_token %} <div class="modal-body"> <strong>To: <span class="text-primary">{{ candidate.first_name }} {{ candidate.last_name }}</span></strong> <hr> <!-- Hiden Inputs --> <input type="hidden" name="name" value="{{ candidate.first_name }} {{ candidate.last_name }}"> <input type="hidden" name="email" value="{{ candidate.email }}"> <input type="hidden" name="status" value="{{ candidate.Situation }}"> <!-- Non Hiden Input --> <input type="text" name="subject" class="form-control mb-2" placeholder="Subject" required> <textarea name="message" class="form-control" rows="8" placeholder="Message to candidate..." required></textarea> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary w-100"> <i class="fas fa-paper-plane"></i>&nbsp;&nbsp; … -
In pycharm previous django project`s server still runs after opening and running another project
I found the answer here PyCharm Django previous project`s server still runs after opening and running another project which works for me but I want to find a permanent solution. Can anyone suggest a solution? -
Django making an efficient way to loop transactions and categories to reduce datebase calls
response.json potentially contains thousands and thousands of items. I have would like to limit the number of times the database is queried. I'm aware a QuerySet can be constructed, filtered, sliced, and generally passed around without hitting the database. No database activity occurs until you do something to evaluate the queryset. In the code below, I rarely have to create a new category if one does not already exist, but the code "appears' to query the database on every item in the response.json loop due to categories.objects.getorcreate line: categories = Category.objects.all() __new_transactions = [] for item in response.json: category = categories.objects.getorcreate(code=item['category_code']) transaction = Transaction( category=category ) __new_transactions.append(transaction) # Save the transactions to the database in bulk. Transaction.objects.bulk_create(__new_transactions) Can I make the above more efficient? My initial idea was to check if the transaction category is in the categories list. However, that is a large list (5000 items) on this line item['category'] in categories categories = Category.objects.all() __new_transactions = [] for item in response.json: # check if the transaction category is in the categories list if item['category'] in categories: category=categories.get(code=item['category']) else: Category.objects.create(code=item['category'], name=item['category']) category = categories.objects.getorcreate(code=item['category_code']) transaction = Transaction( category=category ) __new_transactions.append(transaction) # Save the transactions to the database in bulk. … -
Best method to authenticate users in Django and React
I am building an application in Django for the backend and React for the frontend. Both are hosted in different domains so my way to authenticate users was to use a token which will then be saved on localStorage. However, upon reading more about it, storing the token this way is not so secure. Many recommend cookies but from what I understand they need to be on the same domain for this to work. What is the best thing to do in this case and the most secure? -
Django comment(s) on users in database
I'm currently building a Django website where staff has control over users, and, within those powers, I'd like to add one where the staff members can add private comments on users so that they can be read by whoever has the power to do so. So I started building the user models.py here what I did: class user(models.Model): name = models.CharField(max_length=30) comments = models.TextField() date = models.DateField(default=datetime.now()) def __str__(self): return self.name My question: how can I add a comment field every time a staff member wants to? Like, with the above code, I can only have one comment per user. Everything is appreciated. Thanks! -
Link form in Vue component to Django model
I have a template/html form inside one of my Vue components. How do I link this to my django model? I know how to do this in the case of linking a form made using django's built in forms, but I am not after that, I wish to link my vue form to my django backend. -
Django uvicorn root-path analogue
I work on some project, which uses microservice architecture. I have one Django monolith and several FastAPI microservices, which comunicate with main monolith app (splitting main app to microservices in progress, but now I still need to all this architecture works). I use traefik to route my services, so main app has /core prefix. I have a problem with in-django routing: my custom urls works okey, but built-in django admin urls work not good, because they try to redirect me not on /core/admin/some-url, but on /admin/some-url - they know nothing about my traefik prefix. In my FastAPI apps there are no problems with prefixes. I use uvicorn and they use --root-path /my-prefix-for-this-app setting in uvicorn run command, and I have no redirects inside these apps (probably, in future there will be a problem with redirection, but now I have no). So, my question is the following: "Do Django has any settings or logic to change base prefix to all redirections or maybe gunicorn has (I did not find any) setting to make it change base root url on django start via wsgi or maybe there is some other method to make my django app redirect urls right way? ". If … -
Forbidden: / 403 error while sending image from react to django using axios
I have a reactjs project that makes requests using API to django-rest-framework. I am trying to create an image field in reactJS that sends image to django server on submitting. Maybe the error is with csrf token or maybe not. I am a newbie. Please help. If possible please help me with the correct code. Thankyou veru much Image.js import React, { useState} from 'react'; axios.defaults.xsrfHeaderName = 'X-CSRFTOKEN'; axios.defaults.xsrfCookieName = 'csrftoken'; export default function Image() { const[images,setImages]=useState(null); function handleImages(e){ setImages(e.target.files[0]) } function handleSubmit(evemt){ const formData= new FormData(); formData.append('images',images) axios.post('http://127.0.0.1:8000/',formData,{ headers:{ "Content-Type": "multipart/form-data" }} ).then((res)=>{ console.log(res) } ) } return ( <div> <input type="file" name="images" accept="image/*" onChange={handleImages}/> <button onClick={handleSubmit}>Upload</button> </div> ) } views.py from rest_framework.parsers import FileUploadParser from rest_framework import viewsets from .serializers import RentDetailsSerializer from firstapp.models import RentDetails from rest_framework.parsers import MultiPartParser, FormParser class RentDetailsViewSet(viewsets.ModelViewSet): serializer_class=RentDetailsSerializer queryset=RentDetails.objects.all(); parser_classes = [MultiPartParser, FormParser] serializers.py from rest_framework import serializers from firstapp.models import RentDetails class RentDetailsSerializer(serializers.ModelSerializer): images=serializers.ImageField(required=False) class Meta: model = RentDetails fields = ['floor_no','distance','location','area','no_of_rooms','price','property_type','images'] settings.py REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser' ] } # REST_FRAMEWORK = { # 'DEFAULT_AUTHENTICATION_CLASSES': ( # 'rest_framework.authentication.TokenAuthentication', # ) # } # CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with", ] … -
Django table - Displaying floats
I am currently configuring a better readable FlaotColumn class NumberColumn(tables.Column): def render(self, value): if isinstance(value, float) and abs(value) != 0: dec = decimal.Decimal(value) rounded_val = round(dec, 6) return rounded_val else: return value So this is the current state. As you can see, when the value comes in I am checking if the value is not 0 and has the correct dtype. Now lets say one value is: -0.0977443609022557169385692077412386424839496612548828125 and the other one is: 0.00000000012312312312312321232356787686 How can I gurantee that both values are displayed in a verbose way without saying that values with f.ex. 6 decimal places are returned? Thanks for any suggestions here! -
Django's Admin list_display won't show correct Boolean Icon when using pre_save signal or in a model's custom save() unless saving the model twice
I have a Product model, and in the models.py I use a pre_save signal to update the product's all_variations_active field. For some unknown reasons, this all_variations_active field won't be updated with the correct Boolean value in list_display for admin unless the product gets saved twice. Below is the example code that I have issues with: pre_save signal part in models.py: @receiver(models.signals.pre_save, sender=Product, dispatch_uid='product_pre_save_unique_id') def product_pre_save(sender, instance, **kwargs): res = Variation.objects.filter(product=instance) active_list = [] for i in res: active_list.append(i.is_active) if sum(active_list) < 1 or False in active_list: instance.all_variations_active = False else: instance.all_variations_active = True In admin.py: class VariationInline(admin.TabularInline): model = Variation extra = 3 class ProductAdmin(admin.ModelAdmin): list_display = ( 'thumbnail', 'product_name', 'product_description', 'on_sale', 'price', 'stock', 'is_available', 'category', 'created_date', 'sku', 'all_variations_active') inlines = [VariationInline, ] Additional info: The model Variation(models.Model) has product model as a Foreignkey. Which looks like this: product = models.ForeignKey(Product, on_delete=models.CASCADE) So the gist is that when I go to the inline tabular tab for the variations of a product and change the select boxes - when saving the tabular tab does get saved correctly but in the admin's list_display it won't show the correct boolean status of the variations - because according to my code above if one … -
Django - Wagtail - Heroku: How to troubleshoot intermittent, seemingly random, HTTP 404s?
I'm serving Wagtail pages in a very well tested web app. No errors show up in development. When in Production (using Heroku and a hobby-tier Postgres db), those pages occasionally return an HTTP 404. If I refresh the browser a couple times, it goes back to serving the Page perfectly again. Some details: This happens with multiple pages; I get emails with the 404 error when this happens, so Django's BrokenLinkEmailsMiddleware is kicking in; Heroku web Dyno looks healthy based on its metrics; Heroku Postgres has no logs for the Hobby tier, so I don't know what's going on on the db side; Server is running behind a Cloudflare proxy server, but I can see the request hitting the origin and returning a 404. I'm obviously not expecting a solution here since the above info is insufficent for that. But I'm looking for troubleshooting pointers, for example: If the db has become under-dimensioned (too little RAM, too many simultaneous connections, etc.) - could that result in a Wagtail db query wrongly returning PageNotFound? Or would that return a 500 Server Error? How can I test DB error-handling locally with Django? How can I add a full Traceback for the Django …