Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I annotate a django queryset with more than one values
I have an application that scrapes some eshops every day, and I record the Price of every Item. A simplified version of my models looks like this: class Item(models.Model): name = models.CharField(max_length=512, blank=True) class Price(models.Model): item = models.ForeignKey("Item", on_delete=models.CASCADE) timestamp = models.DateTimeField(blank=True) per_item = models.FloatField(blank=True) And my tables can look like this: # Item id | name ----------- 1i | item-1 2i | item-2 3i | item-3 # Price id | item | timestamp | per_item -------------------------------------- 1p | i1 | 2023-04-10 | 10.0 2p | i2 | 2023-04-10 | 2.0 3p | i3 | 2023-04-10 | 14.5 4p | i1 | 2023-04-11 | 11.0 5p | i3 | 2023-04-11 | 12.5 6p | i2 | 2023-04-12 | 2.0 7p | i3 | 2023-04-12 | 14.5 8p | i1 | 2023-04-13 | 12.0 9p | i2 | 2023-04-13 | 3.5 10p | i3 | 2023-04-13 | 15.0 Note that not all Items exist every day, some of them may be present today, missing tomorrow and back again on the day after, and so on. What I want to do I'm trying to write a query that for a given day it will give me the last 2 Prices for every … -
The user is not added to the group. Django Forms
I have a form to create an employee, and in this form there is a "groups" field. When submitting the form, a user is created but not added to the selected group froms class CreateEmployeeForm(auth_forms.UserCreationForm): class Meta: model = user_model fields = [ 'username', 'password1', 'password2', 'email', 'first_name', 'last_name', 'phone_number', 'gender', 'groups', 'middle_name', ] views My View accepts 3 arguments.(form_class, template, success_url) class DirectorCreateEmployeeView(CreateView): template_name = 'director/create_employee_director.html' form_class = CreateEmployeeForm success_url = reverse_lazy('director_list_employee_view') def user_registered_callback(sender, user, request, **kwargs): group_name = request.POST['group_id'] or None if group_name: try: g = Group.objects.get(name=group_name) except Group.DoewNotExists: g = None if g: g.user_set.add(user) html in html I used a custom crispy form <form action="" method="post"> { % csrf_token % } < div class = "card-body" > < h6 class = "card-title" > Creation empl < /h6> < div class = "row" > < div class = "col-md-6" > < div class = "form-group" > { { form.first_name | as_crispy_field } } < /div> < div class = "form-group" > { { form.last_name | as_crispy_field } } < /div> < div class = "form-group" > { { form.middle_name | as_crispy_field } } < /div> < div class = "form-group" > { { form.password1 | as_crispy_field } } … -
Vercel Django Deployment Error : 500: INTERNAL_SERVER_ERROR. Unable to import module 'backend.settings'
I have created a Django Project which I wanna use as backend for my React project. In the root of the project there are two folders : backend for django and frontends for react. Also I have provided a screenshot of the directory tree of my project: screenshot I added requirements.txt and vercel.json with all required stuff below is the code snippets for both. Also I have added vercel to allowed domains according to the documentation. But when I deploy the app through GitHub in vercel, deployment process finishes but when I visit the website I get 500 INTERNAL_SERVER_ERROR which further says 'FUNCTION_INVOCATION_FAILED' So then I go to vercel and check Runtime Logs and I get to see the following error printed multiple times: [ERROR] Runtime.ImportModuleError: Unable to import module 'vc__handler__python': No module named 'backend.settings' Traceback (most recent call last): So the error is not probably due to missing dependencies in requirements.txt but with the import error of my project files. In this case the settings.py. I don't really understand what's causing the import error since I gave correct paths of wsgi.py in vercel.json requirements.txt asgiref==3.6.0 Django==4.2 djangorestframework==3.14.0 python-dotenv==1.0.0 pytz==2023.3 sqlparse==0.4.3 tzdata==2023.3 vercel.json { "builds": [{ "src": "backend/backend/wsgi.py", "use": "@vercel/python", … -
django admin cannot carryover object from one page to another admin page
I have two models(candidate and panelists) in my Django app, i have a link(for all candidate objects) in candidate admin page, when i click on it, it is redirecting to the panelists admin page, but I'm unable to see from which candidate object the panelists page has redirected. if I'm able to see from which candidate obj(or the candidate id) then I can filter panelists based on the candidate attributes. class Candidate(models.Model): id = models.IntegerField(auto_created=True) name = models.CharField(max_length=255) class panelist(models.Model): id = models.CharField(primary_key=True,max_length=7,unique=True) name = models.CharField(max_length=255) here is the candidate admin class CandidateAdmin(admin.ModelAdmin): list_display = ['id','name''view_panelist'] model = Candidate def view_panelist(self,obj): return format_html('<a href= "/admin/ttt/panelist/" class = "default"> View Panelist </a>') -
User errror django
[[[[enter image description here](https://i.stack.imgur.com/d4uWG.png)](https://i.stack.imgur.com/9lWEh.png)](https://i.stack.imgur.com/M5PPH.png)](https://i.stack.imgur.com/envOh.png)] I am doing a simple user posting clone project in django in user field i am need the current active user but instead i am getting all the user in database -
How can i make a language switch button for my blog?
What py files should I modify? (models/admin ect) I need a button in the home page which would allow to switch language into english/german/spanish I tried running this: rom django import template register = template.Library() @register.filter def new_lang_code(current_lang_code): if current_lang_code == ‘en’: return ‘ja’ else: return ‘en’ @register.filter def new_lang_name(current_lang_code): if current_lang_code == ‘en’: return ‘日本語’ else: return ‘English’ But I don't get where should I put this part of code: % load language_selector %} ⋮ <form action=“{% url ‘set_language’ %}” method=“post” id=“form_{{ LANGUAGE_CODE|new_lang_code }}” > {% csrf_token %} <input name=“next” type=“hidden” value=“{{ redirect_to }}” /> <input name=“language” type=“hidden” value=“{{ LANGUAGE_CODE|new_lang_code }}” /> </form> <button class=“btn btn-sm btn-outline-primary” type=“submit” form=“form_{{ LANGUAGE_CODE|new_lang_code }}” value=“Submit”>{{ LANGUAGE_CODE|new_lang_name }}</button> -
There are several packages installed in my virtual environment but pip list doesn't show anything
I've created a new Django project since almost 1 month. I have several packages installed. As I'm using virtual environment I can find all these packages in this directory F:\newEnironment\Lib\site-packages enter image description here Now when I activate my environment and go on my project pip command doesn't do anything. I want to use pip lists and pip freeze. Both returns nothing. Some of the project abilities won't work if these packages aren't installed. I can successfully run the project on my machine and that's why I'm quite sure this packages are installed. For instance when I write pip list in CMD it shows me that pillow isn't installed globally on my machine. As you see in the picture above it includes in site-packages directory which means I have it installed locally. Not only that, my projects pictures are works correctly because of pillow. -
How to exclude certain items from query ordering but still keep them in the query in Django?
I want to send a list of IDs to my API of items which should always appear at the top of the query disregarding the ordering. For example, if I send ids=3,4 to the API and I have 5 objects in the DB and I order by created_at, I would like to receive them in order: 3 4 1 2 5 or if I order by -created_at then 3 4 5 2 1. I tried to do this # Apply the default ordering first queryset = super().filter_queryset(request, queryset, view) if "ids" in request.query_params: first_ids = request.query_params["ids"].split(",") queryset = queryset.order_by(Case(When(id__in=first_ids, then=0), default=1)) return queryset This works when I order by created_at for example, but fails for -created_at. -
how to change an existing char field to a foreign key in Django
I had this model class Order(models.Model): ... discount_code = models.CharField() but at some point in development we decided to move from text only discount_codes to a Model with code, percentage, start and end dates etc. Which meant we had to update to a foreign key class Order(models.Model): ... discount_code = models.ForeignKey(to=DiscountCode, on_delete=models.PROTECT, null=True, blank=True) during this time a few hundred orders were generated and naturally some had discount codes. When it came to running migrations we werent able to, simply because char is not a foreign key. So I decided to update the migration to handle moving from char to an object but it still fails. Here's the migration file # Generated by Django 3.2 on 2022-09-20 05:13 from django.db import migrations, models import django.db.models.deletion from datetime import date def create_discount_objects(apps, schema_editor): Order = apps.get_model('orders', 'Order') DiscountCode = apps.get_model('orders', 'DiscountCode') # Get a list of unique discount codes from the existing orders discount_codes = Order.objects.exclude(discount_code=None).order_by('discount_code').values_list('discount_code', flat=True).distinct('discount_code') # Create new Discount objects for each discount code discount_objects = [] for code in discount_codes: if code is not None: discount_objects.append(DiscountCode(code=code, percentage=10.0, start_date=date(2023,4,20), end_date=date(2023,4,20))) DiscountCode.objects.bulk_create(discount_objects) # Update the existing orders to link them to the corresponding Discount objects for order in Order.objects.all(): if … -
Join query in Django ORM with multiple joins against same table
I need multiple joins against same table. My Models: class Goods(models.Model): art = models.CharField(max_length=20, blank=True, null=True) name = models.CharField(max_length=255, blank=True, null=True) class PriceGroups(models.Model): name = models.CharField(max_length=255, blank=True, null=True) class Price(models.Model): price = models.DecimalField(max_digits=10, decimal_places=2) goods = models.ForeignKey(Goods, on_delete=models.CASCADE,) pricegroup = models.ForeignKey(PriceGroups, on_delete=models.CASCADE) This SQL works: SELECT goods.id, goods.art art, goods.name name, price_deal.price deal, price_up_200.price price_up_200, price_100_200.price price_100_200, price_50_100.price price_50_100, price_20_50.price price_20_50, price_deal.price + 2.95 deal_up, price_up_200.price + 2.95 price_up_200_up, price_100_200.price + 2.95 price_100_200_up, price_50_100.price +2.95 price_50_100_up, price_20_50.price + 2.95 price_20_50_up FROM price_goods AS goods LEFT JOIN price_price AS price_deal ON goods.id = price_deal.goods_id LEFT JOIN price_price AS price_up_200 ON goods.id = price_up_200.goods_id LEFT JOIN price_price AS price_100_200 ON goods.id = price_100_200.goods_id LEFT JOIN price_price AS price_50_100 ON goods.id = price_50_100.goods_id LEFT JOIN price_price AS price_20_50 ON goods.id = price_20_50.goods_id WHERE price_up_200.pricegroup_id = 8 AND price_deal.pricegroup_id = 5 AND price_100_200.pricegroup_id = 7 AND price_50_100.pricegroup_id = 9 AND price_20_50.pricegroup_id = 6 ''' No idea how to do in Django ORM....any way to do this? -
drf serializers, passing request to serializer context not working
this is the error I'm getting django.db.utils.IntegrityError: null value in column "user_id" of relation "recipes_recipe" violates not-null constraint DETAIL: Failing row contains (24, testtest, test1234, 20, L, , f, null). I understand the error but I don't get why it's happening. When I try do this it doesn't work # views.py class RecipeViewSet(viewsets.ModelViewSet): serializer_class = RecipeSerializer queryset = Recipe.objects.all() def get_serializer_context(self): return {"user_id": self.request.user.id} # serializers.py class RecipeSerializer(ModelSerializer): class Meta: model = Recipe fields = [ "id", "user", "title", "description", "duration", "cost", "reference_link", "is_public", ] extra_kwargs = {"user": {"read_only": True}} def create(self, validated_data): return Recipe.objects.create( user_id=self.context["user_id"], **validated_data ) but when I Do this, it works! # views.py class RecipeViewSet(viewsets.ModelViewSet): serializer_class = RecipeSerializer queryset = Recipe.objects.all() def perform_create(self, serializer): serializer.save(user_id=self.request.user.id) # serializers.py class RecipeSerializer(ModelSerializer): class Meta: model = Recipe fields = [ "id", "user", "title", "description", "duration", "cost", "reference_link", "is_public", ] extra_kwargs = {"user": {"read_only": True}} can someone explain? -
LDAPBackend.authenticate returns `Rejecting empty password for XXXX`
I am useing django-auth-ldap, overriding LDAPBackend.authenticate like this, class MyLDAPBackend(LDAPBackend): def authenticate(self, request, username=None, password=None, **kwargs): print("Try ldap auth") print(username) print(password) user = LDAPBackend.authenticate(self, username, password) Both username and password have value. username = ldaptest password = ldappass hoever it returns the error message like this , Rejecting empty password for ldaptest My settings.py is here. I also set the ldap admin password. AUTHENTICATION_BACKENDS = [ "defapp.backends.MyLDAPBackend", "defapp.backends.MyAuthBackend" ] AUTH_LDAP_SERVER_URI = "ldap://myexmaple.com" AUTH_LDAP_BIND_DN = "cn=admin,dc=myexample,dc=com" AUTH_LDAP_BIND_PASSWORD = "adminpasswd" AUTH_LDAP_USER_SEARCH = LDAPSearch( "ou=people,dc=myexample,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)" ) LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": {"console": {"class": "logging.StreamHandler"}}, "loggers": {"django_auth_ldap": {"level": "DEBUG", "handlers": ["console"]}}, } Where am I wrong? where should I check ? -
How to return related translation of a field in Django rest framework?
I have trasnlated fields in database model like below class Property(models.Model): title_en = models.CharField title_fa = models.CharField title_ar = models.CharField Right now instead of returning all the above fields in response, I use SerializerMethodField for returning related translation based on user language like below. And for updating or creating I must include those field names with their postfix. class PropertySerialzier(serializer.ModelSerialzier): title = serializers.SerializerMethodField() class Meta: model = Property fields = ( 'title', 'title_en', 'title_fa', 'title_ar', ) @staticmethod def get_title(instance: Property): return getattr(instance, f'title_{get_language()}') How can I write something general that I can use for other models and serializers? Because the project will be going to have a lot of translated fields. And also how to include these fields in the fields variable for updating or creating instances without returning in response? Maybe something like overriding methods in ModelSerialzier class in the Django-rest library? -
how can I avoid duplicating django sql queries when recursing
How to avoid duplicates during recursion in Django. Django shows 12 duplicates with recursive sql queries, how do I avoid them, the code attached from below. Еhe task of the tag is to return the nested menu class Menu(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(unique=True, db_index=True) parent = models.ForeignKey( 'self', related_name='kids', blank=True, null=True, on_delete=models.CASCADE ) class MenuView(TemplateView): template_name = 'main/menu.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['main_menu'] = kwargs.get('slug', None) return context @register.simple_tag() def draw_menu(slug): menu = Menu.objects.filter(slug=slug).prefetch_related('kids') if slug \ else Menu.objects.filter(parent=None).prefetch_related('kids') return menu {% extends 'base.html' %} {% block title %}{{ title }}{% endblock%} {% block content %} {% load draw_menu %} {% draw_menu main_menu as menu %} <ul> {% for item in menu %} {% include "inc/menu_by_menu.html" %} {% endfor %} </ul> {% endblock %} <li> {% if item.kids %} <a href="{{ item.slug }}">{{ item.title }}</a> <ul> {% for kid in item.kids.all %} {% with item=kid template_name="inc/menu_by_menu.html" %} {% include template_name %} {% endwith %} {% endfor %} </ul> {% else %} <a href="{{ item.slug }}">{{ item.title }}</a> {% endif %} </li> -
The 'rec_file' attribute has no file associated with it. django
I am working on a project where user is uploading a file and will be able to save the same but i found the below mentioned error Html <tr role="row" class="odd"> {%for list in resource_list%} <td>{{list.resource_name}}</td> <td> <a href="{{list.rec_file.url}}" download><img style="max-width: 22px" src="{% static 'img/file.png' %}" ></a> </td> View.py def add_resources(request): title="Add Resources" requesturl = request.get_full_path title = 'Create Clinic' if request.method == "POST": resource_name = request.POST.get('resource_name') resource_file = request.FILES.get('resource_file') resource_instances = Resources.objects.create( resource_name = resource_name, rec_file = resource_file ) resource_instances.save() return render(request, 'add_resources.html',{'title':title, 'requesturl':requesturl}) def index(request): title="Resources List" requesturl = request.get_full_path() resource_list = Resources.objects.all() # FILES = Resources.objects.get(rec_file = request.rec_file) return render(request, 'resources_list.html', { 'title':title, 'requesturl':requesturl, 'resource_list':resource_list, # 'resource_list1':FILES }) error The 'rec_file' attribute has no file associated with it. thanks -
How to get full url or parts to settings in model (wagtail 4.2)
@register_setting class NavigationMenuSetting(BaseSiteSetting): ... def get_url_to_admin_setting: {code} return 'admin/settings/navigation/navigationmenusetting/2/' Need solution if it's possible to do. -
backend function in AUTHENTICATION_BACKENDS is not called
I am using python-ldap What I want to do is, 1.Access LDAP Server and check there is username or not/ 2.If not exist in LDAP, then check local DB. So I set AUTHENTICATION_BACKENDS like this below in settins.py AUTHENTICATION_BACKENDS = [ "defapp.backends.MyLDAPBackend", "defapp.backends.MyAuthBackend" ] Then my source code is here. from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User from django_auth_ldap.backend import LDAPBackend class MyAuthBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): print("My auth back end is called") try: print(username) user = User.objects.get(username=username) print(user) except User.DoesNotExist: print("user can not found") return None else: if user.check_password(password) and self.user_can_authenticate(user): return user class MyLDAPBackend(LDAPBackend): def authenticate(self, username, password): print("try ldap auth") user = LDAPBackend.authenticate(self, username, password) if user: user.set_password(password) user.save() return user When I try to login the account which is exist in Ldap server, However message is like this, My auth back end is called It seems like MyLDAPBackend is not called. I suppose, class in AUTHENTICATION_BACKENDS is called in order. However dose it not work? -
'User' has no attribute 'DoseNotExist' [closed]
from django.contrib.auth.models import User class MyAuthBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: user = User.objects.get(username=username) except User.DoseNotExist: return None It shows AttributeError: type object 'User' has no attribute 'DoseNotExist' In my understanding Model returns the DoseNotExist, however it doesn't happen in my case. I am using Django4 Where am I wrong? -
Django or Flask or Pyscript? [closed]
I am making a website which uses some python code. For example my python code includes searching a file and some other python stuff also. So now I am confused how should I use my python file with my HTML, CSS and JS. whether I should use Django or flask or use Py script . Also I want a second answer what would be better if my deployment is on AWS and the website has 4-5 users at a time. -
<TemplateResponse> object does not have attribute data in Unit test in django
Hi guys im trying to run some unit testing based on this view here in django but it gives me the error AttributeError: 'TemplateResponse' object has no attribute 'data'. I tried to print the content or context from the TemplateResponse object but it does not retrieve the object date in order to assertEqual (compare) the data. I also tried to return a response object in the view but still getting the same error. class PostList(generics.ListAPIView): permission_classes = [IsAuthenticated] serializer_class = JobPostSerializer def get_queryset(self): user = self.request.user if user.is_superuser: return JobPost.objects.all() else: return JobPost.objects.filter(author=user) This is the unit test snippet code. class PostListTestCase(APITestCase): def setUp(self): self.author = NewUser.objects.create_user( email='testuser@testuser.com', user_name='test11', first_name="test11", password='Family123!') self.superuser = NewUser.objects.create_superuser( email='admin@admin.com', user_name='admin', first_name="admin", password='Family123!') self.post1 = JobPost.objects.create(title="Job Post 1", place="Test Place 1", description="Test description 1", job_date="2023-05-20", status="undone", slug="job-post-1", reward=1, author=self.author,) self.post2 = JobPost.objects.create( title="Job Post 2", place="Test Place 2", description="Test description 2", job_date="2023-05-22", status="done", slug="job-post-2", reward=1, author=self.superuser,) def test_get_queryset_superuser(self): self.client.login(email='testuser@testuser.com', password='Family123!') response = self.client.get('') self.assertEqual(response.status_code, status.HTTP_200_OK) queryset = JobPost.objects.all() serializer = JobPostSerializer(queryset, many=True) self.assertEqual(response.data, serializer.data) def test_get_queryset_author(self): self.client.login(email='admin@admin.com', password='Family123!') response = self.client.get('') print(response) self.assertEqual(response.status_code, status.HTTP_200_OK) queryset = JobPost.objects.filter(author=self.author) serializer = JobPostSerializer(queryset, many=True) self.assertEqual(response.data, serializer.data) -
Should I set a maximum length for journal content in the database?
I am using Django and PostgreSQL to do a Journal Application. What I'm thinking of is not limiting the length of the journal context so that the user can write as much as they want. What will happen if I don't set a maximum length? Should I set a maximum length for journal content in the database? -
Visual Studio 2022 and Django
I've just installed Visual Studio 2022 and created an empty Django project. When I run the server, Django is installed. But I can see that the editor highlights some warnings such as, in apps.py from django.apps import AppConfig I have reportMissingModuleSource Import "django.apps" could not be resolved from source I opened the file in Visual Code Studio and everything looks good. Has anyone an idea of what wrong with Visual Studio 2022? Or what I did wrong, even I just followed the steps of the MS tutorial (https://learn.microsoft.com/fr-fr/visualstudio/python/learn-django-in-visual-studio-step-01-project-and-solution?view=vs-2022). Having "wrong" warning is VS 2023 will very quickly be confusing... -
Binary data of Image as HttpResponse error in Django
I am trying to send the binary data of the image as a HttpResponse for the post request generated by python request lib. My view function is as follows : def view(request): print("--------------------------------------------") print("type of request:", request.method) if request.method =="POST": print( "line 55 EPD, content of POST:", request.body) print( "META", request.META) print( "FILES", request.FILES) print( "headers", request.headers) print( "all", request) print("Content_params",request.content_params) print("COOKIES", request.COOKIES) print("accepts", request.accepts("application/octet-stream")) print("session:", request.session) with open(r"C:\....\main\image.bin", mode='rb') as p: Image=p.read() print(type(Image)) return HttpResponse( Image, headers={'Content-Type': 'application/octet-stream'} ) and my unit test for generating request is as follows: def make_request(): import requests url = 'http://localhost:8000/view/' print("before sending the POST") print("sending") parameters = ( { 'Size':0, 'length':1, }) postresponse = requests.post(url,json=parameters,stream=True, headers= {'Content-Type':'application/json; charset=utf-8'}, timeout=10) print(postresponse.status_code) print("Now print Response") print("headers:", postresponse.headers) print("encoding:", postresponse.encoding) print("raw:",postresponse.raw) print("content:", postresponse.content) make_request() When my server is running, I receive the successful transfer of the response, but in the unit test code terminal, I receive the error as below: C:...\requests\models.py", line 899, in content self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b"" I receive the output until postresponse.raw but unable to output postresponse.content. Any suggestion is highly appreciated. I tried using JsonResponse as return but I get an error message stating byte objects is not serializible. -
500 internal server problem in Django issued from an inexistent favicon
I am a newbie in the Django world, and I am trying to start a new Django project but in vain! first of all, I have an old favicon from another project that appears. I don't have any referred favicon in this new project even I tried to add one it was the same problem. During the handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/user/.local/lib/python3.8/site-packages/django/template/base.py", line 470, in parse compile_func = self.tags[command] KeyError: 'endif' During the handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.8/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/home/jihan/.local/lib/python3.8/site-packages/django/contrib/staticfiles/handlers.py", line 76, in __call__ return self.application(environ, start_response) File "/home/user/.local/lib/python3.8/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ response = self.get_response(request) File "/home/user/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 128, in get_response response = self._middleware_chain(request) File "/home/user/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 49, in inner response = response_for_exception(request, exc) File "/home/user/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 103, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/home/user/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 138, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/home/user/.local/lib/python3.8/site-packages/django/views/debug.py", line 52, in technical_500_response html = reporter.get_traceback_html() File "/home/user/.local/lib/python3.8/site-packages/django/views/debug.py", line 329, in get_traceback_html t = DEBUG_ENGINE.from_string(fh.read()) File "/home/user/.local/lib/python3.8/site-packages/django/template/engine.py", line 136, in from_string return Template(template_code, engine=self) File "/home/user/.local/lib/python3.8/site-packages/django/template/base.py", line 155, in __init__ self.nodelist = self.compile_nodelist() File … -
Docker container Losing all file when start from cache
I am trying to create a Dockerfile for developing Django backend. However, when I finished my Dockerfile and tried to build it, a very strange error occurred. When my container was successfully built and automatically started, all the files I had copied into it were lost. Container build log Container log I try to change the CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] to CMD ["python"] and used ls check the file, its empty. file check Then I found the last cache and used it to generate a container, and found that the process worked perfectly fine, which was the most peculiar part. Container from cache working fine Environment I'm using: Windows 11 Docker for windows v4.17.1 PyCharm 2023.1 (Professional Edition) Configuration setting Docker setting configuration setting I don't know if this is a problem with my Dockerfile or a bug with Docker, but since I need to provide my team with a Docker to complete our task, I hope to solve this problem and enable my team to build containers correctly from the Dockerfile.