Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass all objects attributes to ListView
This is my detail view, I pass if a post is 'liked' and 'total likes' in context. I want to do the same in my List View for every object. class MemeDetailView(DetailView): model = Meme template_name = "memes/meme_detail.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) meme = get_object_or_404(Meme, id=self.kwargs['pk']) context['total_likes'] = meme.total_likes() liked = False if meme.likes.filter(id=self.request.user.id).exists(): liked = True context['liked'] = liked return context here is my ListView: class MemeListView(ListView): model = Meme paginate_by = 100 ordering = ['-created_at'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() return context How can I pass all objects 'total likes' and 'liked' to context? -
Apache Ubuntu - Can't host Django
I've been trying to get my Django REST project to work in Apache for the last couple of hours but all I'm getting is the Apache2 homepage. The url I need the Django server to work on. This currently just displays the default Apache2 page. hhhhhhhhh.stratoserver.net:8000 If I try any of the django paths like /admin or /api it gives me a 404 Not Found error. /etc/apache2/sites-available/st-backend.conf <VirtualHost *:8000> ServerAdmin webmaster@localhost ServerName hhhhhhhhh.stratoserver.net:8000 ServerAlias www.hhhhhhhhh.stratoserver.net:8000 DocumentRoot /var/www/st-backend # Point this to the wsgi.py in the same directory as your settings.py file WSGIScriptAlias / /var/www/st-backend/project/wsgi.py WSGIDaemonProcess st-backend python-path=/var/www/st-backend:/var/www/st-backend/stenv/lib/python3.8/site-packages WSGIProcessGroup st-backend Alias /static /var/www/st-backend/project/static <Directory /var/www/st-backend/project/static> Require all granted </Directory> <Directory /var/www/st-backend> <Files wsgi.py> Require all granted Allow from all </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> I've used a2ensite st-backend to enable the site, apachectl configtest to check syntax (which is ok) and restarted apache using sudo systemctl restart apache2.service. Everything else is default other than changing the port from 80 to 8000. Can anyone point out to me what's going wrong in the configuration file? I've checked all the paths multiple times and they're all valid paths. -
Wagtailmenus: how to access Page fields from first level menu?
I'm using Wagtailmenus 3.0.2. The documentation says: If the template is for rendering the first level of a main or flat menu, then menu_items will be a list of MainMenuItem or FlatMenuItem objects (respectively). In all other cases. it will be a list Page objects. (https://wagtailmenus.readthedocs.io/en/v3.0/rendering_menus/custom_templates.html) I'm using a FlatMenu with only one level. I need to access Page fields but it's not rendered in the template. When I use a multilevel menu, I can access Page fields inside the submenu without problem. I wonder if there is a way to access Page fields inside the first level menu. Thanks in advance for your help! -
I want to use the column defined in one table in another new table in SQL
I want to use the Phone column of extendeduser model in willpant model but when I add the phone column in willplant model and run command makemigrations its gives me two option as seen in Screenshot . I want to use the phone column data in Willplant model below. enter image description here enter image description here enter image description here -
Django: Including multiple forms leads to errors
Error: Some forms are sent as 'invalid', which does not create an entry in the database. Only FieldForm and ColorsForm are working -> all other do not send the submitted data even if i entered valid information What I did: I had multiple forms If I wanted to submit only one specific form with the Submit button, all of them were submitted directly. Found Proper way to handle multiple forms on one page in Django Tried to implement it in my views file: @login_required try: radius = request.user.fieldradius except FieldRadius.DoesNotExist: radius = FieldRadius(user=request.user) try: font_size = request.user.fontsize except FontSize.DoesNotExist: font_size = FontSize(user=request.user) try: change_color = request.user.colors except Colors.DoesNotExist: change_color = Colors(user=request.user) try: toggle_settings = request.user.togglesettings except ToggleSettings.DoesNotExist: toggle_settings = ToggleSettings(user=request.user) try: page_details = request.user.pagedetails except PageDetails.DoesNotExist: page_details = PageDetails(user=request.user) if request.method == 'POST': if 'form1_btn' in request.POST: form = FieldForm(request.POST, prefix='form1', instance=Field(user=request.user)) if form.is_valid(): obj = form.save(commit=False) obj.creator_adress = get_client_ip(request) obj.save() return redirect('/dashboard#5') elif 'form2_btn' in request.POST: togglesettings_form = ToggleSettingsForm( request.POST, prefix='form2', instance=toggle_settings) if togglesettings_form.is_valid(): togglesettings_form.save() return redirect('/dashboard/#panel1') elif 'form3_btn' in request.POST: radius_form = FieldRadiusForm( request.POST, prefix='form3', instance=radius) if radius_form.is_valid(): radius_form.save() return redirect('/dashboard') elif 'form4_btn' in request.POST: change_color_form = ColorsForm( request.POST, prefix='form4', instance=change_color) if change_color_form.is_valid(): change_color_form.save() return redirect('/dashboard') elif 'form5_btn' … -
Javascript. Weird Error with Server events
I'm pretty new in Javascript and having some weird error using Javascript Server Event with Django Framework. Check Code down below. Django: main_course_api.py This func returns server event back to front-end.... (working well): def send_data_as_stream_event(request): import json request_data = request.GET.get('list_of_courses') append_to_list(request_data) course_data = get_parsed_data(LIST_OF_COURSES['list_of_courses']) response = django.http.StreamingHttpResponse(json.dumps(course_data)) response['Content-Type'] = 'text/event-stream' return response urls.py path('get/stream/response/data/', main_course_api.send_data_as_stream_event, name='stream'), Main.js var evtSource = new EventSource('http://127.0.0.1:8000/get/stream/response/data/'); evtSource.onopen = function(event){ console.log('connected....') } evtSource.onmessage = function(event) { console.log('on message event..', event) console.log(event); } evtSource.onerror = function(err) { console.error("EventSource failed:", err); evtSource.close(); }; evtSource.onclose = function(code){ evtSource.close(); console.log('event source has been closed', code); } }); It is supposed to work, but it gives me such error in JS console every time after execution: main.js:74 EventSource failed: Event {isTrusted: true, type: 'error', target: EventSource, currentTarget: EventSource, eventPhase: 2, …}isTrusted: truebubbles: falsecancelBubble: f falsecancelable: falsecomposed: falsecurrentTarget: EventSource {url: 'http://127.0.0.1:8000/get/stream/response/data/', withCredentials: false, readyState: 2, onclose: ƒ, onopen: ƒ, …}defaultPrevented: falseeventPhase: 0path: []returnValue: truesrcElement: EventSource {url: 'http://127.0.0.1:8000/get/stream/response/data/', withCredentials: false, readyState: 2, onclose: ƒ, onopen: ƒ, …}target: EventSource {url: 'http://127.0.0.1:8000/get/stream/response/data/', withCredentials: false, readyState: 2, onclose: ƒ, onopen: ƒ, …}timeStamp: 3608.300000011921type: "error"[[Prototype]]: Event evtSource.onerror @ main.js:74 error (async) (anonymous) @ main.js:73 Looks like something wrong with asynchronous, but not really sure about the … -
how to get the TaskId in GET method in Django Rest framework
I'm trying to get the value in GET method However, it's returning only taskid as NONE. Is it possible to get the values in GET method Here, what I have tried views.py: @api_view(['GET']) def GetCurrentRunningActivityForAudit(request, UserID): if request.method == 'GET': print("current running activity--userid--", UserID) cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivityAudit] @UserId=%s',(UserID,)) result_set = cursor.fetchall() TaskId = request.data.get('TaskId') print('TaskId in result current running activity--', TaskId) IsActive=GetCurrentSubTaskSTatus(TaskId) print("IsActive", IsActive) data = [] for row in result_set: TaskId=row[0] TaskName = row[1] Source = row[2] SID = row[3] type = row[4] data.append({ "TaskId": TaskId, "TaskName":TaskName,"Source":Source, "SID":SID, "type":type, 'IsActive':IsActive}) return Response(data[0]) def GetCurrentSubTaskSTatus(taskid): IsActive = 1 cursor = connection.cursor() cursor.execute('EXEC [dbo].[USP_GetCurrentTaskStatus] @taskid=%s',(taskid,)) result_set = cursor.fetchall() return IsActive -
How to document individual actions of a ViewSet using `drf-spectacular`?
Using DRF's built-in way of documenting the API, I was able to write a docstring like the following and each action was documented by its corresponding line: """ list: The list action returns all available objects. retrieve:The retrieve action returns a single object selected by `id`. create: The create action expects the fields `name`, creates a new object and returns it. """ I am in the middle of switching to the library drf-spectacular, which allows for an easy generation of OpenAPI conforming schemes. However, the same docstring is now rendered for every action, which makes my documentation really long and redundant. Is there a way that only the relevant part of the docstring is rendered for each action? -
Django: bootstrap styling is lost in my sidebar; hat is the best way to solve this?
I use bootstrap dashboard (https://getbootstrap.com/docs/4.1/examples/dashboard) as a base for my project. I have added form in the sidebar but 'bootstrap' styling is lost as you can see in picture below. I have tried different approach like crispy-form (what I currently use), django-widget-peaks, but result is not really good I think, maybe because part of CSS is override? For example, text in the "Select" is partially visible... I would like to be able to use bootstrap styling option like input-group-sm to decrease input size but it doesn't works... Thanks for your help -
Only list the connected object from the OneToMany Field instead of all objects
I have a very reasonable pagespeed inside the django admin interface when i open my "facility" objects. But if i open one of my "facility addresses" it will take more than 8 seconds to load. I imagine that this is caused by the fact that all existing facilities are being loaded into the dropdown of the OneToMany Field even though the facility is only connected to one address. How can i limit it so there is either no dropdown on these OneToMany Fields or that it only shows the current objects it is connected to? class Facility(models.Model): UUID = models.CharField(max_length=150, null=True, blank=True) Name = models.CharField(max_length=150, null=True, blank=True) class Meta: verbose_name_plural = "facilities" def __str__(self): return self.Name class FacilityAddress(models.Model): PrimaryAddress = models.CharField(max_length=50, null=True, blank=True) SecondaryAddress = models.CharField(max_length=50, null=True, blank=True) City = models.CharField(max_length=50, null=True, blank=True) RegionOrState = models.CharField(max_length=30, null=True, blank=True) PostalCode = models.CharField(max_length=20, null=True, blank=True) Geolocation = models.CharField(max_length=20, null=True, blank=True) AddressInfo = models.ForeignKey(Facility, null=True, blank=True, on_delete=models.CASCADE, related_name='fa') class Meta: verbose_name_plural = "facility addresses" def __str__(self): return f"{self.PrimaryAddress} {self.City}" -
Facing this issue with creating a superuser for so long, please help me
While trying to execute this command (venv) sreekarsiddula@Sreekars-MacBook-Air bidgala % /Users/sreekarsiddula/piapps/venv/bin/python3 manage.py createsuperuser I am facing this issue.👇 {} /Users/sreekarsiddula/piapps/venv/lib/python3.9/site-packages/django/db/models/fields/init.py:1365: RuntimeWarning: DateTimeField UserInfo.verification_expiry received a naive datetime (2022-02-01 13:46:28.114225) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" {} ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1129) During handling of the above exception, another exception occurred: urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1129)> During handling of the above exception, another exception occurred: T File "/Users/sreekarsiddula/piapps/venv/lib/python3.9/site-packages/django/dispatch/dispatcher.py", line 174, in (receiver, receiver(signal=self, sender=sender, **named)) File "/Users/sreekarsiddula/piapps/bidgala/bidgala/accounts/views.py", line 391, in user_saved raise Exception("Unable to process the request") Exception: Unable to process the request Any help will be much appreciated, I am trying to resolve this. -
Why isn't Django serving staticfiles in production?
I am wondering the reason why Django does not serve the statifiles in production, when DEGUB = False. STATICFILES_DIRS We specify STATICFILES_DIRS to tell Django where to look for staticfiles that are tied up to a specified app. STATIC_ROOT We specify STATIC_ROOT to tell Django where to store the files once we run python manage.py collectstatic, so everystatic file is stored in the path specified in STATIC_ROOT. Assume that we set STATIC_ROOT = "staticfiles/". This means that once we run the collectstatic command, all the files that are inside STATICFILES_DIRS paths are going to be stored in "staticfiles/" STATIC_URL Finally we specify STATIC_URL as "prefix" to tell Djando where to look for staticfiles, for example in the HTML <link> tag, the url that we see is based on STATIC_URL value When we upload our project to the server, we upload the entire project, so every single file. Why can't Django serve staticfiles itself when running on server? As I just said, we upload the entire folder, so the files we uploaded are there (and the staticfiles too!). QUESTIONS I am just wondering, why do we have to specify the staticfiles based on server in production, when Django could do everything … -
Django aggregate and annotate to count by group - multiple levels
I have a model that looks like: class Foo(models.Model): bar = models.CharField(...) baz = models.CharField(...) Foo(bar="a", baz="x") Foo(bar="a", baz="x") Foo(bar="a", baz="y") Foo(bar="b", baz="y") And I want a queryset that will return the largest count of unique (bar, baz) pairs for each bar: [ {"bar": "a", "baz": "x", "count": 2}, {"bar": "b", "baz": "y", "count": 1}, ] Ideally this will all be done within a query, I've tried combinations of distinct, aggregate, annotate, to no avail and can't see how to do it other than run raw SQL which I want to avoid. I'm using the PostgreSQL as my database backend. -
TypeError: <lambda>() takes exactly 2 arguments (3 given)
i have a problem in this code in wsgi: if settings.UWSGI_DJANGO_WARMUP: application({ 'REQUEST_METHOD': 'OPTIONS', 'SERVER_NAME': '127.0.0.1', 'SERVER_PORT': 80, 'PATH_INFO': '/ping', 'wsgi.input': sys.stdin, }, lambda x, y: None) # call the entry-point function i get this error: TypeError: <lambda>() takes exactly 2 arguments (3 given) (4 additional frame(s) were not displayed) ... File "sentry_sdk/integrations/wsgi.py", line 116, in __call__ _sentry_start_response, start_response, span File "newrelic/api/wsgi_application.py", line 668, in _nr_wsgi_application_wrapper_ result = wrapped(environ, _start_response) File "django/core/handlers/wsgi.py", line 214, in __call__ start_response(force_str(status), response_headers) File "newrelic/api/wsgi_application.py", line 636, in _start_response response_headers + additional_headers, *args) File "sentry_sdk/integrations/wsgi.py", line 137, in _sentry_start_response return old_start_response(status, response_headers, exc_info) TypeError: <lambda>() takes exactly 2 arguments (3 given) is it in the lambda function why is it takes 3 arguments? -
i have multiple documents in MongoDB database i want to fetch them one by one and display in form of table using django
I have multiple documents in MongoDB database i want to fetch them one by one and show their data in the form of table using Django is there any tool I can use my MongoDB is as follows: my model code is as follows from django.db import models # Create your models here. class level(models.Model): time=models.DateTimeField(primary_key=True,default=0) status=models.CharField(max_length=50) level=models.DecimalField(max_digits=12,decimal_places=6) my views code to fetch data is as follows def generate(request): events_list=level.objects.all() return render(request,'result.html',{'res':events_list}) -
Django.mo and Django.po files while moving to a Linux server
I am following CoreySchafer's tutorial to deploy my Django app onto a linux server. When I start copying the files to a linux server it finishes it but it takes a lot longer than his because in my case it is copying A LOT of django.mo and django.po files ? In his example none of that is happening ? I am struggling to understand why is that ? I don't like the idea of something working for me but me not knowing why is it working the way it is. -
why error_messages dictionary doesn't working in Meta class in forms.py?
My forms.py from django.core.exceptions import ValidationError from django.forms import ModelForm from django import forms from . models import Detail class DetailForm(ModelForm): name = forms.CharField(validators=[not_contain_number], required=True) email = forms.EmailField(required=True) phone_no = forms.IntegerField( validators=[number_validation], required=True) class Meta: model = Detail error_messages = { 'name': { 'required': 'enter your name', }, } labels = {'name': 'Your Name', 'email': 'Your Email', 'phone_no': 'Your Phone No.'} widgets = {'name': forms.TextInput( attrs={'placeholder': 'type your Name'})} fields = ['name', 'email', 'phone_no'] Does it occurs due to my any mistake in ModelForm API? It is working when i used it while defining: class DetailForm(ModelForm): name = forms.CharField(validators=[not_contain_number], required=True,error_messages={'required': 'Enter Your Name'}) -
Django: local variable 'form' referenced before assignment
With the post Proper way to handle multiple forms on one page in Django I tried to create multiple forms in just one template, so when I press just one submit button, it doesn't submit all the forms right away. I gave my submit buttons a name, for example form1_btn for my first form. Before I could even try if it works, I get the following error, even though I specified in the Else statement what happens when request != 'POST local variable 'form' referenced before assignment View Files @login_required def DashboardView(request): browser = str(request.user_agent.browser.family) user = str(request.user) short_user = user[0:7] + "..." try: radius = request.user.fieldradius except FieldRadius.DoesNotExist: radius = FieldRadius(user=request.user) try: font_size = request.user.fontsize except FontSize.DoesNotExist: font_size = FontSize(user=request.user) try: change_color = request.user.colors except Colors.DoesNotExist: change_color = Colors(user=request.user) try: toggle_settings = request.user.togglesettings except ToggleSettings.DoesNotExist: toggle_settings = ToggleSettings(user=request.user) try: page_details = request.user.pagedetails except PageDetails.DoesNotExist: page_details = PageDetails(user=request.user) if request.method == 'POST': if 'form1_btn' in request.POST: form = FieldForm(request.POST, prefix='form1', instance=Field(user=request.user)) if form.is_valid(): obj = form.save(commit=False) obj.creator_adress = get_client_ip(request) obj.save() return redirect('/dashboard#5') elif 'form2_btn' in request.POST: togglesettings_form = ToggleSettingsForm( request.POST, prefix='form2', instance=toggle_settings) if togglesettings_form.is_valid(): togglesettings_form.save() return redirect('/dashboard/#panel1') elif 'form3_btn' in request.POST: radius_form = FieldRadiusForm( request.POST, prefix='form3', instance=radius) if radius_form.is_valid(): radius_form.save() … -
Multiform - how can i control each button seperately
How can i use 2 forms in 1 page by using class based view in Django. I have 2 different models tables and i created 2 different forms for each model. Each form contain 1 button each. each form submits different data. I have no of fields in my 1st form and have 1st button. parallel to 2nd field i created my 2nd button(used 2nd form there). Each button saves data for different models. currently works 1st form control for my 2 button. How can i control each button seperately.. which technique i want to use for that? I searched about multiform.. but i can't find good solution.. -
How to display the values of the attributes of the data queried and retireved by ajax call in django
I am trying to query the database based on what the user has clicked on the page and display the data retrieved by it wihtout refreshing the page. I am using ajax for this. Let me show you the codes html <label for="landacq" class="civil-label">Land Acquisation Cases</label> <input class="civil-category" type="radio" name="civil-cat" id="landacq" value="land acquisation" hidden> <label for="sc" class="civil-label">Supreme Court</label> <input class="civil-court" type="radio" name="civil-court" id="sc" value="supreme court" hidden> <label for="limitation" class="civil-label">Limitation</label> <input class="civil-law-type" type="radio" name="civil-law-type" id="limitation" value="limitation" hidden> js for (i = 0; i < lawTypeInput.length; i++) { lawTypeInput[i].addEventListener("click", (e) => { e.preventDefault(); cat = civilCatval; court = civilCourtval; lawT = civillawTypeval; console.log("this is from ajax : ", cat, court, lawT); $.ajax({ type: "POST", headers: { "X-CSRFToken": csrftoken }, mode: "same-origin", // Do not send CSRF token to another domain. url: "civil", data: { "cat[]": civilCatval, "court[]": civilCourtval, "lawT[]": civillawTypeval, }, success: function (query) { showCivilQ(query); // console.log(data); }, error: function (error) { console.log(error); }, }); }); } function showCivilQ(query) { q.textContent = query; console.log(query); } So here for example, if the user the click the radio button in the html, the values are grabbed by in js file and then sent to the url mentioned as a POST request. There these … -
Python: Regex for four of more words and hyphens
I want to match a slug with 4 or more words using regex Example - /productivity-courses-and-programs/ , /artificial-intelligence-courses-and-programs/ should match but /ai-category/ , /data-science/ or /data-science-category/ shouldn't. Tried r'^(?P<slug>\w+(?:-\w+)+)/$ but this takes all of the above example. -
django 404 - a list of known urls includes one that is reportedly not found
in my core urls.py, an app-specific urls.py is included, with namespace set to 'accounts'. path("accounts/", include("shop.apps.accounts.urls", namespace="accounts")), in that accounts.urls, likewise, nothing appears to be missing. Using stock views: from django.contrib.auth import views as auth_views and defining, among others in urlpatterns, this one: path("logout", auth_views.LogoutView.as_view(next_page="/accounts/login/"), name="logout"), Everything appears to be in place. And yet when I click on the logout link defined thus: <a href="{% url "accounts:logout" %}">Logout</a> , I receive a mysterious Page Not Found 404. I say mysterious, because the 404, when in DEBUG=True, lists all the urls which Django knows about - including this item: accounts/ logout [name='logout'] whaaat? I do notice some strange extra space in "[namespace]/ [path]", but I don't think it matters. Any suggestions are much appreciated, thanks! -
Python was not found showing in windows cmd even added path but pip --version has no problem
python -- version showing run without argument but pip --version showing proper output in windows cmd even I add path when installing python -
Render Plotly chart without background
I have a Plotly donut chart rendering in my Django template that comes with a default white background. I can't figure out how to render it without the background. I know how to make the background transparent but when I try to resize the chart, obviously the background is still there and it stretches the div or if I make the chart smaller so it fits then its too small and unreadable. Is there a way to get rid of the background all together? Or maybe I should use something other than Plotly? Thanks for your help! import plotly.graph_objects as go fig = go.Figure(data=[go.Pie(labels=labels, values=values, hole=.3)]) fig.update_layout(paper_bgcolor='rgba(0,0,0,0)', width=300, height=300,) chart = fig.to_html() -
Display Recent 3 Record from Django model in a HTML Template
I would like to show the latest 3 posts in the Latest Posts section of my page. How can I do it without using for loop or is that the only way? I was successful to get the result in the shell console, however, I am not able to show it in the HTML template. Please help models.py from typing import Any from django.db import models from django.contrib.auth.models import User from django.utils import timezone from ckeditor.fields import RichTextField class BlogPost(models.Model): blogpic = models.CharField(max_length=1000) title = models.CharField(max_length=255) description = models.CharField(max_length=100, default='Enter a short desctiption', editable=True) body = RichTextField(blank=True, null=True) category = models.CharField(max_length=50, default='banking', editable=True) tag = models.CharField(max_length=50, default='consulting', editable=True) author = models.ForeignKey(User, on_delete=models.CASCADE) blog_date = models.DateField(default=timezone.now, editable=True,) def __str__(self): return self.title + ' | ' + str(self.author) views.py from django.views.generic import ListView, DetailView from . models import BlogPost class BlogView(ListView): model = BlogPost template_name = 'blog.html' ordering = ['-blog_date'] class BlogDetailsView(DetailView): model = BlogPost template_name = 'blog_details.html' urls.py from django.urls import path from AssayBlog.models import BlogPost from . views import BlogView, BlogDetailsView urlpatterns = [ path('', BlogView.as_view(), name="blog"), path('_detail/<int:pk>', BlogDetailsView.as_view(), name="blog_details"), blog_details.html <h3 class="sidebar__title">Latest Posts</h3> <ul class="sidebar__post-list list-unstyled"> <li> <div class="sidebar__post-image"> <img src="{% static 'assets/images/blog/lp-1-1.jpg' %}" alt=""> </div> <div class="sidebar__post-content"> <h3> …