Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can I change a button value to remove from cart if product is already in session
I been trying to changing the button add to cart to remove from cart if it happens that products is in session. This is the template: products.html ... <div id="products-list" class="grid grid-cols-4 gap-4"> {% for product in products %} <div class="card"> <div class="image-container"> <img class="img" src="{% static product.image %}" alt="Card image cap"> </div> <div class="container"> <h5 class="card-title">{{ product.product_name }}</h5> <p class="card-text">{{ product.description }}</p> <p class="card-text">Price - &#8358;{{ product.price }}</p> <form action="{% url "add-cart" %}" method="POST"> {% csrf_token %} <input type="hidden" name="product_id" value= "{{ product.id }}"> from here is where I have problems. I am trying to put an if condition that changes the value of the button e.g if product is in session it will show the remove from cart button, else it will show the add to cart button. {% comment %} {% if {{ request.session.stored_item }} %} {% endif %} {% endcomment %} {% comment %} document.getElementById("btn-green").addEventListener("click", function() { document.getElementById("btn-green").innerText = "remove from cart" }) {% endcomment %} </form> </div> </div> {% endfor %} # views.py # def products(request): # stored_items = request.session.get("stored_items") # product_item = Product.objects.filter(id__in=stored_items) products = Product.objects.all() if 'query' in request.GET: query = request.GET['query'] multiple_q = Q(Q(product_name__icontains=query) | Q(description__icontains=query)) products = Product.objects.filter(multiple_q) # products = … -
InMemoryUploadedFile Django File Read in Bytes - str vs utf8
I'm looking to read the binary content of a Django type InMemoryUploadedFile. The file type/encoding is a variable, so I don't want to assume UTF8, I simply want to read the binary content, then I want to encode with UTF8. Here's what I've tried: str(file.read()).replace('\n', '\r\n') This looks to work, except the string still has the binary 'b' character. To fix this, I tried: file.read().decode('utf8').replace('\n', '\r\n') This works well for reading .txt files. Any other file types fail to read properly, understandably. How can I read the binary content of type "InMemoryUploadedFile" without specifying an encoding? -
{%static %} the page displays the line itself {%load static %} instead of loading the desired file
I wanted to connect a css file to this html file, I wanted to add it via {%load struct%} `{% load static %} <!DOCTYPE html> <html lang="ru"> <head> <title>Brewtopia Cafe form</title> <meta charset="UTF-8"> <link rel="stylesheet" href="{% static 'css/style_contact.css' %}"> </head> <body> <header>` this is urls.py in the app `from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.Brewtopia_view, name='brewtopia'), path('Contact/', views.Contact_view, name='contact') ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ` these are views.py in the app `from django.shortcuts import render def Brewtopia_view(request): return render(request, 'Brewtopia.html') def Contact_view(request): return render(request, 'Contact.html') ` settings.py settings in static `STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ]` the css file is located in the folder C:\Projects\brew\brewtopia\users\static\users\css I added struct and wanted to upload a css file, but the error is in the screenshot enter image description here but even if you delete {%loadstruct%} it won't work -
When the checkbox is checked then immediately get the result in Django
This is my View.py def weight(request): selected_values = request.GET.get('selected_values[]') p = Product.objects.filter(load = selected_values) context = {'prod_fil_by_weight':p} return render(request, 'product-filter.html', context) This is my Template I just want to render the data on same html template. `<div class="checkbox"> {% for w in weight %} {{ w.name }} {% for n in prod_fil_by_weight %} <h5>{{ n.name }}</h5> <h5>{{ n.price }}</h5> <h5>{{ n.old_price }}</h5> <h5>{{ n.image.url }}</h5> <h5>{% endfor %} {% endfor %}` This is my AJAX which I was Created. <script type="text/javascript"> $(document).ready(function() { $('.myCheckbox').change(function() { var selectedValues = []; $('.myCheckbox:checked').each(function() { selectedValues.push($(this).val()); }); $.ajax({ url: "/weight/", data: { 'selected_values[]': selectedValues }, success: function(response) { $('#data-container').html(response.result); } }); }); }); </script> I just want to get immediate result and render the data in the same template. when the checkbox is checked no matter only one checkbox is checked or multiple checkboxes is checked I just want the data get and render to the same template (Most of the website use this feature like when you check the checkbox then immediately you get the result without redirecting any other page. the feature name is Real Time Feedback if I am right). I research a lot but I fail my last hope is … -
how i can fix an smtp error in Django im using gmail
i have this error this morning after a year using it. Anyone knows how i can fix this?Error here I was looking for a solution but i cant find anything -
Fast CGI Handler not installed in Windows IIS
I am trying to run a Django app with IIS server. Here are my settings: Windows Server 2019, IIS 10.\ I am following this tutorial. I am setting up my server and added CGI as shown in the image. enter image description here But, when i deploy the app, i get an error saying that the "FastCgiModule" is not in the list. enter image description here I looked in HandlerMappings to find that the FastCgiModule was indeed not in the list of modules that IIS considers. Help and understanding about this is much appreciated. Things tried Added wfastcgi.exe path to the system path. Expectation: In case that was the reason FastCGI wasn't being built, this would fix it. Result: No change. Installed ASP.net and .NET frameworks. Expectations: If these are dependencies for the FastCGI framework, it might help install it. Result: No change. -
Django Rest Framework - Data is Not Refreshed from Table When Inserted directly from Oracle
When I am manually inserting some records from Oracle directly, it is not refreshed from my Django Rest API application. Only the data that is inserted from POST request from the application is shown in the GET requests. I can see all the rows in the oracle table but it is not showing up in django application. I have created this table from Django itself by migrating all the changes. How can I refresh the queryset to ensure it fetches all the table records no matter where the data was inserted from? Below is my code: Model: class Genre(models.Model): genre_id = models.AutoField(primary_key=True) genre_name = models.CharField(max_length=60) def __str__(self): return self.genre_name class Meta: db_table = "GENRE" Serializer: class GenreSerializer(serializers.ModelSerializer): class Meta: model = Genre fields = "__all__" ViewSet: class GenreViewSet(viewsets.ModelViewSet): queryset = Genre.objects.all() serializer_class = GenreSerializer -
Slow "waiting for server response" in django-plotly-dash
I have a django project that includes many dash apps through django-plotly-dash. I noticed a strange increase in callback update latency recently and cannot identify the cause. I put together a simple dash app with three sequential callbacks below as an example. When I run the app locally in my main project, each callback takes about 500 ms to run. When I run the same app in a brand new django project, each callback only takes 50 ms to run. Looking at the performance monitor in my browser, the difference appears to be in the dash_renderer js "waiting for server response." Is there a way to identify what is happening for the server to respond quickly in one django project versus another? views.py: from django.shortcuts import render from . import lightning def thunder(request): return render(request, 'dpd/thunder.html') lightning.py (the dash app): from dash import dcc, html from dash.dependencies import Input, Output from django_plotly_dash import DjangoDash app = DjangoDash('lightning', external_stylesheets=['https://codepen.io/chriddyp/pen/bWLwgP.css']) app.layout = html.Div([ dcc.Input( id='x0', type='number', value=0 ), html.Table([ html.Tr([html.Td(['x+1']), html.Td(id='x1')]), html.Tr([html.Td(['x+2']), html.Td(id='x2')]), html.Tr([html.Td(['x+3']), html.Td(id='x3')]), ]), ]) @app.callback( Output('x1', 'children'), Input('x0', 'value') ) def callback1(x): return x+1 @app.callback( Output('x2', 'children'), Input('x1', 'children') ) def callback2(x): return x+1 @app.callback( Output('x3', 'children'), Input('x2', 'children') … -
Hola tengo un error con el admin de django en jazzmin [closed]
Cuando entro a una aplicacion en la tabla me aparece con este bug y no se como solucionarlo enter image description here necesito ayuda lo antes posible -
About the URL.createObjectURL
I am a beginner in django with python, there is a problem i confronting now is that I have a image URL e.g. "http://127.0.0.1:8000/media/images/user_1/XXXX.jpg" and I am trying to use URL.createObjectURL to do a preview, but it is not work. There is the error message: companymanage:1278 Uncaught TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed. at Object.success (companymanage:1278:73) at c (datatables.min.js:14:28327) at Object.fireWith [as resolveWith] (datatables.min.js:14:29072) at l (datatables.min.js:14:79901) at XMLHttpRequest.<anonymous> (datatables.min.js:14:82355) I already try the image URL in chrome browser and arrived the image successfully. So why i can not use the path in URL.createObjectURL? Is the createObjectURL only accept File, Blob only and i enter the path so case this problem?? Is any solution suggest ??? -
MultiValueDictKeyError at /register/ request method post
MultiValueDictKeyError at /register/ 'name' Request Method: POST Request URL: http://127.0.0.1:8000/register/ Django Version: 4.1.7 Exception Type: MultiValueDictKeyError Exception Value: 'name' Exception Location: C:\Users\vaibh\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\datastructures.py, line 86, in getitem Raised during: main.views.register Python Executable: C:\Users\vaibh\AppData\Local\Programs\Python\Python311\python.exe Python Version: 3.11.2 Python Path: ['V:\MEMEPROJECT\meme', 'C:\Users\vaibh\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\vaibh\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\vaibh\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\vaibh\AppData\Local\Programs\Python\Python311', 'C:\Users\vaibh\AppData\Local\Programs\Python\Python311\Lib\site-packages'] Server time: Fri, 24 Feb 2023 17:10:06 +0000 here i M TRYING TO GET USER DETAILS but this error MultiValueDictKeyError at /register/ is coming -
How do I stop logs before Django sets up logging
I have a call to Initialization() in wsgi.py in my django app that gets made before django calls setup(). Within that call to Initialization(), there is another call made to IdentityService() which is an imported library. This results in the logs from IdentityService() going to STDOUT when my django app initializes and I want to suppress these logs. The django app uses the normal LOGGING setting, configured by dictConfig(). Am I right in assuming that because the call on the Initialisation class gets made before configure_logging is called by setup(), the LOGGING dictionary can't control the logs of IdentityService() going to STDOUT? Any suggestions for how I can stop these logs being sent to STDOUT? -
Pytest not recognizing tests in some installed apps in django
I have an issue with pytest in which it executes tests in some installed apps but ignores some even after specifically trying to run tests on that said app it still won't recognize the app. The app that's not recognize currently is named file_upload when ever i run pytest with pytest it detects all tests in other apps (collected 52 items) excludes file_upload , when i also run pytest -k file_upload still says it collected 52 items and deselected 52 items, i named the test file with test_endpoints.py and in my pytest.ini i have the following configurations: [pytest] addopts = --ds=config.settings.test --reuse-db python_files = tests.py test_*.py i added file_storage to my installed apps and works perfectly when running migrations and the rest so it's probably a pytest issue but i can't figure exactly what. -
Django template with if - no clue what's wrong
I'm new to Django and followed the Django tutorial to understand and adapt to my needs. I am trying the following template: {% extends "base_generic.html" %} {% block content %} {% if user.is_authenticated %} <h1>List of my Projects</h1> {% if myproject_list %} <ul> {% for projectuser in myproject_list %} -{{ user.username }}-<br> -{{ projectuser.User }}-<br><br> {% if projectuser.User == user.username %} <li> x {{ projectuser.Project }} </li> {% endif %} {% endfor %} </ul> {% else %} <p>There are no projects to list.</p> {% endif %} {% else %} <li><a href="{% url 'login' %}?next={{ request.path }}">Login</a></li> {% endif %} {% endblock %} some code in there like -{{ user.username }}-<br> -{{ projectuser.User }}-<br><br> are just for debugging. with those two lines I get the usernames which I would like to apply here: {% if projectuser.User == user.username %} However the if is always not true!! What am I missing!?!?!?!? PS: I tried to find a solution with some posts here. Couldn't solve my problem -
User Login in DJango
Just learning to write Django APIs. I have created two APIs : one for Signup and one for Login. For signup, I have to send "username, password, password2" fields. password2 acts as retype password. For login, I have to send only "username, password" and if username and password both are there in User object, it should return 200 response code. The issue , I am getting is: while login, it says, "password2" is required. Here is the code: serializers.py: from rest_framework import serializers from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password class RegisterSerializer(serializers.ModelSerializer): username = serializers.CharField(required=True) password = serializers.CharField(write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) class Meta: model = User fields = ('username', 'password', 'password2', 'email', 'first_name', 'last_name') def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError({"password": "Password fields didn't match."}) return attrs def validate_username(self, value): if User.objects.filter(username__iexact=value).exists(): raise serializers.ValidationError("A user with this username already exists.") return value def create(self, validated_data): user = User.objects.create( username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user class LoginSerializer(serializers.ModelSerializer): username = serializers.CharField(required=True) password = serializers.CharField(required=True) class Meta: model = User fields = ('username', 'password') def validate_username(self, value): if User.objects.filter(username__iexact=value).exists() and User.objects.filter(password__iexact=value).exists(): return value else: raise serializers.ValidationError("username/password is incorrect.") views.py: from django.shortcuts import render # Create your views … -
Set correct path to environ file django
I have this project structure in Django: ├── .env ├── app │ ├── Dockerfile │ ├── Dockerfile.prod │ ├── entrypoint.prod.sh │ ├── entrypoint.sh │ ├── hello_django │ │ ├── __init__.py │ │ ├── asgi.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── manage.py │ └── requirements.txt Using django-environ how can i set the path to .env file? environ.Env.read_env(os.path.join(BASE_DIR, '.env')) This one doesn't work because its one level higher that project. How can i set the correct path? -
Django multiple annotate
Can anyone help me for my query. Let say i have this model : class Players(models.Model): ... teams (FK), nationality (FK), ... What i want to achieve is to annotate with this result : [nationality, count_of_players_with_nationality, distinct_teams_that_have_player_of_this_nationality] i only achieve the first two with this: Player.objects.values("nationality").annotate(count=Count("id")).order_by('-count') Can i add the distinct_teams_that_have_player_of_this_nationality with a single query? -
Change a field option in the inherited class
For example, I have a code: from django.db import models class AbstractClass(models.Model): name = models.CharField(max_length=150, null=True) class A(AbstractClass): field = models.CharField() class B(AbstractClass): another_field = models.CharField() # and also for exmaple i need to set max_length 155 for the name field here Can I somehow change a field option max_length of a field name in AbstractClass? I searched through some sites, but, unfortunately, didn't find anything. I saw about get_initial() and self.fields, but I don't know how to imply it to the class and I am not sure if it is even suitable for my situation. -
Html content comes on top of navbar
I have a problem my html content comes on top of my navbar even tho I'm including it in my {%block content%} This is my base template <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Homepage</title> <link href="https://cdn.jsdelivr.net/npm/remixicon@2.5.0/fonts/remixicon.css" rel="stylesheet"> <link rel="stylesheet" href="https://unpkg.com/boxicons@latest/css/boxicons.min.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Raleway:wght@800&display=swap" rel="stylesheet"> <link rel="stylesheet" href='{% static "css/styles.css" %}'> </head> <body> {% include 'navbar.html'%} {% block content %} {% endblock %} <script type="text/javascript" src="js/script.js"></script> </body> </html> This is my navbar <div> <header> <a href="#" class="logo"> <i class="ri-home-2-fill"></i><span>LOGO</span></a> <ul class="navbar"> <li><a href="#" class="active">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Services</a></li> <li><a href="#">Contact</a></li> <li><a href="#">Soon</a></li> </ul> <div class="main"> <a href="#" class="user"><i class="ri-nurse-fill"></i>Sign in</a> <a href="#">Register</a> <div class="bx bx-menu" id="menu-icon"></div> </div> </header> </div> And this is a page of my app {% extends 'main.html'%} {% block content %} <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, … -
An unwanted and useless extraline in django crispy-forms
In Django, I have this forms.py : class ProfileForm(ModelForm): class Meta: model = Profile fields = [ 'sex','birth_date','civil_status', 'priv_tel','priv_email', 'priv_adr_l1','priv_adr_l2','priv_adr_zipcode','priv_adr_city','priv_adr_country', 'anamnesis','doctor'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-profileForm' self.helper.form_class = 'blueForms' self.helper.form_method = 'post' # self.helper.form_action = reverse('hr:profile/profile_form') self.helper.layout = Layout( TabHolder(Tab('Généralités', 'sex','birth_date','civil_status'), Tab('Contact', 'priv_tel','priv_email', 'priv_adr_l1','priv_adr_l2','priv_adr_zipcode','priv_adr_city','priv_adr_country'), Tab('Médical','anamnesis','doctor'), ) ) self.helper.add_input(Submit('submitprofile', 'Mettre à jour')) class ChildForm(ModelForm): class Meta: model = Child fields = ['child_first_name', 'child_last_name','child_birth_date'] ChildFormSet = inlineformset_factory(User, Child, form=ChildForm, extra=0, can_delete=True, can_delete_extra=True) class ChildFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-childForm' self.form_method = 'post' self.render_required_fields = True self.template = 'bootstrap/table_inline_formset.html' self.add_input(Submit('submitchild', 'Modifier')) And this views.py : class ProfileFormView(LoginRequiredMixin, TemplateView): model = Profile form_class = ProfileForm template_name = 'profile/profile_form.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user_profile = get_object_or_404(Profile, user=self.request.user) context['user_form'] = ProfileForm(instance=user_profile) context['child_formset'] = ChildFormSet(instance=user_profile.user) context['child_formsethelper'] = ChildFormSetHelper() return context def post(self, request, *args, **kwargs): user_profile = Profile.objects.get(user=request.user) user_form = ProfileForm(request.POST, instance=user_profile) child_formset = ChildFormSet(request.POST, instance=user_profile.user) if user_form.is_valid() and child_formset.is_valid(): return self.form_valid(user_form, child_formset) else: return self.form_invalid(user_form, child_formset) def form_valid(self, user_form, child_formset): with transaction.atomic(): user_profile = user_form.save(commit=False) child_formset.instance = user_profile.user user_profile.save() child_formset.save() success_message = Profile._meta.verbose_name + " modifié avec succès." messages.success(self.request, success_message) return HttpResponseRedirect('/profile/') def form_invalid(self, user_form, child_formset): error_message = "Il y … -
dj_rest_auth (jwt) refresh token is empty when login - django rest framework
im having a trouble with dj_rest_auth jwt package. when i signup for a new account it gives me both access token and refresh token in response, but when i try to login with credentials, all i get is access token, and refresh token is entirely empty! i configured the code as described in the documentation and the the tutorial that im following. Any idea about this problem? please let me know. Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth', 'dj_rest_auth.registration', 'accounts.apps.AccountsConfig', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'accounts.permissions.IsStaffOrReadOnly', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'dj_rest_auth.jwt_auth.JWTCookieAuthentication', ], } SITE_ID = 1 REST_AUTH = { 'USE_JWT': True, 'JWT_AUTH_COOKIE': 'access', 'JWT_AUTH_REFRESH_COOKIE': 'refresh', } Response: { "access_token": "eyJhbGciOiJ.....", "refresh_token": "", "user": { "pk": 2, "username": "test_user_0", "email": "test0@mysite.co", "first_name": "", "last_name": "" } } -
Cannot use POST and PUT request at the same time
I am trying to POST and UPDATE a new user using django forms. I have this function in my views.py beforehand and the POST request is working alright but then I realised I couldn't update: def user_form(request, id=0): if request.method == "GET": if id == 0: form = UserForm() else: user = NewUser.objects.get(pk=id) form = UserForm(instance=user) return render(request, "user_register/user_form.html", {'form':form}) else: form = UserForm(request.POST) if form.is_valid(): form.save() return redirect('/user/list') It'll redirect me to the right page - but won't update when I check. I changed the code to this, and the update request worked fine but the problem now is it errors when I try to create a new user: def user_form(request, id=0): if request.method == "GET": if id == 0: form = UserForm() else: user = NewUser.objects.get(pk=id) form = UserForm(instance=user) return render(request, "user_register/user_form.html", {'form':form}) else: user = NewUser.objects.get(pk=id) form = UserForm(request.POST, instance=user) if form.is_valid(): form.save() return redirect('/user/list') The error from the post request stems from the line after the else: and obviously the instance=user after request.POST, as that's what I've added from the original code -
error in django URLconf, I can't start the local server, an error pops up in the screenshot
enter image description here I have a ready-made html template with css. It seems to have done everything correctly, but it does not work. project location C:\Projects\brew\brewtopia location of the application C:\Projects\brew\brewtopia\users location of the main urls.py C:\Projects\brew\brewtopia\brewtopia\urls.py location urls.py in the app C:\Projects\brew\brewtopia\users\urls.py location of views.py in the app C:\Projects\brew\brewtopia\users\views.py html layout C:\Projects\brew\brewtopia\users\templates\users\Brewtopia. folder static C:\Projects\brew\brewtopia\users\static version django 4.1 python 3.11 I've been sitting with this problem for a day now, I've tried everything, people with experiences help me, I just started learning django here is the code in the urls,py of the main project `from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('"', include('users.urls')), ]` here is the code in urls,py in the application `from django.urls import path from . import views urlpatterns = [ path('Brewtopia', views.Brewtopia_view, name='brewtopia') ]` here is the code in views.py in the app `from django.shortcuts import render def Brewtopia_view(request): return render(request, 'Brewtopia.html')` in the main settings.py I have completed this `STATICFILES_DIRS = [BASE_DIR / "static"]` -
What determines what goes into validated_data
My question is fairly simple but I have not found the answer yet. When you send a bunch of post data to Django Rest Framework endpoint then what determines what goes into validated_data and what fields (more the values) are excluded? I have this model # A Product class Product(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=None, related_name="products") brand = models.ForeignKey(Brand, on_delete=models.CASCADE, default=None, null=True, blank=True, related_name="products") body = models.TextField(max_length=5000, null=True, blank=True) image = models.FileField(upload_to=image_directory_path, default='products/default.png', null=True, blank=True) video = models.FileField( upload_to=video_directory_path, blank=True, null=True ) price = models.DecimalField(max_digits=20, decimal_places=2) length = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) width = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) height = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) weight = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) volume = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) sku = models.CharField(max_length=20, null=True, blank=True) stock = models.DecimalField(max_digits=30, decimal_places=0) # user information user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="products") created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "product" verbose_name_plural = "products" db_table = "products" ordering = ["title"] def __str__(self): return self.title and this serializer to create a product: class CreateProductSerializer(ModelSerializer): class Meta: model = Product fields = '__all__' def create(self, validated_data): breakpoint() validated_data.pop("category") main_cat = self.context['request'].data['category'] sub_cat = self.context['request'].data['subcategory'] category = Category.objects.get(id=sub_cat, parent=main_cat) new_product = Product.objects.create(**validated_data, category=category) … -
Django "Detected change in ..., reloading" Error in Docker
I'm having a problem which I don't understand, and therefore can't resolve. I have a Dockerised Django project, which I created using Cookiecutter Django months ago. Today, my development environment has started displaying the following error on every request: I am not currently having this issue in production. I tried rolling back to commits that worked properly before (1 week old commits, for example), and I'm still getting this error. The reloading is causing connections to the database to close and therefore my project isn't working properly at all. Does anyone know what causes this, and how I might fix it? It feels like an issue with my Docker setup, but that hasn't changed in months, so I don't understand why that would change now. Many Thanks for any help anyone can offer!