Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to annotate type of Manager().from_queryset()?
In Django I have custom QuerySet and Manager: from django.db import models class CustomQuerySet(models.QuerySet): def live(self): return self.filter(is_draft=False) class CustomManager(models.Manager): def publish(self, instance: "MyModel"): instance.is_draft = False instance.save() In my model I want to use both, so I use from_queryset method: class MyModel(models.Model): objects: CustomManager = CustomManager().from_queryset(CustomQuerySet)() is_draft = models.BooleanField(blank=True, default=True) Since I annotated objects as CustomManager, Pylance (via vscode) logically yells at me that MyModel.objects.live() is wrong, due to Cannot access attribute "live" for class "CustomManager" Attribute "live" is unknown. Removing type annotation leads to similiar complaint: Cannot access attribute "live" for class "BaseManager[MyModel]" Attribute "live" is unknown. How to annotate objects in MyModel so Pylance will be aware that objects also has CustomQuerySet methods available, not only CustomManager methods? -
How to make group by in djano ORM
I've an Order model as below: class Order(models.Model): bill = models.ForeignKey(Bill, on_delete=models.PROTECT, null=True, blank=True) address_from = models.ForeignKey(Address, on_delete=models.PROTECT) address_to = models.ForeignKey(Address, on_delete=models.PROTECT) How can I group a queryset from it and iterate in each group like the following: bill = models.Bill.objects.create() groups = Order.objects.all().group_by('address_from', 'address_to') for group in groups: group.update(bill = bill) The goal is to set a bill for each group of the orders that have the same address from and address to. -
How to read headers from axios post in django?
I am sending an axios post to my django backend app: async function sendBookingRequest() { // console.log(date,bookedHours,cancha,cellphone) try { axios.post("https://danilo2588.pythonanywhere.com/book", { headers: {'Authorization':"1234567890123456789012345678901234567890"}, params:{ 'requested_date':date, 'hours':bookedHours, 'business':cancha, 'phone':cellphone, } }) .then( function(response){ setConfirmation(response.data) setStepper(7) }) .finally( setIsLoading(false) ) } catch(error){ console.log(error) }; } In my views I have: def booking(request): auth_key = request.headers.get('Authorization') if auth_key: generic_user = Token.objects.get(key=auth_key).user if request.method == "POST" and generic_user: #do whatever needed... However the views is not reading the headers and throws an error. I could simply remove the Authentication/token line and voila! but the thing is that I want to keep the code as secure as possible. What is wrong with my code? -
How to add event liteners in Django?
I have the following code in html with a js script, but i want to add it to my django forms but i don't know how or where to start. What it does is that it automatically multiplies two numbers as the user types and shows the predict in a different part of the table. {% extends "blog/base.html" %} {% block content %} <h1>About Page</h1> <div class="container"> <h2>Basic Table</h2> <form> <table class="table"> <thead> <tr> <th>Value</th> <th>Amount</th> <th>Total</th> </tr> </thead> <tbody> <tr> <td>10</td> <td> <div class="form-group"> <label for="usr"></label> <input type="text" class="form-control" id="num1" /> </div> </td> <td> <div id="total"></div> </td> </tr> <tr> <td>20</td> <td> <div class="form-group"> <label for="tt"></label> <input type="text" class="form-control" id="num2" /> </div> </td> <td> <div id="total 2"></div> </td> </tr> <tr> <td>30</td> <td><div class="form-group"> <label for="ttt"></label> <input type="text" class="form-control" id="num3" /> </div></td> <td><div id="total 3"></div></td> </tr> </tbody> </table> </form> </div> <script> function multiply(a, b, outputId) { var total = a * b; document.getElementById(outputId).innerHTML = total; } const num1 = document.getElementById('num1'); const num2 = document.getElementById('num2'); const num3 = document.getElementById('num3'); num1.addEventListener('input', (event) => { console.log(event); multiply(10, Number(event.target.value), 'total'); }); num2.addEventListener('input', (event) => { multiply(20, Number(event.target.value), 'total 2'); }); num3.addEventListener('input', (event) => { multiply(30, Number(event.target.value), 'total 3'); }); </script> {% endblock content %} I … -
Populating CheckboxSelectMultiple widget using my own model in Wagtail admin
Context I've created a model, corresponding field model, and intend to reuse the built-in CheckboxSelectMultiple widget for use within the Wagtail admin. The concept is a multiple-select permission field that is saved as a bit-field: # Model class class Perm(IntFlag): Empty = 0 Read = 1 Write = 2 I used Django's model field's documentation to create a field model that can translate my Perm type to and from my database (saved as an integer field that bitwise OR's the respective permission bits): # Model field class class PermField(models.Field): description = "Permission field" def __init__(self, value=Perm.Empty.value, *args, **kwargs): self.value = value kwargs["default"] = Perm.Empty.value super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() args += [self.value] return name, path, args, kwargs def db_type(self, connection): return "bigint" # PostgresSQL def from_db_value(self, value, expression, connection): if value is None: return Perm.Empty return Perm(value) def to_python(self, value): if isinstance(value, Perm): return value if isinstance(value, str): return self.parse(value) if value is None: return value return Perm(value) def parse(self, value): v = Perm.Empty if not isinstance(ast.literal_eval(value), list): raise ValueError("%s cannot be converted to %s", value, type(Perm)) for n in ast.literal_eval(value): v = v | Perm(int(n)) return v Then, I also created a Wagtail snippet … -
How to implement multi-step product creation with related models (Tax, Currency, Delivery Area, Category) in Django Rest Framework?
I am working on a product creation process using Django Rest Framework (DRF), and I have models for Tax, Currency, DeliveryArea, Category, and Product. The creation process is divided into multiple steps, with each step capturing different parts of the product's information. Here's what I am trying to achieve: Models: Product: The main model that represents the product. Category: The category to which the product belongs. Currency: The currency for the product's price. DeliveryArea: The delivery area for the product. Tax: The tax details for the product. Steps in the Process: Step 1: Product name, description, and category. Step 2: Price, currency, and delivery area. Step 3: Tax information. What I Need: Data Persistence: I need to save the data progressively as the user completes each step of the form. Step-by-step editing: Users should be able to return to any previous step and update their inputs without losing the progress in the steps they've already completed. Related Models: I need to handle the relationships between the Product model and the other models (Category, Currency, DeliveryArea, and Tax). Approach I've Considered: I plan to use DRF serializers for each step, with the relevant fields for that step. I want to use … -
Django: from user's language to the locale string - how to?
In our Django/Python/Linux stack we want to determine the correct locale from the user's language. The language might be 'de' and the locale could be something like de_DE or de_AT or even de_CH.UTF-8 - depending on what locale -a returns. In case of ambiguity we would just use the first valid entry for the respective language. This locale string shall than be used to determine the correct number format for instance like so: locale.setlocale(locale.LC_ALL, user.language) formattedValue = locale.format_string(f'%.{decimals}f', val=gram, grouping=True) We don't want to create a relation between language code and locale string in our application - so defining a dictionary containing languages and locale strings is not something we have in mind. The information should be retrieved generically. Any ideas how to do it in a proper way? -
"Why is the object passed through Link state in React undefined when accessed via useLocation on the next page?"
I'm having trouble passing an object through the Link state in React Router, and it's coming up as undefined when I try to access it on the next page using useLocation. Here’s a breakdown of my setup and the issues I'm encountering. Staff Component (Staff.js) I'm fetching staff data from an API and rendering it with React Router's Link: import React, { useEffect, useState } from 'react'; import { Link } from 'react-router-dom'; const Staff = () => { const [staffMembers, setStaffMembers] = useState([]); useEffect(() => { // Fetch staff data from API fetch('https://api.example.com/staff') .then(response => response.json()) .then(data => setStaffMembers(data)) .catch(error => console.error('Error fetching staff:', error)); }, []); return ( <div className="hidden p-5 md:grid md:grid-cols-4 gap-6"> {staffMembers.map((staff) => ( <Link key={staff.id} to={{ pathname: `/staff/${staff.title.replace(/\s+/g, '-')}`, state: { staff } // Pass the entire staff object here }} className="image-div shadow hover:shadow-lg text-center rounded flex flex-col items-center border-l-8 border-yellow-200 p-3" > {staff.title_logo ? ( <img src={staff.title_logo} alt={staff.title} className="w-16 h-16" /> ) : ( <div className="w-16 h-16 bg-gray-300 flex items-center justify-center"> <span>No Logo Available</span> </div> )} <span className='mb-2 font-semibold text-lg'>{staff.title}</span> </Link> ))} </div> ); }; export default Staff; Staff Detail Component (StaffDetail.js) I’m trying to access the passed staff object using useLocation: import … -
Should the csrf template tag be used in a Search form?
I have a django view that allows a user to search and get data from a database. No changes are made to the database. I also realized that the csrf token shows up in the url. I searched online and read that this shouldn't be the case and that when making GET requests I should not include the csrf token but I am still not sure. Here is my code: view: class SearchResultsListView(ListView): model = Processor template_name = 'finder/search_results.html' paginate_by = 10 # Number of results per page def get_queryset(self): query = self.request.GET.get("q") return Processor.objects.filter( Q(name__icontains=query) | Q(standard_transaction_fee__icontains=query) | Q(accepted_payment_methods__icontains=query) | Q(available_merchant_countries__icontains=query) | Q(supported_business_types__icontains=query) | Q(basic_info__icontains=query) | Q(restricted_prohibited_business__icontains=query) ) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['query'] = self.request.GET.get('q', '') return context html: <div class="search-container-container"> <div class="search-results-container"> <!-- Top search bar --> <div class="search-header"> <form action="{% url 'search_results' %}" method="GET" class="search-search-form"> {%csrf_token%} <input type="text" name="q" class="search-input" placeholder="Search processors..." value="{{ request.GET.q }}" aria-label="Search" > <button type="submit" class="search-button"> Search </button> </form> </div> -
Query N rows around the row id with complex ordering in Django ORM
According to the reference id, I want to query N rows, so that the row with the reference id would be in the middle. I know how to do it when the QuerySet is simply ordered by id column, but my solution falls apart when I want to order the results by a column other than id (as ids are not sequential anymore) or by multiple columns (e.g. (title, created_at)). For example, if I had 5 items in the table below, and wanted to query 3 items with a reference id of 3, it would select rows with id 2, 3 and 4: Id Title 1 One 2 (Selected) Two 3 (Selected) Three 4 (Selected) Four 5 Five I tried using Window() function with RowNumber() expression to assign row numbers to a sorted list of items, and then query items before and after the reference id row number, which, unsurprisingly, did not work as row numbers are recomputed on each query. -
I want to construct a value dynamically with variable number of parents python django
I am working on a django project. I have my Providable model and a foreign key: category (providable_categtory). each category can have multiple sub-categories and a providable will finally be assigned to a leaf node. here is how the category code for each providable is created: @property def get_code(self): return f"{self.category.get_code}-{self.code}" the get_code method in providable_category: @property def get_code(self): if not self.parent: return self.code else: return f"{self.parent.get_code}-{self.code or self.pk_code}" as you can see when i display a providable code in the django admin it's something like: a-b-c-6 where a,b and c are categories and 6 is the providable's own code. so now I want to be able to search for a providable in django admin using it's full code but since the full providable code is not a field of providable it can't be done directly by adding the get_code method to search field. what I did was, I implemented an override of the get-search_results method in my ProvidableAdmin class as below: def get_search_results(self, request, queryset, search_term): # annotation for the service_code. queryset = queryset.annotate( service_code=Concat( "category__parent__parent__code", Value("-"), "category__parent__code", Value("-"), "category__code", Value("-"), "code" ) ) queryset, may_have_duplicates = super().get_search_results(request, queryset, search_term) return queryset, may_have_duplicates and added service_code to search_fields. this … -
Connecting to mariaDB in Github action
I know there are multiple related questions but I can't get this to work. I'm working on a Github action to test my Django app using MariaDB and Selenium before deploying. I have simplified it to just running the tests for now. I have reviewed my secrets and know they are correct. I have tried running services on both localhost and in a container, but neither can seem to resolve the database address. I have tried it like this: name: Deploy on: push: jobs: django-tests: runs-on: ubuntu-latest services: db: env: MYSQL_ROOT_PASSWORD: ${{ secrets.MYSQL_ROOT_PASSWORD }} MYSQL_DATABASE: ${{ secrets.MYSQL_DATABASE }} MYSQL_USER: ${{ secrets.MYSQL_USER }} MYSQL_PASSWORD: ${{ secrets.MYSQL_PASSWORD }} image: mariadb:11.5 options: > --health-cmd="healthcheck.sh --connect --innodb_initialized" ports: - 3306:3306 selenium: image: selenium/standalone-chrome ports: - 4444:4444 steps: - name: Check out code uses: actions/checkout@v3 - name: Debug Hostname Resolution run: | ping -c 4 localhost:3306 || echo "Failed to resolve 'db'" - name: Set up Python uses: actions/setup-python@v4 with: python-version: 3.12 - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Run Django Selenium Tests env: SECRET_KEY: ${{ secrets.DJANGO_SECRET }} MYSQL_ROOT_PASSWORD: ${{ secrets.MYSQL_ROOT_PASSWORD }} MYSQL_DATABASE: ${{ secrets.MYSQL_DATABASE }} MYSQL_USER: ${{ secrets.MYSQL_USER }} MYSQL_PASSWORD: ${{ secrets.MYSQL_PASSWORD }} … -
HX-Trigger to issue a request using arguments
I want to create a request after a trigger using htmx after a button was clicked with django: def SomeView(request, var1, var2): trigger_data = json.dumps({"dlstart": {"pid": pid, "var1": var1}}) return HttpResponse("", headers={"HX-Trigger": trigger_data}) I can see in the Network Tab the GET request is working. But now I want to add the two arguments from trigger_data to my hx-get dynamically. I did not find a way in htmx alone to achieve this, so I did a JS workaround (which I would gladly drop in favor of a htmx only solution): document.body.addEventListener("dlstart", function() { const url = `/someURL/${event.detail.pid}/${event.detail.var1}`; const filename = "test.png"; fetch(url) .then(response => { if (!response.ok) { throw new Error('was not ok'); } return response.blob(); }) .then(blob => { const link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = filename; document.body.appendChild(link); link.click(); // feels so ugly document.body.removeChild(link); }) }); I imagine some combination of hx-get and dynamically add the arguments must work too? -
Docker Compose - The ImageField field in Django cannot upload images when I migrate the database from sqlite3 to MySQL in Docker Compose
I have the Article model in Django blog app File /backend/blog/models.py class Article(models.Model): class Status(models.TextChoices): DRAFT = 'DF', 'Draft' PUBLISHED = 'PB', 'Published' title = models.CharField(max_length=255) slug = models.SlugField(max_length=100, blank=True, unique=True) content = MDTextField(null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) comments = models.IntegerField(default=0) reactions = models.IntegerField(default=0) updated = models.DateTimeField(auto_now=True) category = models.ForeignKey(Category, related_name='articles', on_delete=models.SET_NULL, null=True) tags = models.ManyToManyField(Tag) image_background = models.ImageField(upload_to='articles_images/', blank=True, null=True) image_url = models.URLField(max_length=500, blank=True, null=True) # Updated field to store image URL from Firebase intro = models.TextField() estimate_time = models.CharField(max_length=50) type = models.ForeignKey(Type, on_delete=models.SET_NULL, null=True) publish = models.DateTimeField(default=timezone.now) status = models.CharField(max_length=2, choices=Status.choices, default=Status.DRAFT) Next, I porting the default database SQLITE3 to MYSQL for Django project File /backend/settings.py # ! Config database for mysql DATABASES = { "default": { "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"), "NAME": os.environ.get("SQL_DATABASE", os.path.join(BASE_DIR, 'db.sqlite3')), "USER": os.environ.get("SQL_USER", "myuser"), "PASSWORD": os.environ.get("SQL_PASSWORD", "myuserpassword"), "HOST": os.environ.get("SQL_HOST", "localhost"), "PORT": os.environ.get("SQL_PORT", "3306"), 'OPTIONS': { 'charset': 'utf8mb4', } } } I also config the path media to upload image /backend/settings.py STATIC_URL = 'static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = (os.path.join(BASE_DIR,"static"), ) I used the docker-compose.yml to build image and run container for backend (django), frontend (nextjs) and database (mysql) to develop my project version: '3.8' services: database: image: … -
django: unable to customise the admin history page
I want to display the old and new values in the history log page. I have been able to save the data and print it to the server but I cannot seem to customise the history page layout / rendering... it simply ignores my file. I have created a custom html file in the folder: project/app/templates/admin/app/modelname/history.html (project/api/templates/admin/api/apicustomer/history.html) after several hours of GPT i give up! Can andybody advise? -
Django populate Model form dynamically with model - possible?
I am trying to use a model form independently of the model that is passed. My goal is to have a list of database tables where the user can select the table which is then displayed. Then within this table there is the possibility to select a table entry which can be updated. There will be changing tables over time, therefore I want to use one model form to include all the fields for editing and just change the underlying Model. I tried some things and right now this is my "last" attempt that is not working. Any advice or guidance? This is in my views.py class DynamicModelForm(forms.ModelForm): class Meta: model = None fields = '__all__' # setting the model based on the input selection of user def get_dynamic_form(request, model, instance=None): DynamicModelForm.model = model DynamicModelForm.fields = '__all__' return DynamicModelForm(request.POST or None , instance=instance) # # # # in my class based view I am using this to list the tables def list(self, request, model, model_name): print(f'Pulling model {model_name}') objects = model.objects.all() fields = [field.name for field in model._meta.fields] # Retrieve field names self.context['fields'] = fields self.context['model_name'] = model_name self.context['objects'], self.context['info'] = set_pagination(request, objects) if not self.context['objects']: return False, self.context['info'] return … -
How to deploy a Django app on a Linux server on a home network such that it is only ever accessible by the people on the network?
How to deploy a Django app on a Linux server on a home network such that it is only ever accessible by people on the network? I have a Django app that I'd like to deploy on a Linux server, but I only want it to be accessible to devices within my home network (e.g., computers and mobile devices connected to the same Wi-Fi). I don't want it to be publicly accessible over the internet. I have the following setup: The Django app is running on a Linux server (Ubuntu 20.04). The server is connected to my home network via Ethernet or Wi-Fi. I want to ensure that the app can be accessed from devices on the same network but not from outside the network. What is the best way to deploy and configure this Django app to achieve the following? Restrict access to the home network: I want the app to only be accessible by devices that are physically connected to the home network (e.g., via Wi-Fi or Ethernet) and not exposed to the outside world. Web server configuration: Should I use Gunicorn or uWSGI with Nginx or Apache? How should I configure them to ensure proper security and … -
How to design a scalable messaging system with Celery, Redis, Django Channels, and FastAPI?
I am designing a scalable messaging system based also in Django, where users can exchange messages in real-time. Here are the key requirements and technologies I am planning to use: I plan to use Celery for background task processing, such as handling message delivery and notifications. Redis will act as the broker. I am considering a NoSQL database, such as MongoDB, to store messages due to its flexibility and scalability. Each message will have fields like message_id, sender_id, receiver_id, content, timestamp, and status. Just a single table approach. For real-time message delivery and user notification, I am exploring Django Channels or FastAPI with WebSockets. Caching Layer: Redis will also be used as a caching layer to improve performance for frequently accessed data, such as user notifications or unread messages. Scalability and Performance: The system should support up to 1,000 messages per second. It should handle over 10,000 concurrent users viewing messages simultaneously. Daily active users may exceed 100,000. My Questions: Is this architecture suitable for my requirements, or should I consider alternative technologies? At what scale should I start considering sharding my MongoDB database to handle the load efficiently? Would a load balancer (e.g., Nginx) suffice to handle the WebSocket … -
Django and Gunicorn setup
I followed this video https://www.youtube.com/watch?v=NSHshIEVL-M and ran into problems when trying to curl the webpage. I thought it might be a firewall issue but since I'm running the curl command locally would that be an issue? I also ran which gunicorn from inside my environment and populated that the in the gunicorn.service file under ExecStart. I have shared my configs below any help is appreciated! django setup: Gunicorn config: gunicorn.service curl command output -
How to validate Django models with foreign key relationships before saving any records?
I am working on a Django project where I need to validate a model before saving it, based on values in its related models. I came up with this issue while extracting an app from an project using an old Django version (3.1) to a separate Django 5.1 project, then there error "ValueError: 'Model...' instance needs to have a primary key value before this relationship can be used" raised on all validation classes that used related model data. For demonstration and simplification purposes, I have a Reservation model that references multiple Guest objects via a foreign key. For the reservation to be valid and be saved, all guests linked to it must be at least 18 years old. However, none of these records (neither the reservation nor the guests) have been saved to the database yet. I need to perform this validation efficiently and cleanly, preferably in a way that keeps the validation logic separated from the models themselves. How can I approach this validation scenario? What are the best practices for validating unsaved foreign key relationships in Django? Here is a simplified version of my setup: File: models.py from django.db import models class Reservation(models.Model): check_in_date = models.DateField() check_out_date = … -
No module named 'psycop'. Cannot make migrations
I'm trying to get a login page not to return a 500 error, and have been trying to migrate my database. I have installed psycopg2 correctly (I believe), but I think I have not got the correct NAME in DATABASES at settings.py. Here is what I have: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': BASE_DIR / 'db.postgresql', } } Would somebody know if what I have in 'NAME' is correct, or what else I should put in there? Thank you. -
Why ValueError is not handled upon my Django Middleware?
I am Implementing a Basic view that raises a ValueError: from rest_framework.views import APIView from django.http import HttpResponse class ThreadView(APIView): def get(self, request, *args, **kwargs): limit = int(request.GET.get('limit', 10)) if limit < 0: raise ValueError("Limit must be a positive number") return HttpResponse("OK",200) And I made a simple middleware as well: from django.http import JsonResponse class ErrorMiddlewareHandler: """ Custom middleware to handle Errors globally and return a standardized JSON response. """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): try: # Process the request and pass to the view response = self.get_response(request) except ValueError as v: print("mIDDLEWARE ",v) response = JsonResponse({'msg': str(v)}, status=400) # You can change status as needed except Exception as e: response = JsonResponse({'msg': "Internal Error occired"}, status=500) return response I registered it into settings.py: 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', 'assistant_api.middleware.ErrorMiddlewareHandler.ErrorMiddlewareHandler', # <<< This One ] But it seem middleware not to be able to handle it: Despite being registered into middlewares. Do you know why??? -
Django Admin: How to hide nested inline until parent is saved?
I have a nested inline setup in Django Admin where I want to hide a child inline until its parent is saved. Here's a simplified version of my models: class Parent(models.Model): name = models.CharField(max_length=255) class Child(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) name = models.CharField(max_length=255) class GrandChild(models.Model): child = models.ForeignKey(Child, on_delete=models.CASCADE) name = models.CharField(max_length=255) And here's my admin setup: class GrandChildInline(NestedTabularInline): model = GrandChild extra = 0 def get_formset(self, request, obj=None, **kwargs): formset = super().get_formset(request, obj, **kwargs) return formset class ChildInline(NestedTabularInline): model = Child extra = 0 inlines = [GrandChildInline] class ParentAdmin(NestedModelAdmin): inlines = [ChildInline] admin.site.register(Parent, ParentAdmin) Current Behavior When editing a Parent, I can add Children The GrandChild inline is visible immediately when adding a new Child I want the GrandChild inline to only appear after the Child is saved Desired Behavior GrandChild inline should be hidden when adding a new Child GrandChild inline should only appear after the Child is saved GrandChild inline should be visible when editing an existing Child What I've Tried Using the template property to return an empty string Using has_add_permission and get_queryset Checking for parent instance existence None of these approaches fully work - either the inline is always visible or always hidden. Question How … -
Django fails to correctly link viewable documents stored in a Django model
So I currently have a Django model which correctly references everything passed to my template, except for the link to the document I have uploaded. The model has been correctly registered in admin.py. Here is is MRE: #investors/models.py from django.db import models class FinancialStatements(models.Model): financials_upload = models.FileField(upload_to='documents/financials/') class Meta: verbose_name_plural = "Financial Statements" #investors/views.py from .models import FinancialStatements def investor_relations(request): financials_queryset = FinancialStatements.objects.all() context = { 'financials_queryset' : financials_queryset, } return render(request, 'investors.html', context) #settings.py MEDIA_URL = '/assets/' MEDIA_ROOT = BASE_DIR / 'assets' #investors/templates/investors.html {% for financials in financials_queryset %} <a href="{{financials.financials_upload.url}}">Financial Statement</a> {% endfor %} Upon accessing the uploaded file from the model, the URL is http://127.0.0.1:8000/assets/documents/financials/<filename>.pdf which is the directory I want to specify, and so is correct. However, Django is continuing to fail to access the URL from {{financials.financials_upload.url}} when looping through the financials_queryset quertset My file directory is set up in the following fashion: <ROOT>/assets/documents/financials/** Whenever I hover over the <a> tag, the message in the bottom of the left corner of the browser fails to return the URL of the document to be viewed. It simply returns http://127.0.0.1:8000/investors Despite this, I do fail to see how cannot work this one out, despite correctly point it … -
Settings.py cannot find psycopg2... squlite3 and postgresql problem... no such table: auth_user
I'm trying to deploy a simple app (learning log from Python Crash Course) to heroku. The app runs but upon login, I get a 500 error, and in debug=true the error is: no such table: auth_user. I realise this has something to do with squlite3 and Postgresql, but when I try to build the code in settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': BASE_DIR / 'db.sqlite3', } } the error message is ImportError: DLL load failed while importing _psycopg: The specified module could not be found. I have attempted to install and import psycopg2, and it appears to be in requirements.txt. But I think the paths are not aligning, since psycopg2 is in a python pathway, and setting.py is looking in my project environment. I'm very confused! Please help!