Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
buffer size in Django using uWSGI and Nginx
i have a test project which made using: Django 3.2.6 uWSGI 2.0.19.1 nginx/1.18.0 (Ubuntu) i was trying to implement SSE 'Server Sent Events' ,to push the some data to a user, i was able to make send the data, but i face a problem with the buffer size. in other words, the data i was trying to send was small data like this below: def sse_test_data(request): def event_stream(): while True: sleep(.2) yield f"data: {datetime.time(datetime.now())}\n\n" return StreamingHttpResponse(event_stream(), content_type='text/event-stream') and i had to wait the buffer size to reach a specific size 'limit' in order to send 'flush' the data. when i was trying to inspect the buffer size should be reached to be sent i found that it was 6000/characters so any data its size below that size it waits another data in the buffer till the whole data size reach 6000/characters and then it is sent as a block i am really new with SSE and buffering as all, i tried to read about , in order to get around this issue but i couldn't have something to solve this issue so my question is, How to control the buffer size 'make it less or more' ? How to force … -
Accessing a ManyToManyField's contents for a Django template
I'm making a low-spec e-bay clone, I'm trying to implement a watchlist function but the problem is I can't access the ManyToManyField in the Watchlist model so I can use the contents of the field in the template I'm using. To display each user's watchlist to them, so far I only get this result: but I need to get a result like so: Code I'm using: watchlist.html {% extends "auctions/layout.html" %} {% load static %} {% block title %} {{name}}'s Watchlist {% endblock %} {% block body %} <h2>{{name}}'s Watchlist</h2> {% for listing in watchlist %} <div class='listing'> <h3>{{ listing.list_title}}</h3> {% if listing.img_url == "" %} <a href='#'><img src="{% static 'auctions/img404.png' %}" class='img-fluid'></a> {% else %} <a href='#'><img src="{{ listing.img_url }}" class="img-fluid" alt='image of {{ listing.list_title }}'></a> {% endif %} <p> {{ listing.desc }} </p> <p> Current Bid: ${{ listing.start_bid }} </p> {% if listing.category == "" %} <p>Category: No Category Listed</p> {% else %} <p>Category: {{ listing.category }}</p> {% endif %} <a href='#' class='btn btn-primary' id='go'>Go To Listing</a> </div> {% endfor %} {% endblock %} views.py def render_listing(request, title): if request.method == "POST": form = BidForm(request.POST) bid = int(request.POST['new_bid']) listing = Auction_Listing.objects.get(list_title=title) comments = Auction_Comments.objects.all().filter(auction_id=listing) if bid < listing.start_bid: … -
how to add lastmod field in index sitemap django
I need to add lastmod attribute to sitemap index. And it looks like django.contrib.sitemaps.views.index doesn't include lastmode though Here is my sitemap.xml: <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" <sitemap> <loc>localhost:8000/sitemap-pages.xml</loc> </sitemap> </sitemapindex> my urls.py sitemaps_pages = { 'pages': sitemaps.PageViewSitemap, 'life': sitemaps.LifeViewSitemap, 'lifes': sitemaps.LifesSitemap, 'novosti': sitemaps.NewsViewSitemap, 'novost': sitemaps.NewsSitemap, 'catalog': sitemaps.CatalogViewSitemap, 'categories': sitemaps.CategorySitemap, 'regions': sitemaps.RegionSitemap, 'times': sitemaps.TimeSitemap, 'material': sitemaps.MaterialSitemap, 'products': sitemaps.ProductsSitemap, } path('sitemap-<section>.xml', sitemap, {'sitemaps': sitemaps_pages}, name='django.contrib.sitemaps.views.sitemap'), path('sitemap.xml', index, {'sitemaps': sitemaps_pages}, name='django.contrib.sitemaps.views.sitemap'), sitemaps.py class ProductsSitemap(sitemaps.Sitemap): protocol = 'https' try: priority_filter = strip_tags(Info.objects.get(name='priority_filter').value) frequency_filter = strip_tags(Info.objects.get(name='frequency_filter').value) except Exception: priority_filter = '0.5' frequency_filter = 'daily' priority = priority_filter changefreq = frequency_filter limit = 1000 def items(self): return Product.objects.all() def location(self, item): return str(item.url) def lastmod(self, item): if item.url == '/': return Product.objects.latest('updated_at').updated_at else: return item.updated_at How do i solve the problem? -
Django Rest Framework: How to randomize Queryset while keeping the pagination and search functionality?
Premise: Imagine I have 100 items in the database and each time the user opens the application I want to display 10 random items, and as the user scrolls down more items get added. I started by creating a "ListAPIView" using a "PageNumberPagination" class: class ItemListView(generics.ListAPIView): queryset = Item.objects.all() serializer_class = ItemListSerializer pagination_class = ItemListPagination class ItemListPagination(PageNumberPagination): page_size = 20 This will give me always the same 10 items, so to randomize it I overwrote the "get_queryset" method and used a seed to randomize the queryset. class ItemListView(generics.ListAPIView): serializer_class = ItemListSerializer pagination_class = ItemListPagination def get_queryset(self): objects = list(Item.objects.all()) seed = self.request.GET.get('seed') # get the seed from the request query params random.seed(seed) # set seed random.shuffle(objects) # randomize objects random.seed() # reset seed return objects This works as expected but as soon as I introduce the SearchFilter backend, it errors out because is expecting a QuerySet and not a list. class ItemListView(generics.ListAPIView): serializer_class = ItemListSerializer pagination_class = ItemListPagination filter_backends = [SearchFilter] search_fields = ['name'] def get_queryset(self): objects = list(Item.objects.all()) # Get queryset and convert it to list seed = self.request.GET.get('seed') # get the seed from the request query params random.seed(seed) # set seed random.shuffle(objects) # randomize objects random.seed() # reset … -
Django Form validation(Not showing submitted Data)
As you see I can try to show only odd numbers on the screen. But after submission, the data not showing on the screen. Here the HTML code {% if form_submited %} <p>Field: {{ field }}</p> {% endif %} Here form.py file from django import forms from django.core import validators def even_or_not(value): if value%2==1: raise forms.ValidationError("Please Insert an Even Number!") class user_form(forms.Form): number_field=forms.IntegerField(validators=[even_or_not]) **Here views.py file ** from django.shortcuts import render,HttpResponse from home.models import Musician, Album from home import forms # Create your views here. def index(request): musician_list = Musician.objects.order_by('first_name') diction={'text_1':'This is a list of Musicians', 'musician':musician_list} return render(request,'index.html',context=diction) # return HttpResponse("this is homepage") def form(request): new_form=forms.user_form() diction={'test_form': new_form, 'heading_1': "This form is created using django library "} if request.method == "POST": new_form = forms.user_form(request.POST) diction.update({'test_form':new_form}) if new_form.is_valid(): diction.update({'field': new_form.cleaned_data['number_field']}) diction.update({'form_submited':"Yes"}) diction={'test_form': new_form,'heading_1':"This form is created using django librery "} return render(request, 'form.html',context=diction) -
how call a function with in the class in djagno shell
class Test: def m1(): pass def m2(): pass I have this class in the test.py(Django-Project) file how to call the m2 function in Django. shell. how to call this function in Django shell. I am trying like this: >> python manage.py shell >> from appname.filename import <class_name|function_name> But it thrown an error like this: ImportError: cannot import name <class_name|function_name>. anyone help me out with this. Thanks in advance. -
How my django model field can take value from a function defined in default
Having this model: class Settings(models.Model): INT = "int" FLOAT = "float" STRING = "string" JSON = "json" BOOLEAN = "boolean" VALUE_TYPES = ( (INT , "int"), (FLOAT , "float"), (STRING , "string"), (JSON , "json"), (BOOLEAN , "boolean"), ) def casted_value(self): if self.value_type == Settings.INT: return int(self.value) elif self.value_type == Settings.FLOAT: return float(self.value) elif self.value_type == Settings.STRING: return str(self.value) elif self.value_type == Settings.BOOLEAN: return bool(self.value) elif self.value_type == Settings.JSON: return json.dumps(self.value_type) key = models.CharField(max_length=100, null=True, blank=True) value = models.CharField(max_length=250, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) value_type = models.CharField(max_length=30, choices=VALUE_TYPES, default=casted_value) I am trying to give to my value_type field value based on the function casted_value. The concept is to return the value based on the type. When I am trying to migrate I come up with the error : TypeError: casted_value() missing 1 required positional argument: 'self' How is the right way to define my casted_value function in order the value_type field to take the value from this function? -
Django Download folder From Media
Django Download folder From Media In django Which method is user for Download complete directory to Client Machine from /media/ -
How do I fix the circular import in django
I am trying to simply put a 'Hello World' text on the server. And it brings an error. Project Urls.py : from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')) ] App Urls.py from django.urls import path from . import views urlpattern = [ path('', views.index,name = 'index') ] Views.py from django.shortcuts import render from django.http import HttpResponse def index(response): return HttpResponse('<h1>Hello World</h1>') The Error it tells me: The included URLconf in myapp/urls.py does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
post() missing 3 required positional arguments: 'user', 'user_obj', and 'code'
class CodeAPIView(APIView): def post(self,request,user,user_obj,code): code2 = request.data['code'] if code2 == code: AuthAPIView.login(self,request,user,user_obj) else: return Response("the code is wrong!") this is my view, and I get an error. How can I fix it? -
For loop in django retrieving all users instead of one and M2M field data output
I have 2 Issues in Django: Below are my codes, whenever I am using For loop in my Template, it is retrieving not one user data, but all users/profile data. but when I use request.user.profile.first_name only then it works, but I am in a situation where i need to retreive data from many-to-many field and I have to use For loop, which brings me to my 2nd question I need to use For loop in many-to-many field to retreive the data, but it is fetching for all users, please can you correct me where I am doing wrong? or is there any alternate method to retreieve data without using for loop (one user/profile only post logging-in) models.py class Department(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.CharField(max_length=200) departments = models.ManyToManyField(Department) views.py def profilepage(request): profiles = Profile.objects.all() departments = Department.objects.all() context = { 'profiles': profiles, 'departments': departments } return render(request, 'profile.html', context) profile.html {% for profile in profiles %} First Name: {{profile.first_name}} {% for department in departments %} Department: {{department.name}} {% endfor %} {% endfor %} -
Zappa Django one lambda per app in a monorepo
My Django REST API is composed of multiples apps, one app per resource like that: ├── core │ ├── settings.py │ ├── urls.py ├── customers │ ├── models.py │ ├── serializers.py │ ├── urls.py │ └── views.py ├── orders │ ├── models.py │ ├── serializers.py │ ├── urls.py │ └── views.py The settings of the app are all in core/settings.py. How can I tell zappa to deploy each app in a different lambda function and configure API Gateway to handle the routing for each app? -
while using django_filters how to remove or edit filters field from URL
while using django_filters the url generated like this: http://127.0.0.1:8000/reports/?EmployeeId=SW1&start_date=07%2F28%2F2021&end_date=07%2F31%2F2021 I dont want to display this things "?EmployeeId=SW1&start_date=07%2F28%2F2021&end_date=07%2F31%2F2021" only id number should display like http://127.0.0.1:8000/reports/1 -
No "Copy content from" wagtail-modeltranslation button
The "COPY CONTENT FROM [available translation languages]" button is not showing in the admin page editing interface. The package was installed properly, following official documentation. What can cause the issue and how to fix it? -
Azure SQL database connection error with django
For my Django web app I'm getting this error when running python manage.py makemigrations I have googles this problem can't able to find solution. Can someone help me to find solution to this problem, I'm a beginner programmer. File "D:\Azure\newDjango\.venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "D:\Azure\newDjango\.venv\lib\site-packages\sql_server\pyodbc\base.py", line 546, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid object name 'core_profilefeeditem'. (208) (SQLExecDirectW)") my settings.py file for database connection DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': '<db-name>', 'USER': '<db-username>', 'PASSWORD': '<db-passord>', 'HOST': '<servername>.windows.net', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', 'MARS_Connection': 'True', } } } my models.py where Profile page with user updates their images using rest_framwork as endpoint to show the user details and images from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager from django.conf import settings import uuid # Create your models here. def image_name_change(instance, filename): ext = filename.split('.')[-1] filename = f'{uuid.uuid4()}.{ext}' return filename # Changing the default authentication # ? https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#auth-custom-user class UserProfileManager(BaseUserManager): """Manager of User Profile""" def create_user(self, email, name, password=None): """Create new user profile""" if not email: raise ValueError("User must have an email address") … -
Rabbitmq installation throws dependency error
I installed rabbitmq version==3.18.19 and erlang = 23.2 win64 version respectively. After installation i give the rabbitmq plugins command : rabbitmq-plugins enable rabbitmq_management. It throws the below error. Any suggestions ? Enabling plugins on node rabbit@Rana-04: rabbitmq_management The following plugins have been configured: rabbitmq_management rabbitmq_management_agent rabbitmq_web_dispatch Applying plugin configuration to rabbit@COMPFIE2-04... Stack trace: ** (CaseClauseError) no case clause matching: {:error, {:missing_dependencies, [:eldap], [:rabbitmq_auth_backend_ldap]}} (rabbitmqctl 3.8.0-dev) lib/rabbitmq/cli/plugins/plugins_helpers.ex:107: RabbitMQ.CLI.Plugins.Helpers.update_enabled_plugins/4 (rabbitmqctl 3.8.0-dev) lib/rabbitmq/cli/plugins/commands/enable_command.ex:121: anonymous fn/6 in RabbitMQ.CLI.Plugins.Commands.EnableCommand.do_run/2 (elixir 1.10.4) lib/stream.ex:1325: anonymous fn/2 in Stream.iterate/2 (elixir 1.10.4) lib/stream.ex:1538: Stream.do_unfold/4 (elixir 1.10.4) lib/stream.ex:1609: Enumerable.Stream.do_each/4 (elixir 1.10.4) lib/stream.ex:956: Stream.do_enum_transform/7 (elixir 1.10.4) lib/stream.ex:1609: Enumerable.Stream.do_each/4 (elixir 1.10.4) lib/enum.ex:2161: Enum.reduce_while/3 {:case_clause, {:error, {:missing_dependencies, [:eldap], [:rabbitmq_auth_backend_ldap]}}} -
What is the best language when it comes to web developing?
So this has come across my mind alot, and I just want to know what the community thinks, because I am sure alot of people have had this same question as me. What do you guys think is the best web developing language when it comes to Security, simplicity, and effectiveness? I have heard React/Django is really good, but I am not really sure. Thanks in advance! :) -
How to add profile_pic field from another model in one model
I want to add profile_pic in Blog View page which is in my Profile model models.py class Profile(models.Model): user = models.OneToOneField(User,null=True, on_delete=models.CASCADE) bio = models.TextField() profile_pic = models.ImageField(null=True, blank=True, upload_to="images/profile/") class StudentBlogModel(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank=True,null=True) snippet = models.TextField(max_length=255) Views.py class BlogView(ListView): model = StudentBlogModel template_name = 'blog/home.html' context_object_name = "StudentBlogModel_list" paginate_by = 10 home.html <div class="container"> <div class="row"> <div class="col-lg-8"> <hr> <div class="profile-feed"> <div class="d-flex align-items-start profile-feed-item"> <img src="{{ }}" alt="profile" class="img-sm rounded-circle mb-5 mx-2"> <div class="ml-4"> <h6> {% if StudentBlogModel.author.first_name or StudentBlogModel.author.last_name%} <small class="card-title">{{StudentBlogModel.author.first_name|capfirst}} {{StudentBlogModel.author.last_name|capfirst}} </small> {% else %} <small class="card-title">{{StudentBlogModel.author.username|capfirst}}</small> {% endif %} <small class="ml-4 text-muted"><i class="mdi mdi-clock mr-1"></i> {{StudentBlogModel.post_date}}</small> </h6> <p> {{StudentBlogModel.title}} </p> what to write in src to get profile pic of particular author -
'NoneType' object has no attribute 'user' DRF
I have got two class based views. class AuthAPIView(APIView): def post_code(self, request, format=None): data = request.data username = data.get('username', None) password = username user = authenticate(username=username, password=password) if user is not None: if user.is_active: code = random_code_generator() user_obj = User.objects.get(username=username) Code.objects.create(phone_number=user_obj,code=code) now = datetime.now() current_time = now.strftime("%H:%M:%S") hour = current_time.split(":")[0] minute = current_time.split(":")[1] send(str(username),code,int(hour),int(minute)+2) return code def post(self,request,format=None): self.post_code(request) return Response("we have sent a code") class CodeAPIView(APIView): def post_code(self,request): data = request.data code2 = data.get('code', None) code = AuthAPIView.post_code(self,request) user = AuthAPIView.post_code(self,request).user if code2 == code: login(request, user) token = Token.objects.get(user=user) return Response(token.key) Code.objects.filter(phone_number=user_obj,code = code).delete() else: return Response("the code is wrong!") def post(self,request): self.post_code(request) here is my two views. I try to access user variable which it is stored in AuthAPIView.post_code in second class . user = AuthAPIView.post_code(self,request).user. where is my mistake? -
cannot import name 'S3' from 'froala_editor'
I am trying to generate a hash value for the folder on Amazon S3 with a package called "Froal_editor" in Django. I am following this tutorial. After everything is setup I installed Froala_Editor with command pip install django-froala-editor which successfully installed the package. I am facing the error cannot import name 'S3' from 'froala_editor when I am trying to import from froala_editor import S3 Any help in this regard would be highly appreciated. -
yaml field formatting display in Django admin pane
I want to display the field in yaml formatting in Django admin. Is there a way to achieve this? I tried exploring but didn't find much about yaml field in Django -
Django: To add a Link to custom page from Django admin form of a model
I want to add a link in admin/seo/seolist/1/change/ form which redirect to a custom html select_page.html and selects an input. -
Filter Dropdown based on Logged in User
I have models as below models.py user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) email = models.EmailField() role_id = models.ForeignKey("Role",on_delete=models.SET_NULL,null=True,related_name="role_id", default=1) lead_id = models.ForeignKey("Employee",on_delete=models.SET_NULL,null=True,related_name="parent_id" ,default=1) department_id = models.ForeignKey("Department" ,on_delete=models.SET_NULL,null=True,default=1) team_id = models.ForeignKey("Team" ,on_delete=models.SET_NULL,null=True,default=1) class Timesheet (models.Model): date = models.DateField(auto_now=True) Task = models.TextField(null=True) employee = models.ForeignKey("Employee",on_delete=models.SET_NULL,null=True ) supervisor = models.ForeignKey("Employee",on_delete=models.SET_NULL,null=True,related_name="supreviosr") my filters.py class TimesheetFilter(django_filters.FilterSet): class Meta: model = Timesheet fields= ['employee'] when a lead logged in , i want lead's employee's to be shown on django's filter dropdown box (this where i am stuck) 2.based on selected employees filter a table(was able to achieve this) looked at this How do I filter values in a Django form using ModelForm? wondering if i can apply same approach for my requirement, any suggestions would be much appreciated Thank you. -
Is the server running on host "localhost" (127.0.0.1)
I am deploying a django app for the first time to Heroku. I used the following: heroku run python manage.py migrate and it returns : Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? In my settings.py i have : DATABASES = { 'default': dj_database_url.config( default=config('DATABASE_URL') ) } and at the bottom : try: from .local_settings import * except ImportError: pass in the local_settings.py I have : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'newapp_development', 'USER': 'postgres', 'PASSWORD': '#####', 'HOST': 'localhost', 'PORT': '5432', } } Do you know why is the error message please ? Also, note that local_settings is added to . gitignore. Thank you for your help. -
How to solve the error while building a VueJS project?
I am using VueJS for front-end and Django on back-end. For production I moved all my VueJS compiled bundel to Static/dist in django. And I blocked the content of index.html in VueJS to base.html in django. And changed the url.py such that when localhost:8000 is called it gives base.html which gives index.html of VueJS. When I am trying to build using npm run buid it is throwing errors as shown ERROR Build failed with errors. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! e_cell_frontend@0.1.0 build: `vue-cli-service build` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the e_cell_frontend@0.1.0 build script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /home/vagrant/.npm/_logs/2021-08-05T04_54_44_578Z-debug.log The log file is as shown: 0 info it worked if it ends with ok 1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'run', 'build' ] 2 info using npm@6.14.4 3 info using node@v10.19.0 4 verbose run-script [ 'prebuild', 'build', 'postbuild' ] 5 info lifecycle e_cell_frontend@0.1.0~prebuild: e_cell_frontend@0.1.0 6 info lifecycle e_cell_frontend@0.1.0~build: e_cell_frontend@0.1.0 7 verbose lifecycle e_cell_frontend@0.1.0~build: unsafe-perm in lifecycle true 8 verbose lifecycle e_cell_frontend@0.1.0~build: PATH: /usr/share/npm/node_modules/npm-lifecycle/node-gyp-bin:/home/vagrant/VueJS/e_cell_frontend/node_modules/.bin:/home/vagrant/.vscode-server/bin/c3f126316369cd610563c75b1b1725e0679adfb3/bin:/home/vagrant/.local/bin:/home/vagrant/.vscode-server/bin/c3f126316369cd610563c75b1b1725e0679adfb3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin …