Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
django+nginx+gunicorn issues with Cerbot to turn into HTTPS
I am currently deploying my django app on a server AWS Lightsail Debian 10.8. It's working fine with http. So I wnated to turn my app into HTTPS and getting an SSL certificate. I followed 2 tutorials about it : This guy This page Once all these steps done nothing works anymore even in HTTP, the site isn't accessible... Here is the config file in /etc/nginx/sites-available. server { server_name 13.38.76.96 www.zlochteam.com; location / { include proxy_params; proxy_pass http://localhost:8000/; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/www.zlochteam.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/www.zlochteam.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.zlochteam.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name 13.38.76.96 www.zlochteam.com; return 404; # managed by Certbot } I wanted to know if someone has ecountered the same issue and how he solved it. Thanks ! -
check all forms then call save methd - django dynamic form
i've created a page which has a formset, i want to check all forms if they have error, then call save method, but create() automatically call save method! is there away to prevent it please ? here is my views.py def addNewGuestPopup(request): if request.method == "POST": form_no = int(request.POST.get('form_no')) removed_form = request.POST.get('removed_form').split(",") error_form_exits = [] new_guests = [] for i in range(form_no): if str(i) not in removed_form: full_name = request.POST.get('fullname-'+str(i)) dob = request.POST.get('dob-'+str(i)).split("-") try: visitor = Vistor.objects.get(full_name=full_name, dob=datetime.datetime(int(dob[0]), int(dob[1]), int(dob[2]))) error_form_exits.append(i) except Vistor.MultipleObjectsReturned: pass except Vistor.DoesNotExist: visitor = Vistor.objects.create(full_name=full_name, dob=datetime.datetime(int(dob[0]), int(dob[1]), int(dob[2])), admin=request.user) new_guests.append(visitor) # return JsonResponse({'error_form':error_form}) print(len(error_form_exits)) return JsonResponse({'data':list(Vistor.objects.values_list('full_name', flat=True)), 'error_form':error_form_exits}, safe=True) return render(request, 'main/forms.html') i dont want to use django formset is there a way to prevent create from save until all forms been checked please? note : dob and full_name are unique together thank you .. -
Django session working normally locally but once deployed to Heroku they are refreshed upon every view change
The sessions work perfectly while changing views when working locally, but when deployed to Heroku it is as if the session was refreshed and all the information it contains is deleted upon every view change. I am using Heroku's Postgres Database. I have already taken a look at: Django Session Not Working on Heroku but the problem still persists. Other people are having the same problem but there is no clear answer. Here is my current settings file. Any help would be appreciated import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'e488a0185303170daa47fe1de243823fbb3db60f045e6eae' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', 'here goes the heroku host'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', '....', '....', ] ASGI_APPLICATION = 'System.asgi.application' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'System.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'System.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } import dj_database_url db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) SESSION_ENGINE= 'django.contrib.sessions.backends.cached_db' AUTH_PASSWORD_VALIDATORS … -
201 Created - but no new object in SqLite database
I have a button that users can click on to add an object to their account. It's sent through django to my sqlite db, and in the console log there are no errors. It says "201 Created", and yet there is no new object in the database. Someone else had the same problem as me, the solution was getting rid of some methods in the serializer, but they don't specify what they got rid off. What's causing this? Here is my serializer: class RatSerializer(FlexFieldsModelSerializer, serializers.ModelSerializer): name = serializers.CharField() user = serializers.CharField(source='user.username', required=False) userid = serializers.CharField(source='user.id', required=False) body_colour = BodyColourSerializer() eye_colour = EyeColourSerializer() image = ImageSerializer(required=False) class Meta: model = rat exclude = ['bio'] def create(self, data): request = self.context.get("request") user = request.user return rat( name = data["name"], body_colour = BodyColour(name=data["body_colour"]["name"]), eye_colour = EyeColour(name=data["eye_colour"]["name"]), image = Image(), user = user) My views: class ratViewset(ModelViewSet, APIView): serializer_class = RatSerializer # queryset = rat.objects.all() def get_queryset(self): user = self.request.user if user.is_anonymous: return rat.objects.all() return rat.objects.filter(user=user.id) def post(self, request): rat = request.data.get('rat') # creates rat with the above data serializer = RatSerializer(data=rat) if serializer.is_valid(raise_exception=True): serializer.save() print(serializer.data, type(serializer.data)) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status) Grateful for any help! -
django rest framework trigger goes in loop on network delay
1: I am working with django rest framework as backend and angular as frontend. I am using signals and receiver of django at many places in my project. on pre_save or post_save method i am facing a common problem. The problem is in case of network delay the requested signals gets executed more than one time. for instance, i am sending email notification to any customer using signal like this. pre_save.connect(send_new_coupon_notification_email, sender = coupon) if due to network email sending response gets delay, coupan table will created multiple records. If response is fast in that case it works fine. 2: we have two models on two server, once coupan is created on pre_save or post_save i need to create another record say in beneficiary model. as i am indicating in these two models. if Beneficiary returns acknowledge quickly than it works fine. but again in case of network delay Coupan creates multiple records. class Beneficiary(models.Model): name = models.CharField(max_length=50) coupon_code = models.ForeignKey(coupon, on_delete=models.CASCADE) miscValue = models.TextField(blank=True, null=True) def __str__(self): return self.name class coupon(models.Model): sl_no = models.CharField(max_length=50) @receiver(post_save, sender=coupon) def save_profile(sender, instance, **kwargs): Beneficiary.objects.create(name="added from reciever", coupon_code=instance) 3: In test environment this works fine as we work on LAN, but once it … -
Can't display picture on my django social app using imageField?
I need some fresh eyes, what am I missing here? In my Post Model imageField is defined as "picture" to be uploaded on the site, I seed it on my admin panel, it gets uploaded just fine but I can't seem to make it appear on the page: http://127.0.0.1:8000/posts/. I get ValueError at /posts/ The 'picture' attribute has no file associated with it. Highlited line is line 257, in post_comment_create_view return render(request, 'network/posts.html', context) Model: class Post(models.Model): # id is created automatically by Django picture = models.ImageField(upload_to='images', blank=True, validators=[FileExtensionValidator(['png', 'jpg', 'jpeg'])]) content = models.TextField() liked = models.ManyToManyField(Profile, blank=True, related_name="likes") author = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created',) def __str__ (self): return str(self.content[:20]) Forms: class PostModelForm(forms.ModelForm): content = forms.CharField(widget=forms.Textarea(attrs={'rows':2})) class Meta: model = Post fields = ('content', 'picture') Views: @login_required def post_comment_create_view(request): qs = Post.objects.all() profile = Profile.objects.get(user=request.user) #Setting up pagination p = Paginator(qs, 5) page = request.GET.get('page') post_list = p.get_page(page) #Post form, comment form p_form = PostModelForm() c_form = CommentModelForm() post_added = False profile = Profile.objects.get(user=request.user) if 'submit_pForm' in request.POST: print(request.POST) p_form = PostModelForm(request.POST, request.FILES) if p_form.is_valid(): instance = p_form.save(commit=False) instance.author = profile instance.save() p_form = PostModelForm() post_added = True if 'submit_cForm' … -
Best wat to implement action button in django
I'm writing a Django app that has an action button called restart. When clicked this button should restart a service. The problem is how would I implement this I have the option to add some JavaScript to the button and call the public rest API that's contained inside the Django app. Would that be the way to go? And how can I add an endpoint to the rest API? The endpoint would look like this /API/v1/services/service_name/restart -
Python/Django "page not found" error: "The current path, ... , didn’t match any of these."
I'm learning Chapter 18 in Python Crash Course by Eric Matthes. I am using Django 4.0.1 and the book uses is 2.2.0 so I see that other people are having similar issues as me with this section. In other similar stackoverflow questions on this issue, proposed solutions using url instead of path seem also outdated. The solutions on the website therefore are unfortunately not helping me. Problem: when I open http://localhost:8000/ and I click on "topics" I get the 404 not found error as follows: Page not found (404) Request Method: GET Request URL: http://localhost:8000/(%25%20url%20'learning_logs:topics'%20%25%7D Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order: admin/ [name='index'] topics/ [name='topics'] The current path, (% url 'learning_logs:topics' %}, didn’t match any of these. However, navigating manually to http://localhost:8000/topics shows me the page as intended. I believe this is an issue due to my urls.py located in my app folder. Here is my urls.py in learning_logs (app), where I think the issue lies: from django.urls import path from . import views app_name = 'learning_logs' urlpatterns = [ #Home page path('', views.index, name='index'), #Page that shows all topics. path('topics/', views.topics, name='topics'), ] Here is my urls.py in learning_log (main project): … -
how to fix template does not exist in Django?
I am a beginner in the Django framework. I created my project created my app and test it, it work fine till I decided to add a template. I don't know where the error is coming from because I follow what Django docs say by creating folder name templates in your app folder creating a folder with your app name and lastly creating the HTML file in the folder. NOTE: other routes are working fine except the template Please view the screenshot of my file structure and error below. File Structure ERROR TemplateDoesNotExist at /blog/ Blog/index Request Method: GET Request URL: http://127.0.0.1:8000/blog/ Django Version: 4.0.1 Exception Type: TemplateDoesNotExist Exception Value: Blog/index Exception Location: C:\Python39\lib\site-packages\django\template\loader.py, line 19, in get_template Python Executable: C:\Python39\python.exe Python Version: 3.9.4 Python Path: ['C:\\Users\\Maxwell\\Desktop\\Django\\WebApp', 'C:\\Python39\\python39.zip', 'C:\\Python39\\DLLs', 'C:\\Python39\\lib', 'C:\\Python39', 'C:\\Users\\Maxwell\\AppData\\Roaming\\Python\\Python39\\site-packages', 'C:\\Python39\\lib\\site-packages', 'C:\\Python39\\lib\\site-packages\\win32', 'C:\\Python39\\lib\\site-packages\\win32\\lib', 'C:\\Python39\\lib\\site-packages\\Pythonwin'] Server time: Sun, 23 Jan 2022 12:04:18 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: C:\Users\Maxwell\Desktop\Django\WebApp\Blog\templates\ Blog\index (Source does not exist) django.template.loaders.app_directories.Loader: C:\Python39\lib\site-packages\django\contrib\admin\templates\ Blog\index (Source does not exist) django.template.loaders.app_directories.Loader: C:\Python39\lib\site-packages\django\contrib\auth\templates\ Blog\index (Source does not exist) App/views.py from django.http import HttpResponse from django.shortcuts import render # Create your views here. def index(request,name): return HttpResponse(f'Hello {name}') def html(request): return … -
Deploy django project with more application using Apache
I'm trying to deploy a website using Apache and mod_wsgi, my project has more applications Project/ ├── Article │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── Client │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── ManagementSoftware │ ├── __init__.py │ ├── __pycache__ │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── static │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── Order │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── Sites │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── Supplier │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ … -
Is it possible to pass extra value with celery AsyncResult while celery task is in any state (RUNNING, PENDING, SUCCESS) in Django?
Actually, I wanted to receive the dictionary while the celery task is in running state For example: task = app.AsyncResult(task_id) response_data = task.get() print(response_data['key']) -
django rest framework and swagger : invalid literal for int() with base 10: 'None'
When I use rest_framework_swagger, I face some errors. as you can see it's more about library and port. is there something wrong about my other views? how can i fix it? here is my code : from rest_framework_swagger.views import get_swagger_view from . import views schema_view = get_swagger_view(title='Pastebin API') urlpatterns = [ path('', schema_view), ] and I face this is error which is about type of port which is none: Traceback (most recent call last): File "/home/alireza/anaconda3/lib/python3.7/site-packages/asgiref/sync.py", line 482, in thread_handler File "/home/alireza/anaconda3/lib/python3.7/site-packages/django_elasticsearch_dsl_drf/viewsets.py", line 160, in __init__ self.document._get_using() File "/home/alireza/anaconda3/lib/python3.7/site-packages/elasticsearch_dsl/connections.py", line 109, in get_connection return self.create_connection(alias, **self._kwargs[alias]) File "/home/alireza/anaconda3/lib/python3.7/site-packages/elasticsearch_dsl/connections.py", line 84, in create_connection conn = self._conns[alias] = Elasticsearch(**kwargs) File "/home/alireza/anaconda3/lib/python3.7/site-packages/elasticsearch/client/__init__.py", line 203, in __init__ self.transport = transport_class(_normalize_hosts(hosts), **kwargs) File "/home/alireza/anaconda3/lib/python3.7/site-packages/elasticsearch/client/utils.py", line 52, in _normalize_hosts if parsed_url.port: File "/home/alireza/anaconda3/lib/python3.7/urllib/parse.py", line 169, in port port = int(port, 10) Exception Type: ValueError at /swagger/ Exception Value: invalid literal for int() with base 10: 'None' ```. can you help me? -
Django template websocket URL tag
I am trying to load ws_urlpatterns to template with tags: routing.py from django.urls import path from .consumers import WSConsumer ws_urlpatterns = [ path('ws/some_url/', WSConsumer.as_asgi(), name="ws"), ] <div class="container"> <div class="row"> <div class="col-6 mx-auto mt-5"> <h1>{{ text }}</h1> </div> </div> </div> <script> let socket = new WebSocket('ws://localhost:8000/ws/some_url/'); const h1 = document.querySelector('h1'); socket.onmessage = function(event){ let data = JSON.parse(event.data); h1.innerText = data.message; } </script> I tried let socket = new WebSocket("{% url 'ws' %}"); but I got Reverse for 'ws' not found. 'ws' is not a valid view function or pattern name. I am new to Django channels, will be very glad if you can give me a hand. -
How interdependent db calls handled in transaction.atomic
I have two DB calls inside the transaction.atomic() Sample codes with transaction.atomic(): result1, created = SomeModel.objects.get_or_create(**somedata) if not created: flag = SomeOtherModel.objects.filter(somemodel=result1).exists() if flag: result1.some_attr = value1 if flag else value2 result1.save() AFAIK about the transaction.atomic when my python codes do not cause an exception, so all the DB calls will be committed on the database. If any of the exceptions raised inside the block, no database operation will be committed to the database. So how is this thing handled when the DB call of one is used in the python logic to make other DB operations? Didn't find this species in the documentation, if any good source, please mention it.