Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django separate location of static files
I am working with Django 3.2 and I have 3 types of static files (images, css files, js files). I did not want the images to be versioned with git so I found a way to have them served by an aws S3 bucket using django-storages and boto3. It works perfectly fine with the following configuration in my settings.py file: AWS_ACCESS_KEY_ID = "my-key-id" AWS_SECRET_ACCESS_KEY = "my-secret-key" AWS_STORAGE_BUCKET_NAME = "my-bucket-name" AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None #DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_ADDRESSING_STYLE = "virtual" AWS_S3_REGION_NAME = 'my-region' AWS_S3_SIGNATURE_VERSION = 's3v4' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Whilst this configuration works perfectly fine, it forces me to have my CSS and js files in the AWS s3 bucket as well. I was perfectly happy with my CSS and js files being served by django (or NGINX in production) and versioned with my code without having to copy them to the bucket manually. Would you have a solution to serve only static images by AWS S3 and CSS/JS files by NGINX ? -
bad request when django deployed to heroku
I've just attempted to deploy my django project to Heroku and I am getting a bad request 400 error. The strange thing is that it was working fine before hand and I had to make changes to my code. This works fine locally too. Really confused right now. Any help on where I am going wrong would be great. part of my settings.py file X_FRAME_OPTIONS = 'SAMEORIGIN' ALLOWED_HOSTS = ['engagefitness.herokuapp.com', 'localhost'] -
Django Custom Filter to get video duration using MoviePy not working
I am trying to use a custom filter to find the video duration using moviepy however the function is not able to access the files even though it seems the correct video path is being passed into the function in the custom filter. I'm getting the following error: OSError at /tape/tape/ MoviePy error: the file /media/video_files/channel_Busy/171003B_026_2k.mp4 could not be found! Please check that you entered the correct path. The custom filter: vduration.py from django import template import moviepy.editor register = template.Library() @register.filter(name='vduration') def vduration(videourl): video = moviepy.editor.VideoFileClip(videourl) video_time = int(video.duration) return video_time views.py def tape(request): tapes=VideoFiles.objects.all() context={ "videos": tapes, } return render(request, "tape/tape.html", context) tape.py {% for video in videos %} <div class="video-time">{{video.video.url | vduration}}</div> {% endfor %} models.py class VideoFiles(models.Model): id=models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) video=models.FileField(upload_to=channel_directory_path) def get_absolute_url(self): return reverse('video_watch', args=[str(self.id)]) def __str__(self): return f"video_file_{self.id}" -
Deleting object with django inline_formset
Am trying to build a page that allows a restaurant owner to edit/delete items from their menu. Models.py: class Restaurant(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) name = models.CharField(max_length=200, verbose_name = 'Restaurant Name') class Menu(models.Model): restaurant = models.OneToOneField( Restaurant, on_delete=models.CASCADE, primary_key=True, ) class Item(models.Model): menu = models.ForeignKey(Menu, on_delete=models.CASCADE) name = models.CharField(max_length=100) description = models.TextField(blank=True) views.py: def test_url(request): # Get this Restaurant object restaurant = Restaurant.objects.get(pk = 1) # Get this Restaurant's Menu object restaurant = restaurant.menu # Create inline formset ItemFormSet = inlineformset_factory(Menu, Item, fields=('name', 'description',), max_num=1, extra=0, can_delete=True) if request.method == 'POST': formset = ItemFormSet(request.POST, instance = menu) if formset.is_valid(): for form in formset: form.save() return HttpResponse(formset.cleaned_data) # referenced later in the question else: formset = ItemFormSet(instance = menu) return render(request, 'restuarant/edit_menu.html', { 'formset': formset, }) The docs state the can_delete attribute: " adds a new field to each form named DELETE and is a forms.BooleanField. When data comes through marking any of the delete fields you can access them with deleted_forms". This does add the delete field to my template, and if I select that checkbox on one of the forms it will return: {'name': 'Fried Calamari', 'description': '', 'id': , 'DELETE': True, 'menu': .RelatedManager object at 0x7fa644347a30>>>} but … -
Django urls href redirect bug
When I click on the "apropos" button on my navbar to access to my "apropos" pages it load the page correctly but with this url http://127.0.0.1:8000/contact/apropos/ when it should be http://127.0.0.1:8000/apropos/. it does the samething when I click on the "contact" button on my navbar it redirect me to this urls http://127.0.0.1:8000/contact/contact And when I click on "Accueil" it redirect me to http://127.0.0.1:8000/contact When it should redirect me to http://127.0.0.1:8000/ mysite/urls.py urlpatterns = [ path("", include("main.urls")), path('admin/', admin.site.urls), path("apropos/", include("main.urls")), path("contact/", include("main.urls")), ] main/urls.py urlpatterns = [ path("", views.home, name="home"), path("apropos/", views.apropos, name="apropos"), path("contact/", views.contact, name="contact") ] views.py def home(response): return render(response, "main/index.html", {}) def apropos(response): return render(response, "main/about.html", {}) def contact(response): return render(response, "main/contact.html", {}) index.html (navbar section) <!-- header nav section --> <header class="xs-header-nav"> <div class="container"> <div class="row menu-item"> <div class="col-lg-12"> <nav id="navigation1" class="navigation header-nav clearfix"> <div class="nav-header"> <!-- <a class="nav-brand" href="#"></a>--> <a href="./index.html" class="mobile-logo"> <img src="static/assets/images/mobile_logo.png" alt=""> </a> <div class="nav-toggle"></div> </div> <div class="nav-menus-wrapper clearfix"> <ul class="nav-menu"> <li class="active"><a href="{% url "home" %}">Home</a> </li> <li><a href="#">Services</a> </li> <li><a href="gallery.html">Portfolio</a></li> <li><a href="{% url "apropos" %}">À-propos</a></li> <li> <a href="{% url "contact" %}">Contact</a> </li> </ul> <div class="header-nav-right-info align-to-right"> <label><i class="icon icon-phone3"></i> (514) 569-2380</label> </div> </div> </nav> </div> </div><!-- .row end --> … -
Getting 500 internal Server Error using django and apache
Hi I'm in the works of making my project live but I am getting a 500 Internal error when trying to access the server domain. This is my first time making a project live using apache and django and linux so it may be something simple that I don't know how to fix, but so far I've set ownership my project with sudo chown www-data mysitenew and for my database (db.sqlite3) as well. I had a suspicion that it could be something to do with changing my pre-existing environment variables to a JSON file where all my variables are stored then added to with json.load in settings.py, but I have done a lot of research and kind find anything that relates to my case as there is nothing indicating in error.log where my problem is. My second suspicion is that I am not on the root but I am on a user which I created and gave the group sudo too, I wasn't sure if that could be problem when setting permissions it may be something there but as I said I am unexperienced when it comes to using linux. I'm going to be updating this question as I keep … -
Query data in django matched with ids in a list
I am trying to update some data in my django models But kinds stuck on how to get that particular attributes. see I have a list name ids = ['112', '111', '114', '113', '115'] And I have a model name Member class Member(models.Model ): user = models.ForeignKey(Users,verbose_name='User Id', on_delete=models.CASCADE) com = models.ForeignKey(Committee, on_delete=models.CASCADE,verbose_name='Committee Name') mem_status = models.CharField( max_length=20,choices=MEMBER_STATUS, verbose_name='Member Status') mem_note = models.TextField(null=True, blank=True) mem_order = models.IntegerField(default=0) So each id in ids have a object available in Member Model, What I want is to update the mem_order of each object like this. suppose 111 in ids is at 2nd index. I want to set mem id with 111 to set 2 in mem_order. I am getting all the desired members from Member table Now I dont know how to loop over those ids and match them the id of Each Member from Member model. -
Page not found when I log out, any idea why the logging out doesn't work?
Working on a social app with django and clicking on the log out doesn't work anymore for some reason I get: Page not found (404) No profile found matching the query Request Method: GET Request URL: http://127.0.0.1:8000/logout Raised by: network.views.<class 'network.views.ProfileDetailView'> Using the URLconf defined in project4.urls, Django tried these URL patterns, in this order: admin/ [name='all-profiles-view'] [name='profile-view'] The current path, logout, matched the last one. Also is there an easy way to make the user's name clickable from any page directed to their profile(ProfileDetailView)?? URLs: from django.urls import path from django.conf import settings from django.conf.urls.static import static from . import views from .views import ( posts_of_following_profiles, like_unlike_post, invites_received_view, invite_profiles_list_view, send_invitation, remove_friends, accept_invitation, reject_invitation, ProfileDetailView, PostDeleteView, PostUpdateView, ProfileListView, ) urlpatterns = [ path("", ProfileListView.as_view(), name="all-profiles-view"), path("<slug>", ProfileDetailView.as_view(), name="profile-view"), path("posts/", views.post_comment_create_view, name="posts"), path("posts-follow/", posts_of_following_profiles, name="posts-follow"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("liked/", like_unlike_post, name="like-post-view"), path("<pk>/delete", PostDeleteView.as_view(), name="post-delete"), path("<pk>/update", PostUpdateView.as_view(), name="post-update"), path("invites/", invites_received_view, name="invites-view"), path("send-invite/", send_invitation, name="send-invite"), path("remove-friend/", remove_friends, name="remove-friend"), path("invites/accept/", accept_invitation, name="accept-invite"), path("invites/reject/", reject_invitation, name="reject-invite"), path("to-invite/", invite_profiles_list_view, name='invite-profiles-view') ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Views: from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.http.response import JsonResponse from … -
Can you pass a session value into a views parameter in django?
Here is a simple adding view I created: def adder(request): request.session['one'] = 1 request.session['two'] = 2 one = request.session['one'] two = request.session['two'] answer = one+two return HttpResponse(answer) I want to be able to do somethign like this: def adder(request,one = request.session['one'], two = request.session['two']): answer = one+two return HttpResponse(answer) I would create the sessions 'one' and 'two' in a separate view beforehand. The reason that I want to pass them in as parameters is that I have some python code that I wish to run in django and it requires parameters that will be input by the user. Any advice would be appreciated. -
Django ModuleNotFoundError all of a sudden
All of a sudden, my django project is not working anymore. Not only my actual branch but even master. This happened after coming back to my project after the night. The error I have is when I run any command I have this message : ModuleNotFoundError: No module named 'pur_beurre.pur_beurre' (Note : pur_beurre is the name of my project) When I run python manage.py, I have the list of all possible commands plus this new message in red : Note that only Django core commands are listed as settings are not properly configured (error: No module named 'pur_beurre.pur_beurre'). I tried to put pur_beurre and pur_beurre.pur_beurre in my installed app in settings.py but its not working. -
One-To-Many Model Serializer not displaying object in django rest framework
I have a one to many model in django rest framework. Video is the parent and Tags are the child, I'm trying to display all the tags in the Video serializer. class Video(Base): video = models.FileField(null=True, blank=True) thumbnail = models.ImageField(null=True, blank=True) class Tag(Base): video = models.ForeignKey(Video, on_delete=models.CASCADE, related_name='tags') text = models.CharField(max_length=100, null=True, blank=True) score = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) In my serializer I have this, class VideoSerializer(serializers.ModelSerializer): video = serializers.FileField(max_length=None, use_url=True, allow_null=True, required=False) thumbnail = serializers.ImageField(max_length=None, use_url=True, allow_null=True, required=False) class Meta: model = Video fields = ('id', 'video', 'thumbnail', 'tags') The problem is that the serialized data only show the id for the Tags. Any help appreciated. -
How to display search term on search results page in django?
I made a form and then i made little search form and it works but, i didnt display the search term on the search results page... I just wanna show Search Results for (Search Term) Here are my codes. Views.py class SearchResultsView(ListView): model = Post template_name = 'search.html' def get_queryset(self): query = self.request.GET.get('q') object_list = Post.objects.filter(Q(soru1__icontains=query) | Q(soru2__icontains=query) | Q(soru3__icontains=query) | Q(soru4__icontains=query) | ) return object_list Base.html ( search bar in it) <form class="d-flex" action="{% url 'search' %}" method="get"> <input class="form-control me-2" name="q" type="text" placeholder="Arama..."> <button class="btn btn-outline-success" type="submit">Ara</button></form> And search.html {% extends 'base.html' %} {% block content %} <h1>Search Results for </h1> <ul> {% for Post in object_list %} <li> <a href="{% url 'article-detail' Post.id %}">{{ Post.soru1 }}</a> </li> {% endfor %} </ul> {% endblock %} -
Django how to add a form to a DetailView with FormMixin
I am attempting to add a form for comments to a DetailView. The DetailView displays notes for specific projects. So the comments have a foreign key that is the specific note and the note has a foreign key for the specific project. I am attempting to use FormMixin with DetailView. So far I have not bee successful. Currently I can get the form to display but it does not save and in the terminal I see the following error Method Not Allowed (POST): /projects/project/1/note/1/ I can get these to work separately but not with the form in the DetailView. Here are my models: class ProjectNotes(models.Model): title = models.CharField(max_length=200) body = tinymce_models.HTMLField() date = models.DateField(auto_now_add=True) project = models.ForeignKey(Project, default=0, blank=True, on_delete=models.CASCADE, related_name='notes') def __str__(self): return self.title class ProjectNoteComments(models.Model): body = tinymce_models.HTMLField() date = models.DateField(auto_now_add=True) projectnote = models.ForeignKey(ProjectNotes, default=0, blank=True, on_delete=models.CASCADE, related_name='comments') The View: class ProjectNotesDetailView(DetailView, FormMixin): model = ProjectNotes id = ProjectNotes.objects.only('id') template_name = 'company_accounts/project_note_detail.html' comments = ProjectNotes.comments form_class = NoteCommentForm def form_valid(self, form): projectnote = get_object_or_404(ProjectNotes, id=self.kwargs.get('pk')) comment = form.save(commit=False) comment.projectnote = projectnote comment.save() return super().form_valid(form) def get_success_url(self): return reverse('project_detail', args=[self.kwargs.get('pk')]) The form: class NoteCommentForm(forms.ModelForm): class Meta: model = ProjectNoteComments fields =['body',] widgets = { 'body': forms.TextInput(attrs={'class': 'form-control'}) } The … -
Want to show the image_name in the Django update form
This is my post item view code if request.method == 'POST': form = MenuItemForm(request.POST,request.FILES) image = request.FILES['image'] image_url = upload_image(image, 'menu_item', image.name) if form.is_valid(): obj = form.save(commit=False) obj.image_url = image_url form.save() return redirect('menu-item') This is my view for the update def menu_item_update(request, id): item = MenuItem.objects.get(id=id) if request.method == 'POST': form = MenuItemForm(request.POST,request.FILES, instance=item) if form.is_valid(): form.save() return redirect('menu-item') else: form = MenuItemForm(instance=item) context = { 'form': form, } return render(request, 'menu/menu_item_update.html', context) and this is my form class MenuItemForm(forms.ModelForm): image = forms.ImageField() class Meta: model = MenuItem fields = ['name', 'description', 'menu_category'] And this is my model class MenuItem(models.Model): name = models.CharField(max_length=500, null=False) description = models.CharField(max_length=500, null=True) image_url = models.CharField(max_length=1000, null=True) menu_category = models.ForeignKey(MenuCategory, on_delete=models.CASCADE) As you can see in my post view, I am uploading the file to the google storage bucket and saving only the URL to the database. Now I want to show the same file or its file name to the update form in the image field, after reading the image from google storage. I have the image URL but how to do it I do not know. -
How to update a model which contains an ImageField in django rest framework?
I need help updating a model that contains an ImageField with django rest framework (3.12.4). I've checked many questions related to this, but none seem to fix the problem. models.py class Image(models.Model): title = models.CharField(max_length=200, unique=True) image = models.ImageField(upload_to="images/") def delete(self, *args, **kwargs): self.image.delete() super().delete(*args, **kwargs) serializers.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = ['id', 'title', 'image'] views.py class ImageViewSet(viewsets.ModelViewSet): serializer_class = ImageSerializer queryset = Image.objects.all() parser_classes = (MultiPartParser, FormParser) def create(self, request, *args, **kwargs): file_serializer = ImageSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) This way I can add a new image. The file is successfully added to images folder and the fields are serialized correctly. I can also delete created image, removing the file from images folder and instance from database. However, when I access the instance, I am unable to modify it without reloading the file; so if I want to change the title, I have to reload the file again and then make the request. Is there any way to update a model that contains an ImageField in django rest framework? -
Allow multiple users to login at the same time in Django project
I am working on a django project and I have completed working on it. And I tested it and ran the project in on two webpages in chrome with my localhost:8000 server . I logged in in first page as a first user , lets say user1 and logged in on another page with another username , lets say user2 . But when I refresh the first page , the user1 is not logged in and I get logged in as the user2. The first page user1 is not logged in . I want to login multiple users at the same time so I can interact with the page. Kindly help me . -
Django - links are incorrectly resolved in menu
I am developing locally Django page and have some issues with highlighted menus. when hover over "moje projekty" I see below link 127.0.0.1:8080/portfolio/, I click and page opens when now I hover hover 2nd time, it is showing: 127.0.0.1:8080/portfolio/portfolio/, I click and page opens when now I hover hover 3rd time,it is showing: 127.0.0.1:8080/portfolio/portfolio/portfolio/, I click and error is: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8080/portfolio/portfolio/portfolio/ Using the URLconf defined in my_site.urls, Django tried these URL patterns, in this order: admin/ [name='home'] about_me/ [name='aboutme'] portfolio/ [name='portfolio'] posts/slug:the_slug/ [name='post_detail'] summernote/ ^media/(?P.)$ portfolio/ [name='home'] portfolio/ about_me/ [name='aboutme'] portfolio/ portfolio/ [name='portfolio'] portfolio/ posts/slug:the_slug/ [name='post_detail'] portfolio/ summernote/ portfolio/ ^media/(?P.)$ about_me/ The current path, portfolio/portfolio/portfolio/, didn’t match any of these. base.html: <!DOCTYPE html> <html> <head> <title>Moja strona</title> <link href="https://fonts.googleapis.com/css?family=Roboto:400,700" rel="stylesheet"> <meta name="google" content="notranslate" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> </head> <body> <style> body { font-family: "Roboto", sans-serif; font-size: 17px; background-color: #fdfdfd; } .shadow { box-shadow: 0 4px 2px -2px rgba(0, 0, 0, 0.1); } .btn-danger { color: #fff; background-color: #f00000; border-color: #dc281e; } .masthead { background: #3398E1; height: auto; padding-bottom: 15px; box-shadow: 0 16px 48px #E3E7EB; padding-top: 10px; } img { width: 00%; height: auto; object-fit: … -
Django how to update image fields which coming from another model?
I am trying to update profile_pic fields in my views which coming from another model. But image isn't updating. here is my code: Here is my two model: class Doctor(models.Model): doctor_name = models.CharField(max_length=100) class UserProfile(models.Model): profile_pic = models.ImageField(upload_to='profile/images/',blank=True,null=True) acess_doctor_model = models.ForeignKey(Doctor, on_delete=models.CASCADE,blank=True,null=True,related_name="acess_doctor_model") forms.py class DoctorUpdateFrom(forms.ModelForm): class Meta: model = Doctor fields = ['doctor_name'] views.py if request.method == "POST": form = DoctorUpdateFrom(request.POST,request.FILES,instance=obj) if form.is_valid(): obj = form.instance profile_pic = request.FILES['profile_pic'] form.save() UserProfile.objects.filter(acess_doctor_model=obj).update(profile_pic=profile_pic) HTML <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="doctor_name"> <input type="file" name="profile_pic" accept="image/*" id="id_profile_pic"> </form> -
Internal Server Error while posting Django app to Heroku
I have just posted my django app to heroku. It is said that the build was successful, but when I am opening the app I see Internal Server Error. I wrote heroku logs --tail and it says that there is no module named _tkinter, however, my application is not using this module at all. What is the problem? Could anyone help me? Here is the full output of heroku logs --tail 2022-01-23T15:59:25.156790+00:00 app[web.1]: import tkinter as TK 2022-01-23T15:59:25.156790+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/tkinter/init.py", line 37, in 2022-01-23T15:59:25.156790+00:00 app[web.1]: import _tkinter # If this fails your Python may not be configured for Tk 2022-01-23T15:59:25.156791+00:00 app[web.1]: ModuleNotFoundError: No module named '_tkinter' 2022-01-23T15:59:25.157000+00:00 app[web.1]: 10.1.20.212 - - [23/Jan/2022:15:59:25 +0000] "GET /favicon.ico HTTP/1.1" 500 0 "-" "-" 2022-01-23T15:59:25.158452+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=thinking-meme-live.herokuapp.com request_id=09f7a53c-e31c-4496-8023-5ff6be64f006 fwd="193.174.122.67" dyno=web.1 connect=0ms service=42ms status=500 bytes=244 protocol=https -
empty path breaks after adding the first app in django
I created a new django app and ran it using python manage.py runserver . It ran normal and I could see the default page With the shell outputting: Django version 4.0.1, using settings 'storefront.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [23/Jan/2022 18:52:07] ←[m"GET / HTTP/1.1" 200 10697←[0m [23/Jan/2022 18:52:07] ←[36m"GET /static/admin/css/fonts.css HTTP/1.1" 304 0←[0m [23/Jan/2022 18:52:07] ←[36m"GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 304 0←[0m [23/Jan/2022 18:52:07] ←[36m"GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 304 0←[0m [23/Jan/2022 18:52:07] ←[36m"GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 304 0←[0m Not Found: /favicon.ico [23/Jan/2022 18:52:07,704] - Broken pipe from ('127.0.0.1', 56807) Then I added a new app, like so: python manage.py startapp playground then I added an action handler playground/views.py def say_hello(request): return HttpResponse('Hello World!') I also added urls.py inside the playground folder playground/urls.py urlpatterns = [ path('hello/', views.say_hello) ] And the main urls.py I added: root/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('playground/', include('playground.urls')), ] In the main settings.py, I included playground in the INSTALLED_APPS list. Then I ran the application, and I can confirm that the path 127.0.0.1:800/playground/hello works as expected. However, the empty path 127.0.0.1:8000/ is no longer valid. I get this error: The empty path only works if I comment the playground urls, urlpatterns = [ path('admin/', admin.site.urls), … -
Apache error[ ModuleNotFoundError: No module named 'encodings'] python
I'm trying to build a production environment using Django. python・・・ver3.9.5 apache・・・ver2.4 windows server .venv is not used. The following sites are the main references. https://tamapoco.com/archives/7727 I have confirmed the startup confirmation (It works) of apache. The project created in Django has been confirmed to work in a virtual environment. I want to run a project by linking apache and wsgi, but I get an error. Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' I had the same question on other sites, so I referred to it. I tried setting the environment path and reinstalling python, but it didn't work. Can you tell me? Thank you. Contents added in httpd.conf (listed at the end) LoadFile "c:/users/administrator/appdata/local/programs/python/python39/python39.dll" LoadModule wsgi_module "c:/users/administrator/appdata/local/programs/python/python39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "c:/users/administrator/appdata/local/programs/python/python39" WSGIScriptAlias / "/Users/Administrator/django/CoreManageSystem/CoreManageSystem/wsgi.py" WSGIScriptReloading On <Files wsgi.py> #Require all denied Require all granted #Require ip 192.168.10 #Require host .xxx.com </Files> Alias /static/admin "C:/Users/Administrator/AppData\Local/Programs/Python/Python39/Lib/site-packages/django/contrib/admin/static/admin" <Directory "C:/Users/Administrator/AppData\Local/Programs/Python/Python39/Lib/site-packages/django/contrib/admin/static/admin"> #Require all denied Require all granted #Require ip 192.168.10 #Require host .xxx.com </Directory> Alias /static/ "C:/Users/Administrator/django/CoreManageSystem/main/static/" <Directory "C:/Users/Administrator/django/CoreManageSystem/main/static/"> #Require all denied Require all granted #Require ip 192.168.10 #Require host .xxx.com </Directory> environmental variables C:\Users\Administrator\AppData\Local\Programs\Python\Python39\Scripts C:\Users\Administrator\AppData\Local\Programs\Python\Python39\ apache log Python path … -
django bootstrap alert: message alert showing forcefully in django
i am writing a function that would allow users chat with freelancers but now it keeps popping up a messages alert when i open up a new chat with another user. i would provide a screenshot below, and that is because it is not throwing any errors, but forcefully showing alerts. i have some ideas why it would be doing that and that is because django messages uses message.success(request, ...) etc. and in my function i have a lot of variables named message = ..., the problem now is that i do not know the particular message varible that i am going to rewrite. NOTE: when i comment out the alert logic in base.html - the erros stops showing, SCREENSHOT IS BELOW i would provide any more details needed asap base.html - section containing the bootstrap alert messages <header> {% if messages %} {% for message in messages %} <div class="alert alert-{{message.tags}} alert-dismissible fade show" role="alert" style="text-align: center;"> <div class="avatar avatar-xs me-2"> {% if request.user.profile.image.url %} <img class="avatar-img rounded-circle" src="{{request.user.profile.image.url}}" alt="avatar"> {% else %} {% endif %} </div> <!-- Info --> {{message}} <a href="#" class="text-reset btn-link mb-0 fw-bold"></a> <button type="button" class="btn-close mt-1" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endfor %} {% endif … -
MultiValueDictKeyError at /
with a post request locally (pycharm) everything works, but not on the server I can’t figure out what the problem is, I see that I can’t find doc_id but I don’t understand why post { "customer_id":"1", "field": { "Number_doc_str":"32", "company_1":"РосРеестр", "company_2": "ИП Иванов", }, "doc_id": 2 } view.py class AddDocument(APIView): def post(self, request): data = request.data document = Document.objects.get(id=data['doc_id']) Error: MultiValueDictKeyError at /adddocument/ 'doc_id' Request Method: POST Request URL: http://constructor.site/adddocument/ Django Version: 3.2.11 Exception Type: MultiValueDictKeyError Exception Value: 'doc_id' Exception Location: /var/www/u1576304/data/djangoenv/lib/python3.7/site- packages/django/utils/datastructures.py, line 78, in __getitem__ Python Executable: /opt/python/python-3.7.0/bin/python Python Version: 3.7.10 Python Path: ['/var/www/u1576304/data//www/constructor.site/Constructor', '/var/www/u1576304/data/djangoenv/lib/python3.7/site-packages', '/var/www/u1576304/data/www/constructor.site', '/usr/share/passenger/helper-scripts', '/opt/python/python-3.7.0/lib/python37.zip', '/opt/python/python-3.7.0/lib/python3.7', '/opt/python/python-3.7.0/lib/python3.7/lib-dynload', '/opt/python/python-3.7.0/lib/python3.7/site-packages'] Server time: Sun, 23 Jan 2022 14:25:02 +0000 -
I have Error: The 'image' attribute has no file associated with it
I'v been trying to update image by using django-extra-views(UpdateWithInlinesView). When I check clear checkbox and update this field, I have this error The 'image' attribute has no file associated with it. However, when I check delete checkbox and update the field, I can successfully update it. Then I have two question. Why these behaviors are different? What should I do to solve the above error? -
Django ChoiceField make only one choice readonly
I have a dropdown multichoice field in django, and I want to make only one value from the dropdown read only so it can't be edited, and leave the rest editable I want if possible to do it in my view's get_form here's what I'm doing so far : form.fields["groups"].queryset = models.Group.objects.all() form.fields["groups"].initial = models.Group.objects.filter(is_default=True) So basicly I want the default value to always be selected ( selected and disabled ) Thanks for guiding me through this.