Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
call another viewset method from same viewset
I am writing a simple django app where all my apis are based on class based viewsets. I've the following viewset with 2 methods(2 different api calls) but in one of the apis i wanted to access another api's method. class TestViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet): queryset = Model.objects.all() serializer_class = MSerializer @action(detail=True, methods=["PUT"], name="viewone") def viewone(self, request, pk): try: <logic> except Exception as e: raise("error") @action(detail=True, methods=["PUT"], name="viewtwo") def viewtwo(self, request, pk): try: viewone = self.as_view({'put': 'viewone'})(request, pk=pk) except Exception as e: print(e) raise("error") the view set two throws me the following AttributeError: This method is available only on the class, not on instances. what am i doing wrong here? -
Django not recognizing empty url config
Sorry, beginner here. I was following this tutorial https://www.youtube.com/watch?v=JD-age0BPVo on py/django and managed to get the webserver running. However, it simply displays the default page: when in my urls.py, I have the default page set. urls.py from django.contrib import admin from django.urls import include from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('', include('api.urls')) ] and in api.urls: from django.urls import path from .views import main urlpatterns = [ path('', main) ] and finally in api.views.py I have main(request) from django.shortcuts import render from django.http import HttpResponse # Create your views here. def main(request): return HttpResponse("hello") My project directory looks like this in case it helps: -
How to implement multiple subcategory selection in Django models
I want to implement multiple choice field in model for example i have table named as Category and Subcategory and what i want when i add subcategory i can select multiple Categories using checkbox and categories are stored in a list. NOTE : Categories will come dynamic -
How to achieve multiple sorting levels in Django ORM Queries
On the below Posts model , I need to sort the posts by both date and likes. the results should be last 24 hr posts ,sorted by likes , then the next day posts sorted by likes , it goes on.. class Posts(models.Model): comment_text= models.CharField(max_length=1000) date = models.DateTimeField(default=timezone.now()) likes = models.IntegerField(default=0) views.py latest=Posts.objects.filter().order_by(-date,-likes) the above query is not giving the desired results , let us say if there are two posts created at 07/06/2021 at 1 pm which has 3 likes and another one at 1:30 pm which as 1 like. Then the post created at 1:30 pm with 1 like comes on top instead of the post at 1 pm with 3 likes -
How to solve AttributeError: 'NoneType' object has no attribute 'encode' in Django
I tried to give validation to the give form in the HTML file using JAVASCRIPT and also check the email is available or not in the database table using AJAX.Also imported sha256 from hashlib.But I got an error like this. I did not understand why this error happens.Can anyone suggests a solution for this problem. Internal Server Error: /User/Registration/ Traceback (most recent call last): File "C:\PYTHON\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\PYTHON\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Project\salon\user\views.py", line 214, in userregister epassword = sha256(upassword.encode()).hexdigest() AttributeError: 'NoneType' object has no attribute 'encode' HTML file: <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="UTF-8"> <title>User Registration</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link href="{% static 'styles/style.css' %}" rel="stylesheet"/> <script type="text/javascript" language="javascript"> function getsid(str) { print(str) if(window.XMLHttpRequest) { xmlhttp= new XMLHttpRequest(); } xmlhttp.onreadystatechange=function() { if(xmlhttp.readystate==4 && xmlhttp.status==200) { document.getElementById("lemail").innerHTML= xmlhttp.responseText; } } xmlhttp.open("GET","{% url 'checkemail' %}?id="+str,true); xmlhttp.send(null); } </script> </head> <body> <section class="sreg" id="sreg"> <div class="container-fluid"> <div class="htop"> <h4>User <span>Register Form</span></h4> </div> <div class="row"> <div class="col-12"> <form method="POST" name="contact" action="{% url 'userregister' %}"> {%csrf_token%} <div class="form-row"> <div class="form-group col-md-6"> <label for="fname">First Name</label> <input type="text" class="form-control" id="fname" name="fname" placeholder="First Name"> <span id="lfname"></span> </div> <div … -
Can't create user post in django
I'm trying to create a post using the User profile instance. The post is saved but there is no object created in the database In my user_blog app i have created Profile model for user blog_users/models.py from django.db import models from django.conf import settings from django.utils import timezone from django.urls import reverse from django.utils.text import slugify # Create your models here. class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile_user', on_delete=models.CASCADE) bio = models.CharField(max_length=500, blank=True) url = models.URLField(max_length=200, blank=True, null=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics/', blank=True, null=True) created_date = models.DateTimeField(auto_now_add=True) slug = models.SlugField(unique=True, null=False) def save(self, *args, **kwargs): self.slug = slugify(self.user.username) return super().save(*args, **kwargs) I have created Post model in separate app (posts) posts/models.py from django.db import models from django.conf import settings from django.utils import timezone from django.urls import reverse from django.utils.text import slugify from ckeditor.fields import RichTextField from blog_users.models import Profile # Create your models here. class Post(models.Model): profile = models.ForeignKey(Profile, related_name='user_post', on_delete=models.CASCADE) title = models.CharField(max_length=250, blank=True) content = RichTextField(blank=True, null=True) date_created = models.DateTimeField(default=timezone.now) slug = models.SlugField(unique=True, null=False) def __str__(self): return f"{self.profile.user.username} | post" posts/views.py @login_required(login_url='account_login') def create_post(request): current_user = Profile.objects.get(user=request.user) form = CreatePost(instance=current_user) if request.method == "POST": form = CreatePost(request.POST, instance=current_user) if form.is_valid(): form.save() print('success') return redirect(f"/blog_users/{request.user}") context = { 'form': form … -
How to populate django select form from bootstrap
I'm currently having a problem in terms of populating the select tag from bootstrap 5. When I'm using {{form.as_p}} all options in select tag are shown but not with bootstrap. here is my forms.py and models.py: models.py class Category(models.Model): class Meta: verbose_name = _('Category') verbose_name_plural = _('Categories') ordering = ['id'] name=models.CharField(max_length=255,verbose_name=_('Category')) def __str__(self): return self.name def get_absolute_url(self): return reverse('home') class Post(models.Model): class Meta: verbose_name = _('Post') verbose_name_plural = _('Posts') ordering = ['id'] title= models.CharField(max_length=255,verbose_name=_('Post Title')) header_image= models.ImageField(null=True,blank=True,upload_to='images/',verbose_name=_('Image')) title_tag= models.CharField(max_length=255, verbose_name=_('Tag')) author=models.ForeignKey(User,on_delete=models.CASCADE,verbose_name=_('Author')) body=RichTextField(blank=True,null=True,verbose_name=_('Description')) status = models.BooleanField(default=False,verbose_name=_('Private')) post_date=models.DateTimeField(auto_now_add=True,verbose_name=_('Date Posted')) category= models.CharField(max_length=255,verbose_name=_('Category')) likes= models.ManyToManyField(User,related_name='blog_posts',verbose_name=_('Likes')) def total_likes(self): return self.likes.count() def __str__(self): return self.title + '|' + self.author def get_absolute_url(self): return reverse('home',args=(str(self.id))) forms.py choices=Category.objects.all().values_list('name','name') choice_list=[] for item in choices: choice_list.append(item) class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title','title_tag','author','body','category','header_image','status') widgets= { 'title':forms.TextInput(attrs={'class':'form-control'}), 'title_tag':forms.TextInput(attrs={'class':'form-control'}), 'author':forms.TextInput(attrs={'class':'form-control','value':'','id':'author_id','type':'hidden'}), 'category':forms.Select(choices=choices,attrs={'class':'form-select'}), 'status':forms.CheckboxInput(attrs={'class':'form-check-input'}), 'body':forms.Textarea(attrs={'class':'form-control'}), } and here is my html template file: <div class="form-floating"> <select name="category" class="form-select" id="id_category" aria-label="Floating label select example" maxlength="255"> </select> <label for="floatingInput">Category</label> </div> I have 3 inputs at the moment coding,news and sports but they only show when I use the {{ form.as_p }} template -
django rest framework - update ModelViewSet class variable
I have a ModelViewSet that looks like the following class BusinessViewSet(ModelViewSet): filterset_class = BusinessFilter serializer_class = BusinessSerializer ordering_fields = [ "source", "xl_source", "company_name", "contact_title", "category", "contact_name", "description", "tags", "business_hours", "location", "website", "phone", "email", "social_media", "address", "is_ecommerce", "is_verified", "ownership", "supplemental_information", "products", "location_street", "location_city", "location_state", "location_zip", ] def get_queryset(self): referer = self.request.META["HTTP_REFERER"] try: source = referer.split("source=")[1] except Exception as e: print(e) source = None if source == None: queryset = Business.objects.all() elif source == 'SBASpecial': queryset = SBABusiness.objects.all() self.serializer_class = SBABusinessSerializer self.filterset_class = SBABusinessFilter self.ordering_fields = [ 'name_and_trade_of_firm', 'contact', 'address_city', 'capabilities_narrative', 'ownership_self_certs', 'email_address', 'www_page_url', 'phone_number', 'year_established', 'keywords', 'naics_codes', ] else: queryset = Business.objects.filter(xl_source=source) return queryset As you can see, if the source is SBASpecial, I try to change the class variables serializer_class and ordering_fields inside get_queryset. Obviously this is not working. I've looked at the django rest framework documentation and there isn't anything there that can help me with this problem. What can I do? Any help is appreciated. Thanks in advance -
How to connect already existing PostgreSQL database with Heroku?
I deployed my app using Heroku, but while deploying Heroku created a new PostgreSQL database. Now I need to change that to my already existing PostgreSQL database(I am using Django framework in VsCode), which I used while running in the localhost. Does anyone have an idea, please help me with this?. -
Django form not getting the select field selection. Dropdown dependant
so, I have a very complex way in wich I ask a database within my own project for the State, County and Neighborhood throuh Ajax, with the help of the forms.py, now, I have it for registering a room (which is related to these locations), and it goes through a CreateView, with this one I have no issues, but, when wanting to make a queryset to perform a search of my rooms and their respective locations, it just seems like it´s not picking up what is selected on the field, this I know because I asked it to print the request and it prints 'None', here is my code: models.py class PostRoom(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE,default=1,related_name='room_author') colonia = models.ForeignKey(Colonia, on_delete=models.SET_NULL, blank=True, null=True) cp = models.ForeignKey(CP, on_delete=models.SET_NULL, blank=True, null=True) municipio = models.ForeignKey(Municipio, on_delete=models.SET_NULL, blank=True, null=True) estado = models.ForeignKey(Estado, on_delete=models.SET_NULL, blank=True, null=True) the CreateView where everything works perfectly: class RoomSubmitCreateView(LoginRequiredMixin, CreateView): model = PostRoom form_class = PostRoomForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) The ajax code through which I send the selected fields to my location.views.py: <script> $("#id_estado").change(function () { var url = $("#roomForm").attr("load-municipios"); // get the url of the `load_cities` view var estadoId = $(this).val(); // get the selected country … -
How to use dropify in image/file fields in Django admin?
I want to use dropify for image/file upload in Django admin. But I have not found any usage/tutorial how to use it in Django admin. Is there a way how to do it ? -
Django-Tinymce not loading
I have included django-tinymce module in my django 3.1 project. However, the tinymce editor disappeared from my pages and I don't know why. When I run the project in my localhost I get a 404 on init_tinymce.js, a folder that is not in my project and not specified in the django-tinymce project. I hardly touched anything but it suddenly did not show on my pages. Here is the log from my console: [08/Jun/2021 08:32:26] "GET /letter_head_edit/1/ HTTP/1.1" 200 14367 [08/Jun/2021 08:32:26] "GET /static/django_tinymce/init_tinymce.js HTTP/1.1" 404 179 [08/Jun/2021 08:32:26] "GET /static/django_tinymce/init_tinymce.js HTTP/1.1" 404 179 Here is my settings.py file config: TINYMCE_JS_URL = os.path.join(STATIC_URL, "js/tinymce/tinymce.min.js") TINYMCE_JS_ROOT = os.path.join(STATIC_ROOT, "js/tinymce") TINYMCE_SPELLCHECKER = True TINYMCE_DEFAULT_CONFIG = { "height": "500px", "width": "auto", "menubar": "file edit view insert format tools table help", "plugins": "advlist autolink lists link image charmap print preview anchor searchreplace visualblocks code " "fullscreen insertdatetime media table paste code help wordcount spellchecker", "toolbar": "undo redo | bold italic underline strikethrough | fontselect fontsizeselect formatselect | alignleft " "aligncenter alignright alignjustify | outdent indent | numlist bullist checklist | forecolor " "backcolor casechange permanentpen formatpainter removeformat | pagebreak | charmap emoticons | " "fullscreen preview save print | insertfile image media pageembed template link … -
Python, django: I made some codes but I think it takes time to perform. Is python slow? or my codes slow?
I would like to check and improve the codes I wrote because it takes time... slow probably I could wrote better... here are the codes at views.py def price_detail(request): if request.method == "POST": flight_date = request.POST.get('flight_date') direction = request.POST.get('direction') suburb = request.POST.get('suburb') no_of_passenger = request.POST.get('no_of_passenger') def price_cal(): if direction == 'Drop off To airport': return int(suburbs.get(suburb)) + ((int(no_of_passenger) * 10) - 10) else: return int(suburbs.get(suburb)) + (int(no_of_passenger) * 10) price_cal() price = str(price_cal()) p = Post(flight_date=flight_date, direction=direction, suburb=suburb, no_of_passenger=no_of_passenger, fare=price) p.save() data = { 'flight_date': flight_date, 'direction': direction, 'suburb': suburb, 'no_of_passenger': no_of_passenger, 'price': price, } message = ''' Flight date: {} Direction: {} Suburb: {} No of passenger: {} Price: {} '''.format(data['flight_date'], data['direction'], data['suburb'], data['no_of_passenger'], data['price']) send_mail(data['flight_date'], message, '', ['sungkam3@gmail.com']) return render(request, 'basecamp/price_detail.html', {'flight_date': flight_date, 'direction': direction, 'suburb': suburb, 'no_of_passenger': no_of_passenger, 'price': price}, ) else: return render(request, 'basecamp/price_detail.html', {}) User put some information on html and inquiry about the price... views get objects from templates, work out the price and after that, save all the information into database and email to me the details user inquiried. After all this donw, views.py send information to other page (html) to show the results to User. it works fine... but the problem is … -
How to use filecmp.cmp() in Django for InMemoryUploadedFile objects?
The filecmp.cmp() method takes two arguments, path of file1 and path of file2. InMemoryUploadedFile objects won't have any path associated with them. So, what is the simplest method to compare two InMemoryUploadedFile objects? Thanks -
To display a dropdown and table/ list of the related content, Django SQL database
This is what I currently have, the first dropdown is faculty, second is the module. This is created with ajax. Now, I would like to create a table that shows all the modules and their respective details when I select a specific faculty. Let's say I selected Physics the table content will now show all the modules and their semester availability and credit unit. The dropdown and the content of the table have to be dynamic and change according to what is selected. The model would contain column faculty, modules, semester availability, and credit unit. I would appreciate any resources that will guide me in this! Thank you! -
Modifying a dropdown menu option in a form Django
I have a dropdown menu that i'm using to fill a field on a form, but, as i'm just starting with django and html, i'm using another form to edit and update the data of the previous form. But i cant make the dropdown menu to work on that second form. The model: class Orden(models.Model): STATUS = ( ('En espera', 'En espera'), ('En proceso', 'En proceso'), ('Terminado', 'Terminado'), ('Entregado', 'Entregado'), ) num_orden = models.CharField(max_length=20, default='') fechain = models.CharField(max_length=30, default='') fechaout = models.CharField(max_length=30, default='') instrumento = models.CharField(max_length=30, default='') marca = models.CharField(max_length=20) referencia = models.CharField(max_length=30, default='') serial = models.CharField(max_length=15, default='') encargado = models.CharField(max_length=50, default='') abono = models.CharField(max_length=15, default='') procesos = models.TextField(default='') estado = models.CharField(max_length=50, null=True, choices=STATUS) # <--- This one client = models.ForeignKey(Cliente, on_delete=models.CASCADE, default='', related_name="client") The view related to the first form: def ordenfill(request, client_id): if request.method == 'POST': orden = ordenForm(request.POST) if orden.is_valid(): orden.instance.client_id = client_id init = orden.save() return redirect('ordenview', id=init.id) else: orden = ordenForm() client = Cliente.objects.get(id=client_id) context = { 'orden': orden, 'client': client, } return render(request, 'ordenfill.html', context) The template part asociated to that dropdown menu: <form method="POST" class="post-form" action="{% url 'ordenfill' client.id %}"> {% csrf_token %} <div class="container"> <br> . . . <div class="form-group row"> <label … -
I would like to pass an array in django
I would like to pass an array in django {% include '/blocks/block-products-carousel.html' with groups= [ {title: 'All', active: true}, {title: 'Power Tools', active: false}, {title: 'Hand Tools', active: false}, {title: 'Plumbing', active: false}, ], -
Linux partition sizes for a locally-deployed (via docker) django web application with postres database
I plan to deploy, via docker, a django web application with postgres database in a local machine within a local network. I believe that docker volumes live in the /var/lib/docker/volumes directory of the host computer. My question is: I suppose this means that when I prepare the host machine, I will have to allot a large portion to the root directory? Are there ideal sizes for the partitions of the host machine? (root, swap, home) This may sound trivial, but I would like to get confirmation before I start working on the deployment. Thanks so much. -
How can i group by all data according to model in DRF?
Currently, I am working on a DFR project where can successfully get all data but i need some modify with the json data. Here Is the code class PermissionSerializers(serializers.ModelSerializer): class Meta: model = Permission fields = ['id', 'name', 'codename'] def to_representation(self, instance): return { 'model': instance.content_type.name, 'data' :{ 'id': instance.id, 'name': instance.name, 'codename': instance.codename, } } And i get this JSON format, { "next": "http://127.0.0.1:8000/en/ga/api-version/common/admin/permissions/?page=4", "previous": "http://127.0.0.1:8000/en/ga/api-version/common/admin/permissions/?page=2", "total": 33, "page": 3, "page_size": 10, "results": [ { "model": "user", "data": { "id": 25, "name": "Can add user", "codename": "add_user" } }, { "model": "user", "data": { "id": 29, "name": "Admistrative Access", "codename": "admin_access" } }, But I want to modify with something like this which has model name on top and then all available data inside a dictionary: { "model": "user", "data": { "id": 26, "name": "Can change user", "codename": "change_user" }, { "id": 25, "name": "Can add user", "codename": "add_user" }, }, -
How to change Django project settings dynamically for production and staging servers
In my current project, I have two servers: production and staging. The staging server uses the default MySQL Django connector. The production server uses a custom connector for MariaDB. The information from the database is retrieved through raw queries. I can't use ORM for this project. Both staging and production are connected to the project's git repository. If I push a commit with the specific settings for the staging server, when I git pull from production server it won't work and vice versa. I need to create a mechanism that detects if the server is production or staging and based on that it executes the specific code for MariaDB or MySQL. The conflicting files are: settings.py (no explanations needed) and db.py (contains all the logic of the database, here are implemented the functions that are responsible for making queries to the database). STAGING SERVER db.py (truncated): #!/usr/bin/python from django.db import connection import re from collections import namedtuple def get_genome_id_from_start_value(start): results = [] cursor = connection.cursor() cursor.execute("SELECT record_id FROM `db-dummy`.g_info WHERE start = %s", ('{}%'.format(start),)) columns = [column[0] for column in cursor.description] results = [] for row in cursor.fetchall(): results.append(dict(zip(columns, row))) return results[0]['record_id'] settings.py (truncated): DATABASES = { 'default': { 'ENGINE': … -
Django login with rest framework
While working with the rest framework and frontend native client, I need to log in with both native clients and directly to the API endpoint for development and testing purpose. Native client login requires token authentication and direct API login requires session authentication. But if I put both in settings.py as default I get csrf error from the native client and if I remove session auth I am not able to login directly to API (I can still log in to the admin console). My settings .py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication' ], 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ) } What can be done to log in from both for development and testing? Any help? -
WebSocket drops connection django channels redis docker compose
tried to connect redis with my app on docker compose and django. It starts but when i try to use websockets it falls with exception: web_1 | WebSocket DISCONNECT /comments/3/ [172.23.0.1:57474] web_1 | Exception inside application: [Errno -3] Try again web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.9/site-packages/channels/staticfiles.py", line 44, in __call__ web_1 | return await self.application(scope, receive, send) web_1 | File "/usr/local/lib/python3.9/site-packages/channels/routing.py", line 71, in __call__ web_1 | return await application(scope, receive, send) web_1 | File "/usr/local/lib/python3.9/site-packages/channels/sessions.py", line 47, in __call__ web_1 | return await self.inner(dict(scope, cookies=cookies), receive, send) web_1 | File "/usr/local/lib/python3.9/site-packages/channels/sessions.py", line 254, in __call__ web_1 | return await self.inner(wrapper.scope, receive, wrapper.send) web_1 | File "/usr/local/lib/python3.9/site-packages/channels/auth.py", line 181, in __call__ web_1 | return await super().__call__(scope, receive, send) web_1 | File "/usr/local/lib/python3.9/site-packages/channels/middleware.py", line 26, in __call__ web_1 | return await self.inner(scope, receive, send) web_1 | File "/usr/local/lib/python3.9/site-packages/channels/routing.py", line 150, in __call__ web_1 | return await application( web_1 | File "/usr/local/lib/python3.9/site-packages/channels/consumer.py", line 94, in app web_1 | return await consumer(scope, receive, send) web_1 | File "/usr/local/lib/python3.9/site-packages/channels/consumer.py", line 58, in __call__ web_1 | await await_many_dispatch( web_1 | File "/usr/local/lib/python3.9/site-packages/channels/utils.py", line 51, in await_many_dispatch web_1 | await dispatch(result) web_1 | File "/usr/local/lib/python3.9/site-packages/channels/consumer.py", line 73, in dispatch web_1 | … -
Celery showing django's runserver logs instead of celery logs
I have a dockerized Django project and everything works fine because Celery keeps displaying runserver logs instead of celery logs. Here's my docker-compose.yml: version: "3.8" services: api: container_name: api restart: always build: . networks: - API_NETWORK depends_on: - redis - database ports: - "8000:8000" env_file: - ./.env command: bash -c /entrypoint.sh database: container_name: postgres restart: always image: postgres:latest networks: - API_NETWORK volumes: - pgdata:/var/lib/postgresql/data/ environment: - POSTGRES_HOST_AUTH_METHOD=trust redis: container_name: redis image: redis:latest networks: - API_NETWORK celery: container_name: celery restart: always build: . networks: - API_NETWORK depends_on: - api - redis - database env_file: - ./.env command: celery -A dir_name worker -l debug celery-beat: container_name: celery-beat restart: always build: . networks: - API_NETWORK depends_on: - api - redis - database env_file: - ./.env command: celery -A dir_name beat -l debug --scheduler django_celery_beat.schedulers:DatabaseScheduler volumes: pgdata: networks: API_NETWORK: name: API_NETWORK driver: bridge ...and here's my Dockerfile: FROM python:3.9-slim-buster ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 RUN apt-get update \ && apt-get install -y --no-install-recommends \ build-essential git gcc python3-dev \ && python -m pip install --upgrade pip RUN mkdir /dir_name WORKDIR /dir_name COPY . /dir_name RUN pip install -r ./requirements.txt RUN chmod +x ./entrypoint.sh ENTRYPOINT ["sh", "./entrypoint.sh"] The issue is instead of getting proper … -
Undefined Path In Django
I am working on a django application and everything is working fine except I am getting an error Not Found: /about-us/undefined when I visit the url 127.0.0.1:8000/about-us/ With a view as below the error is not showing: def about_us(request): if request.method == 'GET': return HttpResponse('<h1>About Page</h1>') But when I render an HTML template as shown below then the error shows def home(request): if request.method == 'GET': return render(request, 'website_files/index.html', {'home' : True}) website.urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('about-us/', views.about_us, name="about-us"), path('why_us/', views.why_us, name="why_us"), path('out_team/', views.out_team, name="out_team"), path('it_solutions/', views.it_solutions, name="it_solutions"), path('it_solutions/it_management_services', views.it_management_services, name="it_management_services"), path('it_solutions/cyber_security_services', views.cyber_security_services, name="cyber_security_services"), path('it_solutions/software_dev_services', views.software_dev_services, name="software_dev_services"), path('it_solutions/networking_and_cloud_services', views.networking_services, name="networking_and_cloud_services"), path('it_solutions/it_consultations', views.consulting_services, name="it_consultations"), path('it_solutions/data_backup_and_recovery', views.backup_services, name="data_backup_and_recovery"), path('it_solutions/email_hosting', views.email_hosting, name="email_hosting"), path('it_solutions/web_hosting', views.web_hosting, name="web_hosting"), path('stories', views.blogging, name="stories"), path('contact_us', views.contact, name="contact_us"), path('find_out', views.find_out, name="find_out"), path('request_quote', views.get_quote, name="request_quote"), ] main urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # path('admin/', admin.site.urls), path('', include('website.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) What am I missing? You assistance will greatly appriciated. -
Local Django server is incredibly slow
I am trying to connect with a Django dev server running locally. HTTP requests take a minute or more! Looking for a way to speed it up. According to Chrome network monitor, Waiting (TTFB) on one of the URLs is 5.5 minutes. Similarly bad performance occurs using Firefox screenshot of chrome network monitor Server side error/logs: HTTP GET /sources/ 200 [151.03, 127.0.0.1:49420] <generator object source_list.<locals>.<genexpr> at 0x7fccf6a90350> Application instance <Task pending coro=<AsgiHandler.__call__() running at .../djangoenv377/lib/python3.7/site-packages/channels/http.py:192> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at .../.pyenv/versions/3.7.7/lib/python3.7/asyncio/futures.py:351, <TaskWakeupMethWrapper object at 0x7fccf5c4bf50>()]>> for connection <WebRequest at 0x7fccf5f41690 method=GET uri=/sources/ clientproto=HTTP/1.1> took too long to shut down and was killed. <generator object source_list.<locals>.<genexpr> at 0x7fccf6a90250> HTTP GET /sources/ 200 [332.32, 127.0.0.1:49846] When refreshing, these two lines happen pretty instantaneously: HTTP GET /sources/ 200 [332.32, 127.0.0.1:49846] <generator object source_list.<locals>.<genexpr> at 0x7fccf695e350> And it takes a while for the Application instance <Task pending coro=<AsgiHandler.__call__()... error to occur. Environment info: OS: Ubuntu 20.04.2 LTS Python: 3.7.7 channels==2.4.0 channels-redis==2.4.2 celery==4.4.7 redis==3.5.3 Twisted==20.3.0 websocket-client==0.57.0 uWSGI==2.0.18 daphne==2.4.1 defusedxml==0.6.0 Django==2.2.7 django-celery==3.3.1 django-celery-results==1.2.1 django-channels-panel==0.0.5 djangorestframework==3.11.0 asgi-redis==1.4.3 asgiref==3.3.1 async-timeout==3.0.1 I've tried mixing and matching different pip package versions with no success. I've tried using debug=False with no success. The annoying thing is that this application works as expected …