Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get id of foreign key in django modelform
I want to show the foreign key of the user field in a dropdown select option in the form, and get the id of the selected username. Currently, when saving the form in the code below, the 'None' is saved in the user_id field. Any solution? It was successful until it appeared in dropdown format, and the current login account username was set to default, and the disabled attribute was added so that it could not be edited. [models.py] class Leave(models.Model): title = models.CharField(max_length=50, blank=True, null=True) from_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) memo = models.TextField(blank=True, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) is_deleted = models.BooleanField(default=False) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) [forms.py] class LeaveForm(ModelForm): class Meta: model = Leave # datetime-local is a HTML5 input type, format to make date time show on fields widgets = {'user': Select(attrs={"disabled": 'disabled'})} fields = ['title', 'from_date', 'end_date', 'memo', 'user'] def __init__(self, request, *args, **kwargs): super(LeaveForm, self).__init__(*args, **kwargs) # input_formats to parse HTML5 datetime-local input to datetime field self.fields['from_date'].input_formats = ('%Y-%m-%d',) self.fields['end_date'].input_formats = ('%Y-%m-%d',) self.fields['user'].empty_label = request.user.username [views.py] def leave(request, leave_id=None): instance = Leave() if leave_id: instance = get_object_or_404(Leave, pk=leave_id) else: instance = Leave() form = LeaveForm(request, request.POST or None, instance=instance) if … -
Queryset for a sql query
See Filtering unique values for the problem description, sample data and postgres query. I'd like to convert the SQL to a queryset. I feel like I'm close but not quite. SELECT Column_A, Column_B, Column_C, 0 as RN FROM TABLE WHERE COLUMN_C is null and Column_B in (UserA, UserB, UserC) UNION ALL SELECT Column_A, Column_B, Column_C, RN FROM ( SELECT A.*, ROW_NUMBER() over (partition by A.column_C Order by case A.column_B when 'UserA' then 0 else 1 end, U.Time_Created) rn FROM Table A INNER JOIN user U on U.Column_B = A.Column_B WHERE A.Column_C is not null and ColumnB in (userA, userB, UserC)) B WHERE RN = 1 This is what I have so far: qs1 = Table.objects.filter(Column_C__isnull=True).annotate(rn=Value(0)) qs2 = Table.objects.annotate(rn=Window( expression=RowNumber(), partition_by=[Column_C], order_by=[Case(When(Column_B=UserA, then=0), default=1), 'Table_for_Column_B__time_created'] )).filter(Column_C__isnull=False, rn=1) return qs2.union(qs1) This doesn't quite work. django.db.utils.NotSupportedError: Window is disallowed in the filter clause. Next, I tried pulling the intermediate result in a subquery, to allow for filtering in the outer query, since I only really need rows with row number = 1. qs1 = Table.objects.filter(Column_C__isnull=True).annotate(rn=Value(0)) qs2 = Table.objects.annotate(rn=Window( expression=RowNumber(), partition_by=[Column_C], order_by=[Case(When(Column_B=UserA, then=0), default=1), 'Table_for_Column_B__time_created'] )).filter(pk=OuterRef('pk')) qs3 = Table.objects.annotate(rn=Subquery(qs2.values('rn'))).filter(Column_C__isnull=False, rn=1) return qs3.union(q1) No exceptions this time, but this doesn't work. Every row in the … -
django model gives error on datetime field
Hi guys I have a model with a datetime field, I tried creating an entry like this Order.objects.create( ... arrival = datetime(year=t['year'],month=t['month'],day=t['day'],hour=t['hour'],tzinfo=timezone.utc) } this is the field in the model arrival = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) When I try to save the object I get this error TypeError: expected string or bytes-like object -
TypeError /admin/ cannot mix str and non-str arguments
Everything goes will till i logout from admin page When i want to open admin page, its show me the error that's in the title I want to know how to open admin page normally without errors -
Django DurationField for only hours and minutes?
I am working with a ModelForm where I have a field that is stored in the database as a DurationField Now on user input, when a user enters 1:30 I would like this to register as 1 hour and 30 minutes, but the DurationField stores this in the database as 00:01:30 which is 1 minute and 30 seconds. When I go into my django shell, I see the output of the field as datetime.timedelta(seconds=90) I am trying to figure out a way to convert this to either datetime.timedelta(minutes=90) or even parse 00 on the end of input just to store this correctly in the DB I'm not sure why the timedelta defaults to seconds ? I've never worked with a DurationField field before, and appreciate any guidance -
How to annotate strings in django objects
I want to concatinate first name + last name but i'm getting 0 as a value of full name What I'm trying to do is this Customer.objects.annotate(full_name=F('first_name') + F('last_name')).filter(full_name='Filan Fisteku') -
django get_attname() to return a list with value if attribute is required
I have this code: [header.get_attname() for header in Model._meta.fields] which returns all the attribute names of the Model I selected. I want to see if the attribute is required, for example, if the attribute name is a foreign key, the return should be [('a_foreign_key', 'required'),...] right now its only returning ['a_foreign_key',...]. Is there a way I can do this? -
How to properly drop a unique constraint on Django when migrating a OneToOneField to a ForeignKey?
I need to transform a OneToOneField in a ForeignKey, and obviously remove the unique constraint but makemigrations command can't identify that operation and it's not adding the RemoveConstraint operation. How can I create the proper RemoveConstraint to the migrations file and make it safer to apply? I thought about getting the name of the constraint and hard coding it but I was thinking if there was a smarter way of doing this. This is the generated migration file class Migration(migrations.Migration): dependencies = [ ('acc', '0018_auto_20211113_2246'), ] operations = [ migrations.AlterField( model_name='account', name='owner', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, related_name='accounts', to='acc.owner'), ), migrations.AlterField( model_name='account', name='internal_account', field=models.BooleanField(blank=True, default=True, editable=False, null=True), ), migrations.AlterField( model_name='historicalaccount', name='internal_account', field=models.BooleanField(blank=True, default=True, editable=False, null=True), ), ] -
Django models default manager not behaving as expected
I am using Django 3.2 I have a model defined like this: CHOICE_TYPES = ( (0, 'pending'), (1, 'approved'), (2, 'rejected') ) class ApprovedFooManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status=1) class PendingFooManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status=0) class RejectedContentManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status=2) class Foo(models.Model): status = models.PostiveSmallInteger(choices=CHOICE_TYPES, default=0) #objects = models.Manager() objects = ApprovedFooManager() objects_pending = PendingFooManager() objects_rejected = RejectedFooManager() class Meta: abstract = True class FooBar(Foo): name = models.CharField(max_length=100) # pass In my shell I type: from myapp.models import FooBar FooBar.objects.create(name='Fred') # Should be created with status of pending FooBar.objects.all() # Expect empty QuerySet, but I get QuerySet with 1 item (the object created in line above Why is the objects attribute on FooBar not returning 'records' filtered with status=1? How do I fix this? -
Django admin add list_filter based on custom field
I am trying to create a custom list_filter in django admin. The custom field works just fine in the admin but when i add it to the list_filter i get ERRORS: <class 'whosnext.admin.WhosNextTrackingAdmin'>: (admin.E116) The value of 'list_filter[1]' refers to 'get_is_different', which does not refer to a Field. I created a custom SimpleListFilter to handle this but it also says ERRORS: <class 'whosnext.admin.WhosNextTrackingAdmin'>: (admin.E116) The value of 'list_filter[1]' refers to 'MatchedNamesFilter', which does not refer to a Field. I am wondering how I can create a list_filter for this custom field. Code is as follows (all in admin.py). Django 3.2.3 class MatchedNamesFilter(admin.SimpleListFilter): title = "Matched Status" parameter_name = "get_is_different" def lookups(self, request, model_admin): return [( ("matched", "Matched"), ("not_matched", "Not Matched"), ("na", "N/A") )] def queryset(self, request, queryest): if self.value() == "matched": return queryest.distinct().filter(get_is_different="Matched") if self.value() == "not_matched": return queryest.distinct().filter(get_is_different="Does Not Match") if self.value() == "na" or self.value == None: return queryest.distinct().filter(get_is_different__isnull=True) @admin.register(WhosNextTracking) class WhosNextTrackingAdmin(admin.ModelAdmin): list_display = ['tsa', 'date_time_clicked', 'get_case_number', 'get_triage_failed', 'who_was_picked', 'who_case_was_actually_assigned_to', 'get_is_different'] list_filter = [('date_time_clicked', DateFieldListFilter), 'get_is_different'] search_fields = ['tsa', 'who_was_picked', 'get_case_number', 'who_case_was_actually_assigned_to'] def get_case_number(self, obj): case_number = eval(obj.case_details)['case_number'] return case_number get_case_number.admin_order_field = 'case_number' get_case_number.short_description = 'Case Number' def get_triage_failed(self, obj): triage_failed = eval(obj.triage_result)['Error'] if triage_failed: return format_html(triage_failed) else: … -
NoReverseMatch at /kwalificaties/ Reverse for 'updatekwalificatie' with arguments '('',)' not found. 1 pattern(s) tried:
views.py def updateKwalificatie (request, pk): kwalificatie = Kwalificaties.objects.get(id=pk) form = kwalificatie_beheer(instance=kwalificatie) context = {'form': form} return render(request,'accounts/kwalificatiebeheer.html', context) urls.py path('updateKwalificatie/<str:pk>/', views.updateKwalificatie, name='updatekwalificatie'), kwalificaties.html <td><a class="btn btn-sm btn-outline-secondary" href="{% url 'updatekwalificatie' kwalificatie.id %}">Update</a></td> hey i got a error but dont know what todo. can some one plz help me thx alot.. -
Django template count of second order relationship
I am using a relational database via Django Models and have the following classes: class EventSite(models.Model): name = models.CharField(....etc.) class Artist(models.Model): jobsite = models.ForeignKey(JobSite, related_name="jobsite", null=True....etc.) is_british = models.BooleanField(default=False) class Concert(models.Model): event = models.ForeignKey(EventSite, related_name="event_concert", null=True....etc.) artists = models.ManyToManyField(Artist, related_name="artist_conerts", null=True....etc.) So each Concert is related to an Event Site and can have several Artists. Inside of my html template, I need to get a total count of the count of the number of Artists on each Concert related to an Event. (See the pic) So the html I tried looks something like: {% for site in event_sites %} {{site.event_concert.all.artists.count}}, {% endfor %} So for my scenario, I'm hoping that will display to the user: 12,3,0 but it's just returning an empty string right now. I cannot seem to find a solution, which I suspect is because I don't have the right terminology to describe what I'm trying to get. In some scenarios, I'll also have to count only the artists that are british. Any help would be greatly appreciated! -
Multiple instances of views.py in django with gunicorn threads
I am running a Django, Gunicorn and Nginx web application. The Gunicorn wsgi was configured with three worker threads. In one of my apps, I have a view.py file that has a global variable, which represents the states of some of my pins on my raspberry pi. If multiple web requests come in, and gunicorn uses different threads, will there be different versions of that global variable in my view.py file? from gpiozero import LED led = LED(17) #led for the gpio pin 17 led.off() def home(request): led.on() ... -
Is there a way to dynamically specify a queryset for nested relationship (nested serializer class) in django rest framework
Suppose we have two models: class Chapter(models.Model): title = models.CharField(max_length=128) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Post(models.Model): title = models.CharField(max_length=128) body = models.TextField() is_archived = models.BooleanField(default=False) chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE) And default ModelViewSet viewset for Chapter model: class ChapterViewSet(viewsets.ModelViewSet): queryset = Chapter.objects.all() serializer_class = ChapterSerializer The key thing is that ChapterSerializer performs nested serialization using PostSerializer to provide a post_set key in the response. class PostSerializer(serializers.HyperlinkedModelSerializer): detail_url = HyperlinkedIdentityField(view_name='post-detail', read_only=True) class Meta: fields = ['id', 'title', 'is_archived', 'detail_url'] model = Post class ChapterSerializer(serializers.ModelSerializer): post_set = PostSerializer(read_only=True, many=True) class Meta: model = Chapter fields = ['id', 'title', 'owner', 'post_set'] The question is how I can dynamically specify a queryset for this nested PostSerializer. For example, when user makes GET request I only want to include the posts that are not archived (is_archived field is set to False) if user, who has done a request, is not an owner of a Chapter (request.user != current_chapter.owner). Is there any way to achive it? -
two ajax submit form makes crush - Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
I'm trying to submit my forms via ajax request , but now it makes crush and raise this error since i created my second ajax submition form : Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') here is my first and second ajax submition form #first const create_city_form = document.getElementById('create-city') create_city_form.addEventListener("submit",submitCityHandler); function submitCityHandler(e) { e.preventDefault(); $.ajax({ type: 'POST', url: '/forms/cities', data : $('#create-city').serialize(), dataType: 'json', success: successCityFunction, error:errorCityFunction, }); } function successCityFunction(data,xhr) { if (data.success==true) { create_city_form.reset(); alertify.success('added') } } function errorCityFunction(data,xhr){ for(var key in data.responseJSON['error_msg']){ if(key == 'city'){ document.getElementById('city_name_error').removeAttribute('hidden') document.getElementById('city_name_error').innerHTML = data.responseJSON['error_msg'][key][0] } } } #second const create_com_form = document.getElementById('create-com') create_com_form.addEventListener("submit",submitCusComHandler); function submitCusComHandler(e) { e.preventDefault(); $.ajax({ type: 'POST', url: '/forms/companies', data : $('#create-com').serialize(), dataType: 'json', success: successComFunction, error:errorComFunction, }); } function successComFunction(data,xhr) { if (data.success==true) { create_com_form.reset(); alertify.success('added') } } function errorComFunction(data,xhr){ for(var key in data.responseJSON['error_msg']){ if(key == 'name'){ document.getElementById('com_name_error').removeAttribute('hidden') document.getElementById('com_name_error').innerHTML = data.responseJSON['error_msg'][key][0] } } } first form <form action="" method="POST" id="create-city">{% csrf_token %} <div class="row"> <div class="col-md-6"> <div class="form-group"> <label>city name</label> {{form.city}} </div> <p class="text-danger text-center" hidden id="city_name_error"></p> </div> </div> <button type="submit" class="btn btn-success btn-lg">save</button> </form> second form <form action="" method="POST" id="create-com">{% csrf_token %} <div class="row"> <div class="col-md-6"> <div class="form-group"> <i class="fas fa-user-tag"></i> <label>company name</label> {{ form.name … -
How to get ManyToMany Field values in with selecte_related
I'm new to django. I'm using a ManyToMany field in my Profile model with Membership Model. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) picture = models.ImageField(blank=True) membership = models.ManyToManyField(MemberShip, null=True) What I want to do is I want to get all the users who has specific membership(from membership model) For example I want the list of all the users who has the Red Membership. I researched and found out that select_related() or prefetch_related can help in some way. but I can't understand how can I use these methods to get what I want. -
Adding markers google maps using sql db in django
How can I add multiple markers to my Google map using data from database? My js code: function initMap() { const myLatLng = { lat: -25.363, lng: 131.044 }; const map = new google.maps.Map(document.getElementById("map"), { zoom: 4, center: myLatLng, }); new google.maps.Marker({ position: myLatLng, map, title: "Hello World!", }); } // Adds a marker to the map and push to the array. function addMarker(position) { marker_f = Markers.objects.all() const marker = new google.maps.Marker({ Markers from models, map, }); markers.push(marker); } My models.py code: from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. class Markers(models.Model): area = models.CharField(max_length=100) latitude = models.FloatField( validators=[MinValueValidator(-90), MaxValueValidator(90)], ) longitude = models.FloatField( validators=[MinValueValidator(-180), MaxValueValidator(180)], ) Tutorials used for generating this code: https://developers.google.com/maps/documentation/javascript/examples/marker-remove https://developers.google.com/maps/documentation/javascript/examples/marker-simple I don't want to hardcode my coords in js like in the example below, I would like to add them via my admin page in django with models.py variable to show markers on my map in html https://developers.google.com/maps/documentation/javascript/examples/icon-complex -
Plotly - Plot not rendering in Django
I have created 2 functions to generate plots in my projects, essentially the view call these functions to create the plots, however, the problem I have is that one of the plots is not shown, but the code is exactly the same as the other plot (the exception is the column names) views.py @login_required def dashboard(request): c = Profile.objects.get(user=request.user) leads = Leads.objects.filter(agent_id = c) deals = Deal.objects.filter(agent_id=c) #Data for plot qs_leads = Leads.objects.filter( agent_id=c, status='Open') qs_deals = Deal.objects.filter( agent_id=c) df = read_frame(qs_leads) #Creates Plots plot_div_leads = plot_leads_data(qs_leads) plot_div_deals = plot_deals_data(qs_deals) if len(leads) == 0: context = {'leads': len(leads), 'deals': len(deals), } else: if len(deals) == 0: context = {'leads':leads, 'deals': len(deals), 'pot_div_leads':plot_div_leads} else: context = {'leads':leads, 'deals':deals, 'pot_div_leads':plot_div_leads, 'plot_div_deals':plot_div_deals} return render(request, 'account/dashboard.html', context) Dashboard.html {% extends "base.html" %} {% load static %} {% block title %}Dashboard{% endblock %} <meta name="viewport" content="width=device-width, initial-scale=1"> {% block content %} <h1>Dashboard</h1> <p>Welcome to your dashboard.</p> <h1> Add Data </h1> <a href="{% url 'add_company' %}" class="buttons">Add Company</a> <a href="{% url 'add_client' %}" class="buttons">Add Client</a> <a href="{% url 'add_lead' %}" class="buttons">Add Lead</a> <a href="{% url 'add_call' %}" class="buttons">Add Call Report</a> <p></p> <h1>Your Data </h1> <p>Click on the buttons inside the tabbed menu:</p> <div class="tab"> <button class="tablinks" … -
how Convert .ajax() to fetch()
I'm trying to use JavaScript's fetch library to make a form submission to my Django application. However no matter what I do it still complains about CSRF validation. my code fetch don't work ajax function myidLikeCom(params) { $.ajax({ type: 'POST', url: '{% url "boards:likeComment" %}', data: { postid: params, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function (json) { document.querySelector(`#myidLikeCom${params}`).innerText = "json['result']"; }, error: function (xhr, errmsg, err) { } }); } fetch function myidLikeCom(params) { let data= { postid: params, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), } fetch('{% url "boards:likeComment" %}', { method: 'POST', body: data, }) } -
form tag not working with django and heroku
When I deployed my website with heroku it works fine but when I go to the contact page it give me error (500) but when I put it to Debug = True its says Exception Type: TemplateDoesNotExist and Exception Value: games\contact_page.html here is my views.py file its seems fine: error = False def contact_page(request): global error try: if request.method == 'POST': message_name = request.POST['message-name'] message_email = request.POST['message-email'] message = request.POST['message'] if '@' and '.com' not in message_email: error = True raise Exception("Enter True email") elif '@' not in message_email or '.com' not in message_email: error = True raise Exception("Enter True email") else: error = False with open(os.path.join("staticfiles/txtfiles/messages.txt"), "a") as file: file.writelines(f'{message_name} :: {message_email} :: {message} :: {time.ctime()}\n\n') messages.success(request, ('Your email is sent! We will reply as soon as possilbe')) return redirect('home') except: messages.success(request, ('Oops there is an error!! Enter the information correctly')) return render(request, 'games\contact_page.html', { 'error': error }) else: return render(request, 'games\contact_page.html', { }) contact_page.html file: <!DOCTYPE html> {% extends 'games/base.html' %} {% block content %} <form method="POST"> {% csrf_token %} <div class="row"> <div class="col-lg-6" style="margin: 50px 0px 25px 0px"> <input type="text" name="message-name" class="form-control mb-30" placeholder="Your name"/> </div> <div class="col-lg-6" style="margin: 50px 0px 25px 0px"> <input type="text" name="message-email" class="form-control … -
Count number of Tests
I wanted to know that is there any way I can have a test for number of tests that got run in my Django manage.py test command? My Project CI runs my test but when I comment out some tests for local testing and forget to undo them before commiting, my CI will not run all my test so more bugs may happen in production -
How to create new model using pk
I am trying to make user join the room ( so creating a new RoomMember) but this is the error that I get : "Cannot assign "room_name": "RoomMember.room" must be a "Room" instance." (thanks in advance) * Views.py: def join_room(request, pk): RoomMember.objects.create(room=pk, user=request.user).save() return redirect('room_detail') Urls.py: path("join/<int:pk>/room/", views.join_room, name="join_room"), Models.py: class Room(models.Model): name = models.CharField(max_length=100) about = models.TextField(max_length=500, null=True, blank=True) creator = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='room_creator') members = models.ManyToManyField(User, through="RoomMember") class RoomMember(models.Model): approved = models.BooleanField(default=False, blank=False) room = models.ForeignKey(Room, related_name='memberships', on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='user_groups', on_delete=models.CASCADE) class Messages(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) text = models.CharField(max_length=10000, blank=False, null=False) date = models.DateTimeField(default=datetime.now) room = models.ForeignKey(Room, null=True, blank=False, on_delete=models.CASCADE) Html: <a class="btn btn-dark" href="{% url 'join_room' pk=room.pk %}">Join</a>* -
Products/Items are not being added in the Cart in Django. How do I fix it?
I am new to Django and working on an ecommerce app. I have defined the products and users things. But I am stuck at the cart. I have basically two apps in my project viz. index and cart. I have defined TwoPieceSuits() as a products' model in index.models.py and I have defined Cart() & CartManager() (just to manage cart properly if an anonymous user logs in the web, after adding the products in cart) in cart.models.py. I have defined two_piece_suits, an attribute in cart.models.Cart as a ManyToManyField referenced to index.models.TwoPieceSuit. Now it basically works all the way, until I want to add up the price(s) of TwoPieceSuit() instances and save the result in total of Cart(), it does not add up the prices. Despite of Cart() instance having many (because of ManyToManyField) instances of TwoPieceSuit() containing the values in price attribute, it does not add up the prices when I call them to be added in my cart.models.py. My index.models.py is: import os from django.db import models from django.utils.text import slugify def get_file_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.splitext(base_name) return name, ext def upload_image_path(instance, filepath): name, ext = get_file_ext(filepath) filename = instance.fabric + '-' + instance.lining + '-' + … -
Finding outliers with django
So i trying to detect some price outliers in a query, but didn't fully understand. How it cant be done. So how i trying to do this: I got one model class History(models.Model): id = models.CharField(...) price = models.FloatField(...) retailer = models.CharField(...) in view i got query like so price_query = History.objects \ .filter(id__in=product) \ .filter(price_query) \ .annotate(dt=Trunc('StartDate', frequency)) \ .values('dt') \ .annotate(F('Price')\ .order_by('dt') # so i can access price outliers = np.array(price_query) filtered_price = outliers[(outliers>np.quantile(price_query, 0.1)) & (outliers<np.quantile(price_query, 0.99))] but in this case a can associate any filtered_price with any id in History model, any suggestions how i can do right? Sorry, haven't slept for a long time, nothing comes to my mind -
serving react and django with nginx without having to delete and rebuild docker
I am trying to serve Django and react via Nginx separately. Part of my Nginx folder is: upstream react_frontend { server react:3000; } location /static/ { alias /usr/src/app/react_files/static/; } location / { proxy_pass http://react_frontend; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } Part of my docker-compose is react: container_name: frontend build: context: ./frontend dockerfile: Dockerfile args: - API_SERVER=http://127.0.0.1 volumes: - react_static_volume:/usr/src/app/build/static expose: - 3000 env_file: - ./frontend/react_app/.env command: serve -s build -l 3000 depends_on: - web On the frontend the error I get is localhost/:1 GET http://localhost/static/css/main.e7ed58af.chunk.css net::ERR_ABORTED 404 (Not Found) localhost/:1 GET http://localhost/static/js/2.23f5dba1.chunk.js 404 (Not Found) localhost/:1 GET http://localhost/static/js/main.11478e07.chunk.js net::ERR_ABORTED 404 (Not Found) localhost/:1 GET http://localhost/static/js/2.23f5dba1.chunk.js net::ERR_ABORTED 404 (Not Found) localhost/:1 GET http://localhost/static/js/main.11478e07.chunk.js net::ERR_ABORTED 404 (Not Found) However when I delete the docker container + volume + images, then those errors go away. Is there a faster way than deleting all the containers and building it again?