Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and React push rejected, failed to compile on Heroku
I have been trying to deploy my Django and React application on Heroku in vain. The Django and React integration have been done by following more or less this guide: https://www.fusionbox.com/blog/detail/create-react-app-and-django/624/ The React app setting in settings.py: STATIC_URL = '/static/' REACT_APP_DIR = os.path.join(BASE_DIR, 'frontend') STATICFILES_DIRS = ( os.path.join(REACT_APP_DIR, 'build', 'static'), ) STATIC_ROOT = 'static/' My urls.py: from django.urls import re_path, path from backend.views import FrontendAppView urlpatterns = [ re_path('', FrontendAppView.as_view(), name='home'), ] My view: class FrontendAppView(View): """ Serves the compiled frontend entry point (only works if you have run `yarn run build`). """ def get(self, request): print(os.path.join(settings.REACT_APP_DIR, 'build', 'index.html')) try: with open( os.path.join(settings.REACT_APP_DIR, 'build', 'index.html')) as f: return HttpResponse(f.read()) except FileNotFoundError: logging.exception('Production build of app not found') return HttpResponse( """ This URL is only used when you have built the production version of the app. Visit http://localhost:3000/ instead, or run `yarn run build` to test the production version. """, status=501, ) The error I am having. The Error is coming probably from this FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_79d83787/frontend/build/static' If yes then my question is why it is looking for '/tmp/build_79d83787/frontend/build/static'? if no, then what is the problem then. -----> Building on the Heroku-20 stack -----> Using … -
Django - Custom Cross Join fails due to expected join fields for on clause
I've created a custom class for implementing cross join's in Django using the following code class CrossJoinToFunction(Join): def __init__(self, table_name, parent_alias, table_alias, join_type, join_field, nullable, filtered_relation=None, table_function_params: List[Any] = None): super().__init__(table_name, parent_alias, table_alias, join_type, join_field, nullable, filtered_relation) self.table_function_params = table_function_params # type: List[Any] def as_sql(self, compiler, connection): sql, params = super().as_sql(compiler, connection) table_function_placeholders = [] table_function_params = [] for param in self.table_function_params: if hasattr(param, 'as_sql'): param_sql, param_params = param.as_sql(compiler, connection) else: param_sql = '%s' param_params = [param] table_function_placeholders.append(param_sql) table_function_params += param_params sql = '{} {}({}) {}'.format( self.join_type, compiler.quote_name_unless_alias(self.table_name), ', '.join(table_function_placeholders), self.table_alias ) return sql, table_function_params + params which can be used on custom Query as following self.alias_map[alias] = CrossJoinToFunction( join.table_name, join.parent_alias, join.table_alias, join.join_type, None, None, None, resolved_params ) The desired output in SQL from this is as follows select fb.id cf.some_returned_value from foobar fb cross join custom_function(params..) as cf The issue arrises with Django always expecting there to be a join_field for all joins. This conflicts with cross joins, as they do not have an on clause. Adding join.join_field throws to the CrossJoinToFunction raises the following django error self.alias_map[alias] = CrossJoinToFunction( join.table_name, join.parent_alias, join.table_alias, join.join_type, join.join_field, join.nullable, join.filtered_relation, resolved_params ) File "/Users/timmcgee/Documents/main-site/project/models.py", line 1493, in setup_joins join.table_name, join.parent_alias, join.table_alias, join.join_type, … -
Where should I set model fields derived from a form field?
Given a model with some fields which do not map directly to a ModelForm's fields, where should I set their value? In the following, form.blast_db should be assigned to either model.protein_db or model.nucleotide_db depending on what type of blast DB it is. They are mutually exclusive but required, so they must be set before model.full_clean() is called. from django.db import models class BlastQuery(models.Model): # Protein/nucleotide blast DB. Mutually exclusive, one must be provided protein_db = models.ForeignKey(ProteinDB, null=True, blank=True) nucleotide_db = models.ForeignKey(ProteinDB, null=True, blank=True) # Just 1 field to keep it terse but in reality there are many other fields foo = models.IntegerField() def clean(self): if self.protein_db and self.nucleotide_db: raise ValidationError('Protein/nucleotide DB are mutually exclusive') if not self.protein_db and not self.nucleotide_db: raise ValidationError('Protein/nucleotide DB are required') from django import forms class BlastForm(forms.ModelForm): # Magical field that's like a ModelChoiceField but can # hold both ProteinDB and NucleotideDB instances blast_db = BlastDBField() class Meta: model = BlastQuery fields = ('foo',) -
What is wrong with my upload CSV in Django?
I have created I think pretty standard code but the file seem not to get uploaded! My set up folder is empty plus no file displays after i click submit! When pressing submit I only see "GET /?csrfmiddlewaretoken=9JefYLkycrupVof72b1oujZ2DSi0o5BlfujkW27PhVDWBcoZyzc74aZ9yckOkJUz&myfile=file+.csv HTTP/1.1" 200 2844 and similar messages My code: Main project folder: In setting.py added MEDIA_URL = '/documents/' MEDIA_ROOT = os.path.join(BASE_DIR, 'documents') urlpatterns = [ ] if DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) url.py from django.contrib import admin from django.urls import path from django.conf.urls import include from mainsite import views as main urlpatterns = [ path('admin/', admin.site.urls), path('', main.model_form_upload, name= 'index'), path('contact/', include('contact.urls')), path('explanation/', include('modelexpl.urls')), path('uploads/', main.model_form_upload, name='model_form_upload') ] Then in my project folder: urls.py from django.shortcuts import render from django.http import HttpResponse from django.urls import path from mainsite import views # Create your views here. urlpatterns = [ path('', views.index, name='index') ] models.py from django.db import models # Create your models here. class Document(models.Model): description = models.CharField(max_length=200, blank= True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) views.py: initially I added following function: from django.shortcuts import render from django.http import HttpResponse from mainsite.models import Document from mainsite.forms import DocumentForm from django.core.files.storage import FileSystemStorage # Create your views here. def index (request): placeholder = {'test' : … -
Change instance values after capture change with Django Signals
I have a model Course that have a ManyToMany relation with my CustomUser model: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('Email Address'), unique=True) user_name = models.CharField(_('User Name'), max_length=150, unique=True) # and a lot of other fields and stuff class Course(models.Model): enrolled_users = models.ManyToManyField(CustomUser, related_name="enrolls", blank=True) previous_enrolled_users = models.ManyToManyField(CustomUser, related_name="previous_enrolls", blank=True) course_name = models.CharField(_("Course Name"), max_length=200) What I'm trying to implement is that whenever a user finishes a course (and so the user is removed from enrolled_users), my application stores this user in previous_enrolled_users, so I can know the users that were previously enrolled at that course. I've implement a m2m_changed signal listening like this: def listen_m2mchange(sender, instance, model, pk_set, action, **kwargs): if action == 'pre_remove': # I'm trying to guess what to do m2m_changed.connect(listen_m2mchange, sender=Course.enrolled_users.through) With that, whenever I remove a user from a course, Django signals the m2m_changed and I capture that signal. I know that instance is the instance of the Course class and that model is the instance of that CustomUser class I'm removing. What I could not guess is how, using the instance of Course class, I can add the CustomUser in the previous_enrolled_users. Any help will be very appreciated. -
pipenv updates all dependencies bringing breaking changes
I'm having problems with an app that uses Django. Everything is in a docker container, there is a pipfile and a pipfile.lock. So far, so good. The problem is when I want to install a new depedency. I open the docker container shell, and I install the dependency with pipenv install <package-name>. After installing the package, pipenv runs a command to update the pipfile.lock file and doing so updates all packages to their last version, bringing whit these updates a lot of breaking changes. I don't understand why is this happening, I have all packages listed in my pipfile with ~=, this is suppose to avoid updating to versions that can break your app. I'll give you an example, I have this dependency in my pipfile: dj-stripe = "~=2.4". But, in the pipfile.lock file, after pipenv runs the command lock, that depedency is updated to its last version (2.5.1). What am I doing wrong? -
Django rest framework: exclude results when nested serializer is empty
I have a nested serializer that works, but I would like to exclude instances where the nested serializer is empty. The filtering I'm using on the nested serializer works, but currently this code returns all Sites, most of which have empty site_observations arrays when filters are applied. I would like to return only Sites that contain site_observations. I have tried a SerializerMethodField for site_observations but have the same issue. Using DRF 3.12 Relevant models are Site, and Observation which has FK to site, with related field=site_observations serializers.py class FilteredObsListSerializer(serializers.ListSerializer): def to_representation(self, data): projName = self.context["projName"] # this is my filter which works data = filter_site_observations(data, self.context["request"], projName) return super(FilteredObsListSerializer, self).to_representation(data) class ObsFilterSerializer(serializers.ModelSerializer): class Meta: list_serializer_class = FilteredObsListSerializer model = Observation fields = "__all__" class SiteSerializer(GeoFeatureModelSerializer): site_observations = ObsFilterSerializer(many=True) class Meta: model = Site geo_field = "geometry" fields = ("id", "name", "geometry", "site_observations") views.py class SiteList(generics.ListAPIView): queryset = Site.objects.all().order_by("pk") serializer_class = SiteSerializer # this is for filtering Observations on segment of an url: def get_serializer_context(self): context = super(SiteList, self).get_serializer_context() context.update({"projName": self.kwargs["name"]}) return context How can I exclude Sites where site_observations is an empty list? Thanks. -
Django and Ajax: add to Favourites button in a for loop functioning and making changes to database but not changing colour/name appropriately
I'm having difficulty understanding why my favourite buttons will not change colour and name when clicked to match the data in the database. I presume it is due to the way I have set up the 'is_fav' boolean variable but I've been unable to work out a fix. Any help is greatly appreciated! the view: def favourite_unfavourite(request): html = None #if request.method == 'POST': activity_id = request.POST.get('activity_id') activity = get_object_or_404(TherapyActivity, id=activity_id) #is_fav = False if activity.favourites.filter(id=request.user.id).exists(): activity.favourites.remove(request.user) is_fav = False else: activity.favourites.add(request.user) is_fav = True context = { 'Activity': activity, 'is_fav': is_fav, 'value': activity_id } if request.is_ajax(): html = render_to_string('main/favourite_section.html', context, request=request) return JsonResponse({'form': html}) page html: {% extends "main/index.html" %} {% block title %} <h1>View All</h1> {% endblock %} {% block content %} {% for activity in activities %} <div class="col-md-7 d-flex justify-content-between"> <li><a href="{{activity.get_absolute_url}}">{{activity.name}}</a> <br> {{activity.description}} </li> <div id="favourite-section"> {% include 'main/favourite_section.html' with activity=activity %} </div> </div> {% endfor %} {% endblock %} included section: {% if request.user.is_authenticated %} <form action="{% url 'account:favourite_unfavourite' %}" method="post"> {% csrf_token %} {% if fav %} <button type="submit" id="favourite" name="activity_id" value="{{ activity.id }}" class="btn btn-danger">Unfavourite</button> {% else %} <button type="submit" id="favourite" name="activity_id" value="{{ activity.id }}" class="btn btn-primary">Favourite</button> {% endif %} </form> {% … -
Heroku deploy with django database issue
i need some, did lot of research but cant find the solution. i just deployed my app into heroku, everything seem to work just fin, but the cant access to the database from the APP, admin looks empty. But the database is there on heroku when i check it database in heroku Settings.py Whitenoise whitenoise 2 database conection static urls.py static in URL i think maybe some config with the connection is missing, but i dont know what else to do... thanks in advanced for any help! -
Making API calls for authentication tasks in Angular
I'm trying to build an authentication system using Django, Django rest framework, angular, and I have been based on Dj-rest-auth to handle user registration and authentication tasks. I finished implementing the back-end level, but I'm getting stuck on how can I make API calls to register new users, log in as an authenticated user, and other queries such as forgot password, and email confirmation. Would you please help me to implement that in service.ts? -
Problem installing Pandas and Numpy on Heroku
I am trying to install Django 3.0.5 on heroku with numpy==1.18.3and pandas==1.0.3 libraries included in the requirements.txt file but it keeps running into an error. I have python-3.7.10 in my runtime.txt I ran the install command, but it gives me the following errors. git push heroku main and I am getting this error: Counting objects: 100% (107/107), done. Delta compression using up to 12 threads Compressing objects: 100% (95/95), done. Writing objects: 100% (107/107), 223.74 KiB | 6.99 MiB/s, done. Total 107 (delta 19), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> No Python version was specified. Using the buildpack default: python-3.9.6 remote: To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.9.6 remote: -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting asgiref==3.2.7 remote: Downloading asgiref-3.2.7-py2.py3-none-any.whl (19 kB) remote: Collecting certifi==2020.4.5.1 remote: Downloading certifi-2020.4.5.1-py2.py3-none-any.whl (157 kB) remote: Collecting chardet==3.0.4 remote: Downloading chardet-3.0.4-py2.py3-none-any.whl (133 kB) remote: Collecting coverage==5.5 remote: Downloading coverage-5.5-cp39-cp39-manylinux2010_x86_64.whl (243 kB) remote: Collecting Django==3.1.12 … -
Is Mysql good for Django?
Do you think I can use MySql with Django, cuz a friend tells me it's not the best choice to use with Django framework -
Getting CSV saving in the document folder
I know this question probably appeared million times, but I cannot get my code to work. I want to upload csv to a folder, so I can make further operations on it. I think the problem might be in my HTML code, but not sure where. Folder I want to save it to is documents/, I did not add it to settings.py but I saw other people were not adding it there either. My code is as per below: Main urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include from mainsite import views as main urlpatterns = [ path('admin/', admin.site.urls), path('', main.index, name= 'index'), path('contact/', include('contact.urls')), path('explanation/', include('modelexpl.urls')), path('uploads/', main.model_form_upload, name='model_form_upload') ] App urls.py from django.shortcuts import render from django.http import HttpResponse from django.urls import path from mainsite import views # Create your views here. urlpatterns = [ path('', views.index, name='index') ] App's models. from django.db import models # Create your models here. class Document(models.Model): description = models.CharField(max_length=200, blank= True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) App's views from django.shortcuts import render from django.http import HttpResponse from mainsite.models import Document from mainsite.forms import DocumentForm # Create your views here. def index (request): placeholder = {'test' : … -
Can't import image in Django
Here is my project structure I'm trying to display the image from the static folder but it can't be displayed. I also tried to mention the static folder in the settings.py file as below: Here is how I'm calling the image from the base.html file. I'm not sure what is wrong, I tried to search but the google sources can't help. -
How to add a horizontal rule in bootstrap?
I'm trying to add a horizontal rule in-between my divs. Here is my code. Div("Name", css_class='col-sm-12'), Div("Address", css_class='col-sm-6'), Div("Favorite_Movie", css_class='col-sm-6'), <hr> <-- Horizontal rule would go here. -
Key encyption, front-end back-end question
I have a front end which has some api credentials which are needed to receive information for the front-end. I also want to store these credentials in a database so that the user does not need to enter these api credentials with every log in, rather the api credentials are 'there'. How should these api keys be stored in the back end and then de-crypted in the front-end? -
Django: On button/link click, send an API request, fetch data, save it in a variable, and put variable in textarea/textbox without refreshing page
I've been breaking my head attempting to come up with a simple solution to something I had in mind. What I'd like to have is: User clicks on a button or a link disguised as a button to reveal information. The server will then send an API request to https://randomuser.me/api, which is outside of the domain. The first name of the random user in the API will be stored in a variable. The variable storing the first name will then be put in the textarea. The button's text will change to "hello" as a greeting instead of just "button" and will not be clickable from now on. OR TO BE FANCY: It can have a timer counting down from 20 minutes. The div that was hidden previously will now show up with the updated button and the textarea filled in with the first name of the random person, ready for the user to copy. I know I can use Python to get requests results from the server. I just don't know how to implement that with Django with the features I want above, especially without Django reloading/refreshing the page. The HTML page: <div> <a href="#" class="button" onclick="showButtonDetails()">button</a> <div id="showDIV" style="display: … -
Custom Django User not saving
So I'm trying to create a user with many fields. I followed a tutorial on how to create a custom user model by inheriting from the base user class and then creating a user manager. I had one of my past professors take a look at it and he couldn't find anything that would keep it from saving, kind of at a loss here. class UserManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, password): """ Creates and saves a superuser with the given email and password. """ user = self.create_user( email, password=password, ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser Full_Name = models.CharField(max_length=200) industry_type = models.CharField(max_length=200) presenter = … -
Deployment Error Heroku [Remote rejected] master -> master (pre-receive hook declined)
I am trying to deploy my app in Django/Heroku but I am having this issue while doing git push Heroku master. This is the error I am getting after this command. Enumerating objects: 654, done. Counting objects: 100% (654/654), done. Delta compression using up to 8 threads Compressing objects: 100% (637/637), done. Writing objects: 100% (654/654), 10.77 MiB | 525.00 KiB/s, done. Total 654 (delta 138), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: ! Requested runtime (python-3.6.8) is not available for this stack (heroku-20). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to warm-taiga-11044. remote: To https://git.heroku.com/warm-taiga-11044.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/warm-taiga-11044.git'``` -
Djanto Singnals is not triggering through admin panel
I have a library that syncs some models with the s3 bucket, so, when someone deletes some row, it should receive the signal and activate the function. Here is the function: @receiver(post_delete) def on_object_deletion(sender, instance, **kwargs): """Upload deleted object to cloud if it is part of synced model""" deletion_time = datetime.datetime.now() # Retrieve the metadata (app and model name) for the model contenttype = ContentType.objects.get_for_model(model=instance) # Skip unnecessary database lookup (never syncs its own models) if contenttype.app_label == "lakehouse_sync": return syncmodel = SyncModel.try_retrieve_model(contenttype.app_label, contenttype.model) if not syncmodel: return # Raise exception if the instance is not BaseSyncModel. # Should be caught during clean() though. if not isinstance(instance, BaseSyncModel): raise Exception("Cannot sync a model that does not inherit BaseSyncModel") # Manually update the timestamp so the lakehouse can merge data instance.updated_at = deletion_time # Write the serialized object to the cloud blacklist = syncmodel.get_blacklist() serialized = Serializer.serialize_object(instance, blacklist) CloudActions.write_delete_file( contenttype.app_label, contenttype.model, serialized.getvalue() ) I didn't set the sender because I'll use this function for any model that inherits from the SyncModel. I'd like to ask for some help to figure out how to activate the signal when I made some deletions through the admin panel. I didn't understand the reason why … -
Maintaining history by soft deleting the row of table
Initially, I was hard deleting SQL rows. Now, I want to soft delete the row by adding a new column in table 'is_active'. if is_active=False, this means the row is deleted, and it is now part of history. But the concern is with the other tables where this table is referenced via a foreign key. earlier, when deleting this row, automatically deletes the record from other tables(model.cascade). Example; Table 1{ id uuid, is_active bool, . . } Table2{ id uuid, fk foreignKey(Table1, on_delete=models.cascade) } Table3{ id uuid, fk foreignKey(Table1, on_delete=models.cascade) } Now, if I will soft delete the table1(making is_active=False), then I have the following option, Add is_active columns to all other tables also which is referencing table1. and follow the same procedure to these tables as for table1. ISSUE: it will be a very hectic task, as some other tables might be pointing to table2, which in result may be referenced by some other tables. and we have manually set is_active=False for table2 and table3. QS. Is there any better approach for soft_deleting the table? like something like that, Table2{ id uuid, fk foreignKey(Table1, on_is_active_is_False=set.is_active=False), is_active bool } -
Django elasticsearch DSL with custom model fields (hashid field)
I have a model that uses django hashid fields for the id. class Artwork(Model): id = HashidAutoField(primary_key=True, min_length=8, alphabet="0123456789abcdefghijklmnopqrstuvwxyz") title = .... This is the related item of another model class ArtworkFeedItem(FeedItem): artwork = models.OneToOneField('artwork.Artwork', related_name='artwork_feeditem', on_delete=models.CASCADE) Now I'm trying to setup [django elasticsearch dsl] (https://github.com/django-es/django-elasticsearch-dsl) and to that end have the Document @registry.register_document class ArtworkFeedItemDocument(Document): class Index: name = 'feed' settings = { 'number_of_shards': 1, 'number_of_replicas': 0 } artwork = fields.ObjectField( properties={ 'id': fields.TextField(), 'title': fields.TextField( attr='title', fields={ 'suggest': fields.Completion(), } ) } ) class Django: model = ArtworkFeedItem fields = [] related_models = [Artwork] However, when I try to rebuild indices with python manage.py search_index --rebuild I get the following exception elasticsearch.exceptions.SerializationError: ({'index': {'_id': Hashid(135): l2vylzm9, '_index': 'feed'}}, TypeError("Unable to serialize Hashid(135): l2vylzm9 (type: <class 'hashid_field.hashid.Hashid'>)",)) Django elasticsearch dsl clearly does not know what to do with such a hashid field. I thought maybe I could just make my own HashIdField like from elasticsearch_dsl import Field class HashIdField(Field): """ Custom DSL field to support HashIds """ name = "hashid" def _serialize(self, data): return data.hashid then use it in 'id': HashIdField, but this gave me yet another exception elasticsearch.exceptions.RequestError: RequestError(400, 'mapper_parsing_exception', 'No handler for type [hashid] declared on field … -
Change sorting order for foreign key entity on Django
I would like to rearrange this dropdown to were profiles are sorted based on A-Z order based on the name. I would like to leave the string formatted in the same format it is now just have them sorted from A-Z. -
Nginx-ajax-django: 504 timeout error on page, error-log: upstream timed out (110: Connection timed out) , TTFB>1
I have a django application running on an nginx server which uses ajax to do asynchronous rendering of an html page. I have got the 504 gateway timeout tried almost every solution mentioned in stack overflow nothing worked out. In my application, I upload an excel sheet from which data is parsed, processed, pushed into database and then status of processing is displayed on an html page. I realized that first two to three rows of data are being processed normally and result is also being displayed correctly.For the remaining rows the backend process is happening correctly but ajax is not receiving the status message from django view. It is showing 504 error message. The error logs are showing upstream timed out error. I even included timeout:333333 in my ajax code. If I make async:false in ajax , process is slowing down and I am getting page unresponsive error message. By closely observing I realized that for processes which are incomplete TTFB is becoming more than 1. So can someone explain what to do? nginx.conf events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush off; tcp_nodelay on; keepalive_timeout 605; types_hash_max_size 2048; … -
Image url in django template doesnt work in production
I'm trying to show images in a one-to-many relationship with a Post model. The Post model is in a one-to-many relationship with a Category model. My code works with debug: True but fails in production. Can anyone see why? settings.py: import os BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') DEBUG = False models.py: class BlogImage(models.Model): b_img = models.ImageField("Blog Image", null=True, blank=True, upload_to="img/b", default='imagedefault.jpg') postimg = models.ForeignKey('Post', on_delete=models.SET_NULL, null=True) class Post(models.Model): ... category = models.ForeignKey('PortfolioCategory', on_delete=models.SET_NULL, blank=True, null=True) class PortfolioCategory(models.Model): category_name = models.CharField(max_length=100, unique=True) urls.py: from django.conf.urls.static import static ... urlpatterns = [...]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) html: {% for category in categories %} {% for post in category.post_set.all %} {% for img in post.blogimage_set.all %} <img src="{{ img.b_img.url }}" alt=""> {% endfor %} {% endfor %} {% endfor %} This code returns ValueError: The 'b_img' attribute has no file associated with it. I'm losing my marbles trying to make this work. Thanks in advance for anyone who can help !