Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How To Pass Some Fields Into A Choice List
I have a model that holds the categories of items which are all BooleanFields. I want to display these categories in each post but there are too many to show so I want to make a form that allows the user to select 5 of their selected categories to display in the posts and then it will say (+ 5 more) or something like that. So is there a way that i can pass only the categories of which the value is true as choices in a ChoiceField? -
how can i create templates directory in community edition of pycharm?
I want to create directory of templates of Django in community edition of pycharm I run this command in community edition of pycharm django-admin startproject mysite but it does not create directory of templates i create that manually but always when I run server to url that are in templates directory always return Django templates does not exist -
Django RDF 'Request' object has no attribute 'accepted_renderer'
I've tried to use a custom render for my RDF responses, then this error suddenly appeared, her is my code: My serializer and API view codes class SupplierSerializer(serializers.ModelSerializer): class Meta: model = models.Supplier fields = [ # "plan", "type", "created", "id", "name", "bio", "established", "logo", "last_updated", "is_active", "date_to_pay", "mobile", "password", ] class SupplierViewSet(viewsets.ModelViewSet): """ViewSet for the Supplier class""" def initial(self, request, *args, **kwargs): """ Runs anything that needs to occur prior to calling the method handler. """ self.format_kwarg = self.get_format_suffix(**kwargs) # Perform content negotiation and store the accepted info on the request neg = self.perform_content_negotiation(request) request.accepted_renderer, request.accepted_media_type = neg # Determine the API version, if versioning is in use. version, scheme = self.determine_version(request, *args, **kwargs) request.version, request.versioning_scheme = version, scheme # Ensure that the incoming request is permitted self.perform_authentication(request) self.check_permissions(request) self.check_throttles(request) queryset = models.Supplier.objects.all() serializer_class = serializers.SupplierSerializer permission_classes = [permissions.IsAuthenticated] My custom rendering method and settings from rest_framework.renderers import BaseRenderer from rest_framework.utils import json class ApiRenderer(BaseRenderer): def render(self, data, accepted_media_type=None, renderer_context=None): response_dict = { 'status': 'failure', 'data': {}, 'message': '', } if data.get('data'): response_dict['data'] = data.get('data') if data.get('status'): response_dict['status'] = data.get('status') if data.get('message'): response_dict['message'] = data.get('message') data = response_dict return json.dumps(data) Settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', # <-- … -
How to choose (not upload) file from server in admin (Django)
I need to display icon(representing the type of the document inside the post) along with each post. There are hundreds of posts each year. There are about a dozen types of documents hence I need that much icons. The problem is that if I use models.ImageField it will upload a new image each time a post is created, and I will end up with bunch of same icons pretty soon. So I am wondering how to implement the following logic: preview_icon -> choose from server upload_icon -> If the wanted icon does not exists on the server then upload and choose it from server via preview_icon field. My initial idea is to make a new model: class PostIcon(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="icons") post_icon = models.ImageField(upload_to=f"path") So you can connect icon to post. But I am wondering if there is a way to implement the first logic I mentioned, because it would be much neater. Thank you. -
404 error when trying to add item to cart on other websites than main
so Im making webstore. Everything works fine on base url (127.0.0.1:8000) I can add "recommended" items to cart from here but when i go into the page that has all the details about this product (more pictures, description etc) and I want to add to cart from there I get error 404 127.0.0.1:8000/detail/1/updateItem cart.js var updateBtn = document.getElementsByClassName("update-cart") for (i = 0; i < updateBtn.length; i++){ updateBtn[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log(productId,action) console.log(user) if (user === "AnonymousUser"){ console.log("user not logged in") }else{ updateUserOrder(productId, action) } }) } function updateUserOrder(productId, action){ console.log("user created an order") var url = 'updateItem' fetch(url, { method:'POST', headers:{ 'Content-Type': 'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}) }) .then((response) =>{ return response.json() }) .then((data) =>{ location.reload() }) } My bet is that the error is in cart.js but im sooo bad at js... urls.py path('updateItem', views.updateItem, name='updateItem'), path('cart', views.cartDetail, name='cart'), views.py def cartDetail(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() else: order = {'get_cart_total':0,} items = [] print(items) context ={ 'items':items, 'orders':order, } return render(request,'cart.html',context) def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer,complete=False) orderItem, created … -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/login
I already posted this error but I couldn't find an answer, now I'm reposting with more details of my code. I'm new in coding field. I decided to start a project with Django & Python, but I got stuck due to some errors. For the past 3 weeks, I tried to figure out what was the issue but couldn't find it. Please help me to figure out the problems. I have 3 problems: 1-Welcome Page 2-Login & Registration(Sign-up) 3-Seach part 1.Welcome Page Welcome Page is the first page. It's the first page that any users see whenever he comes to the website and it is also a page where he has to login if he want to go to the second page. PROBLEM 1:\ whenever I get to the website, I won't see the content of the first page which is the welcome page. It will take me directly to the second page without even login 2- Login & Registration(Sign-up): Before getting into the second web page, The user has to login. If he can't login, he has to register. After registering, he will be redirected to the login page. PROBLEM 2:\ When I'm trying to Login, I received the … -
Modal Form Connected to SQLite3
I have the following code that is purposed to display a table of data and allow the user to add a new row by clicking a +New button, which opens a modal with the correct form, and then the user hits submit and the new row saves in the table. I am struggling to convert the modal from static, fake data to the data coming from my SQLite3 database. Anytime I try and add my fields (e.g. { stakeholder.employee }) into the modal I get an error: Error: Invalid block tag on line 123: 'stakeholder.id'. Did you forget to register or load this tag? Table of existing data with a button on top to add a new row: <div class="col-md-12"> <button type="button" class="btn btn-primary badge-pill float-right" style="font-size: 14px; width:80px;" data-toggle="modal" data-target="#new">+ New</button> </div> <table class="table table-hover" style="width:90% "> <thead> <tr style="font-family: Graphik Black; font-size: 14px"> <th scope="col">#</th> <th scope="col">Employee</th> <th scope="col">Stakeholder Group</th> <th scope="col">Quadrant</th> <th scope="col">Description</th> </tr> </thead> <tbody> {% for stakeholder in stakeholder_list %} <tr style="font-family: Graphik;font-size: 12px"> <td>{{ stakeholder.id }}</td> <td style="font-size: 15px">{{ stakeholder.employee }}</li></td> <td>{{ stakeholder.stakeholder_group }}</td> <td>{{ stakeholder.stakeholder_quadrant }}</td> <td>{{ stakeholder.description }}</td> <td><button type="button" class="btn btn-danger btn-sm badge-pill" style="font-size: 11px; width:60px" data-toggle="modal" data-target="#new">Edit</button></td> </tr> {% endfor … -
django_neomodel fails to connect to a running database while neomodel works
I made these setting on settings.py, as directed on Getting Started: NEOMODEL_NEO4J_BOLT_URL = os.environ.get('NEO4J_BOLT_URL', 'bolt://neo4j:password@localhost:7687') INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_neomodel', 'utils' ] But I only get this error with python manage.py install_labels: neo4j.exceptions.ServiceUnavailable: [SSLCertVerificationError] Connection Failed. Please ensure that your database is listening on the correct host and port and that you have enabled encryption if required. Note that the default encryption setting has changed in Neo4j 4.0. See the docs for more information. Failed to establish encrypted connection. (code 1: Operation not permitted) I know the database and neomodel are ok, because neomodel_install_labels models.py --db bolt://neo4j:password@localhost:7687 works perfectly and creates the nodes on the database. I don't know where I can look for the source of this exception. -
how to integerate jazzcash sandbox with django app?
I am implementing a Django app I need a payment method in it. I wanted to implement JazzCash sandbox in my app how can implement it in my app? -
Accessing one-to-one table field value in Django
I have a Django model which creates a one-to-one-field relationship with Django sites from django.contrib.sites.models import Site class SiteSettings(models.Model): site = models.OneToOneField(Site, related_name="settings", on_delete=models.CASCADE) header_text = models.CharField(max_length=200, blank=True) I want to access the header_text field in the SiteSettings table from the Site model. I have tried getting the value using: value = Site.settings.header_text print(value) I get the error: AttributeError: 'ReverseOneToOneDescriptor' object has no attribute 'header_text' Any help is appreciated. -
Number format wrong
Hi i'm trying to convert html to pdf with WeasyPrint(https://weasyprint.org/), the only problem is the format of the numbers : this is what i should get ( this is rendered with django) the page correct rendered with django this one is the pdf i get from WeasyPrint: page with the numbers with wrong format -
Django user logged out in a different app
I have a Django application with three different apps in it. One app's views contain the login view. the user stays logged in that two apps including the login view one. But as soon as I access templates related to the third view, Django states that no user is logged and gives anonymous user error. But if I go back to some other views from the functional views, the user is still logged in. What should I do? Thank. -
HOW django TemplateDoesNotExist at /
views.py ''' from django.shortcuts import render from django.utils import timezone from .models import Post def minjuand(request): posts = Post.objects.filter(published_date__lte = timezone.now()).order_by('published_date') return render(request,'blog/minjuand.html',{'posts':posts}) ''' urls.py ''' from django.urls import path from . import views urlpatterns=[ path('', views.minjuand, name="minjunad"), ] ''' in settings.py ''' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(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', ], }, }, ] ''' i already Add application into settings.py end of the INSTALLED_APPS and Typo checkstrong text i don't know what's wrong with this code any help appreciated django version : 3.1.4 python version : 3.9.0 window10 -
PayTM integration in django rest framework
I happened to be a part of a project based on Django as backend. Though I have created small Django projects I am not much familiar with Django REST framework. How should I approach this integration. More specifically how does this works there like receiving this information from frontend ,then sending information to PayTM ,and then returning the transaction status to frontend. I know its a very broad question. But an overview about this would help me a lot -
Adding a View to Django
I am trying to convert the django tutorial app into my own, and with that I need to add a few different views. I've added a new Column called 'Owner' into my database, migrated it, and am now trying to create a new view that will display the Owner data (similar to how the tutorial displays the questions and their data). Any idea what steps I am missing to get past this error? Expected Output would be for this to open with a functioning page displaying based on the stakeholdes.html file: http://127.0.0.1:7000/polls/stakeholders urls.py from django.urls import path from django.conf.urls import include from . import views app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/stakeholders/', views.StakeholdersView, name='stakeholders'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), path('django_plotly_dash/', include('django_plotly_dash.urls')), ] views.py from django.http import Http404 from django.shortcuts import get_object_or_404, render from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from django.urls import reverse from django.views import generic from django.utils import timezone from .models import Question from .forms import QuestionForm def stakeholders(request): owner_list = Owner.objects.order_by('-question_id')[:5] template = loader.get_template('polls/stakeholders.html') context = { 'owner_list': owner_list, } return HttpResponse(template.render(context, request)) class StakeholdersView(generic.ListView): template_name = 'polls/stakeholders.html' context_object_name = 'owner_list' def get_queryset(self): """Return the last five published … -
My HTML button doesn't work. Anything wrong?
I just wanna ask if there is anything wrong with my button code.. here it is: <button id="stop" type="Submit" class='btn btn-primary mx-sm-2 mb-1' href="/roles/meditation/meditate-timer/stop/">Stop</button> The button should have redirected us to the url, but when i serve the file from localhost (I'm using Django), nothing happened. The button is not functional. I have inspected the element and found no error. Anyone has an idea why? Thank you in advance! -
Django form not returning validation error even when it is supposed to?
In the console I can see that it has printed the "Less" string, that means the control is going inside the "if len(f_N) < 2", but then the validation error is not printed. Please help me out on whats wrong with the code. ####My forms.py file:#### from django import forms from django.core.exceptions import ValidationError class UserRegistrationForm(forms.Form): GENDER=[('male','MALE'),('female','FEMALE')] firstName= forms.CharField() lastName= forms.CharField() email= forms.CharField(widget=forms.EmailInput,required=False,initial='Youremail@xmail.com') address=forms.CharField(widget=forms.Textarea) gender=forms.CharField(widget=forms.Select(choices=GENDER)) password=forms.CharField(widget=forms.PasswordInput) ssn=forms.IntegerField() def clean_firstName(self): f_N=self.cleaned_data['firstName'] print(f_N) if len(f_N)>15: raise forms.ValidationError('Max length allowed is 15 characters') if len(f_N) < 2: print(len(f_N)) print("less") raise forms.ValidationError('Min length showuld be 2 characters') else: print("end") return f_N #######My html file###### <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>User Registration</title> </head> <body> <h1> User Registration</h1> <table> <form method="post"> {% csrf_token %} {{form.as_table}} </table> <button type="submit" name="button">Submit</button> </form> </body> </html> ##########My views.py file########## from django.shortcuts import render from .forms import UserRegistrationForm from .models import User # Create your views here. def UserRegistrationView(request): form=UserRegistrationForm() if request.method=='POST': form_1=UserRegistrationForm(request.POST) if form_1.is_valid() : #print(form_1.cleaned_data) form_1=form_1.cleaned_data print(request.POST) print(form_1) user_1=User() user_1.firstName=form_1['firstName'] user_1.lastName = form_1['lastName'] user_1.email = form_1['email'] user_1.save() return render(request,'formsDemo/userRegistration.html',{'form':form}) -
Vue error "Templates should only be responsible for mapping the state to the UI."
I'm using Django webpack-loader to load VueJS components inside of my Django templates, basically i have the following django template: {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html lang="en"> {% load static %} {% block content %} <head> ... </head> <body> <div id="app"> <div id="someDjangoStuff"> </div> <someVueComponent></someVueComponent> <anotherVueComponent></anotherVueComponent> </div> <body> {% endblock %} </html> So basically what i'm doing here is using Django to render the template and all the html in the template, then inside the template i'm injecting Vue components for stuff that requires more interactivity. The problem is that, in my console, i'll get the following error: [Vue warn]: Error compiling template: Templates should only be responsible for mapping the state to the UI. I'm sure it's because i'm loading the Vue app and inside the app i'm also loading other html. Now this error doesn't have any repercussion, everything seems to work without any problem, but i wanted to clarify a bit: Is there any way to suppress the error or do this in another way without getting the errors? Can it create problems because it's not how i should use Vue? -
solve issue of django template does not exist
this is current_datetime.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> it is now {{date time}} </body> </html> this is views.py import datetime from django.shortcuts import render def current_datetime(request): now=datetime.datetime.now() return render(request,'mysite/template/current_datetime.html',{'datetime':now}) this is urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls,name="admin"), path('current_datetime/',views.current_datetime,name="current_datetime"), ] and this is my directory but when i run server by "python manage.py run server" and go to this url: http://127.0.0.1:8000/current_datetime/ i got this error: TemplateDoesNotExist at /current_datetime/ -
Python version mismatch for Azure Web App
I have created a web app on Microsoft Azure and choosen Python 3.8 as configuration. Then I set up a deployment pipeline on Azure DevOps which deploys a django app into the web app. The deployment itself also runs fine, artifacts are copied and unzipped. But the installation of the requirements is giving me a hard time. On the Configuration section for the Web App on Azure portal I defined "Python 3.8" in the general settings. And in the Azure DevOps pipeline the deployment task is configured to use "PYTHON|3.8" as runtime stack. But still the post deployment actions do fail - and this as it looks like is caused by the Kundu component which executes the task and itself is running python 3.5 (python3) and python 2.7 (python). The pip installation for django 3.1.4 then fails with error and I am getting warnings about end of life python 3.5. Here's deployment step and full output of it #Your build pipeline references an undefined variable named ‘Parameters.ConnectedServiceName’. Create or edit the build pipeline for this YAML file, define the variable on the Variables tab. See https://go.microsoft.com/fwlink/?linkid=865972 #Your build pipeline references an undefined variable named ‘Parameters.WebAppKind’. Create or edit the build … -
How can you connect Django code with Python?
I'm fairly new into Django and Python. I'm currently building a crawler that searches for emails and I currently have a crawler build with Python but I want it to be linked to a search bar in Django that when it is clicked, the code detects the URL and the Python code starts running. I don't know how to proceed doing this. For now, I've tried to put the code in views.py and connect it to a url.py and connecting that url to a button. But it doesn't work. Here is the crawler code: import re import requests import requests.exceptions from urllib.parse import urlsplit, urljoin from lxml import html import sys import csv class EmailCrawler: processed_urls = set() unprocessed_urls = set() emails = set() def __init__(self, website: str): self.website = website self.unprocessed_urls.add(website) self.headers = { 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/78.0.3904.70 Chrome/78.0.3904.70 Safari/537.36', } self.base_url = urlsplit(self.website).netloc self.outputfile = self.base_url.replace('.','_')+'.csv' # we will use this list to skip urls that contain one of these extension. This will save us a lot of bandwidth and speedup the crawling process # for example: www.example.com/image.png --> this url is useless for us. we cannot possibly parse email from … -
how to keep django server running when I have some errors in code
class AnswerCreateAPIView(generics.CreateAPIView): ... def perform_create(self, serializer): ... serializer.save(author=request_user, question) like when I am editing my code after question, I switch to other window, and check for documentation, my Pycharm simply stop the server running because the django detected problems in my snippet. What's more , problems may make Pycharm jump to other files while debugging( Appreciate if you know how to prevent this from happening ). How can I keep django running instead of complete stop. -
django queryset not showing accurate result (building a news app)
I am creating a news app using django. It consists of search by date option. When i choose the date(ex:29-11-2020) and click submit, It should take me to the news of that particular day. When i try the below code instead of showing the details it is giving me a blank page. views.py from django.shortcuts import render from .models import * from django.views.generic.detail import DetailView from django.views.generic import ListView def index(request): return render(request,'newspaperapp/index.html') class nowlist(ListView): model = newsmodel_1 template_name = 'newspaperapp/index.html' class newslist(DetailView): model = newsmodel_1 template_name = 'newspaperapp/home.html' context_object_name = 'newspaperapp' # search by giving date in index and search date class SearchView(ListView): model = newsmodel_1 template_name = 'newspaperapp/search.html' context_object_name = 'all_search_results' def get_queryset(self): result = super(SearchView, self).get_queryset() query = self.request.GET.get('search') if query: postresult = newsmodel_1.objects.filter(date_published__contains=query) result = postresult else: result = None return result urls.py from django.urls import path app_name = 'newspaperapp' from .views import newslist,SearchView,nowlist from newspaperapp import views urlpatterns = [ path('',views.index,name='index'), path('date/',nowlist.as_view(),name = "date"), path('<int:pk>',newslist.as_view(),name = "home"), path('results/', SearchView.as_view(), name='search'), ] newspaperapp/home.html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <p>Today's Paper</p> {{newspaperapp.date_published}} {{newspaperapp.category}} </body> newspaperapp/index.html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <!-- this page has search … -
Add a country field to Django-Odcar address form
How can I add a coutry field to shipping address form in django oscar so i can later use it in CheckoutSessionMixin by calling a method Documentation doesnt specify the form structure. When I call the method I get the default value of "United Kingdom of Great Britain and Northern Ireland" self.get_shipping_address(basket) -
Filter Data in Serialization
i have serialization class like this class MenuSerializer(serializers.ModelSerializer): data = Menu.objects.raw('''SELECT menu_menu.*, menu_permission.role_id FROM menu_menu JOIN menu_permission ON menu_menu.id = menu_permission.menu_id WHERE sub_menu_id IS NULL ORDER BY menu_menu.id ASC''') subItems = SubMenuSerializer(data=data,many=True) class Meta: model = Menu fields = ('id', 'label', 'icon', 'link', 'isTitle', 'isMenuCollapse', 'subItems') how to filter subItems based request header