Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
best solution for Django Composite primary-key from foreign-keys
I want to satisfy this relationship in a Django SQLite DB (ER Diagram), I have tried using both the unique_together and models.UniqueConstraint solutions that I've seen suggested. myapp/models.py class User(models.Model): user_id = models.AutoField(primary_key=True, null=False) class Article(models.Model): article_id = models.AutoField(primary_key=True) class ArticleEditor(models.Model): class Meta: # RECOMMENDED models.UniqueConstraint(fields=['article_id', 'editor_id'], name="article_editor_id",) # DEPRECATED unique_together = (('article_id', 'editor_id'),) article_id = models.ForeignKey( Article, on_delete=models.CASCADE, ) editor_id = models.ForeignKey( User, on_delete=models.PROTECT, ) In both cases, when I try saving an ArticleEdiotor object through the python console, I get this error: >>> from myapp.models import User, Article, ArticleEditor >>> a = Article.objects.get(article_id=2) >>> u = User.objects.get(user_id=1) >>> ae = ArticleEditor(a.article_id, u.user_id) >>> ae.save() Traceback (most recent call last): ... django.db.utils.OperationalError: no such table: myapp_articleeditor However, I checked the sqlmigrate command for the migration and it does CREATE TABLE "myapp_articleeditor"; but it still makes an "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT that I don't want, as I'd like for my composite key (article_editor_id) to be the primary key. How to I achieve this? And is this actually the best way to make a many-to-many relationship that has an intermediate table, like depicted in the diagram, or is there a better solution? -
django rest framework get vieset by route basename
A basic class based view in django gives view name by reslove(reverse("url-name")).func But is there anyway I get viewset name by route basename. When I try reverse("basename") I get errors. -
Django : request.body isn't null but request.POST is null
I wanna test LOGIN function. I used Insomnia to send signal. like this: enter image description here I found request.POST is always null, but request.body is not. In terminal, Output is as follows: print(request.body) : b'{\n\t"userid" : "TEST",\n\t"userpw" : "TEST",\n\t"created" : ""\n}' print(request.POST) : <QueryDict: {}> My code in PyCharm: models.py : from django.db import models class AppAddresses(models.Model): userid = models.CharField(max_length=30, null=False, default=False) userpw = models.CharField(max_length=30, null=False, default=False) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created'] serializers.py : from rest_framework import serializers from .models import AppAddresses class AppAddressesSerializer(serializers.ModelSerializer): class Meta: model = AppAddresses fields = ['userid', 'userpw'] urls.py : from django.contrib import admin from django.urls import path, include from addresses import views urlpatterns = [ path('app_login/', views.app_login), path('app_signup/', views.app_signup), path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] views.py : from django.contrib.auth.models import User from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from .models import AppAddresses from .serializers import AppAddressesSerializer from django.contrib.auth import authenticate @csrf_exempt def app_login(request): if request.method == 'POST': id = request.POST.get('userid', '') pw = request.POST.get('userpw', '') print(request.body) print(request.POST) login_result = authenticate(username=id, password=pw) if login_result: print("SUCCESS!") return JsonResponse({'code': '0000', 'msg': 'SUCCESS'}, status=200) else: print("FAILED!") return JsonResponse({'code': '1001', 'msg': 'FAILED'}, status=401) elif request.method == 'GET': query_set = AppAddresses.objects.all() serializer = AppAddressesSerializer(query_set, … -
Error : "Invalid block tag on line 51: 'endif', expected 'empty' or 'endfor'. Did you forget to register or load this tag?' in Django vscode
I was unable to solve this error which was occured in Django website. Here's my view.py file from django.shortcuts import render from .models import Product from math import ceil from django.http import HttpResponse def index(request): products = Product.objects.all() n = len(products) nSlides = n//4 + ceil((n/4) + (n//4)) params = {'no_of_slides': nSlides, 'range': range( 1, nSlides), 'product': products} return render(request, "shop/index.html", params) def about(request): return render(request, 'shop/about.html') def contact(request): return HttpResponse("We are at contact") def tracker(request): return HttpResponse("We are at tracker") def search(request): return HttpResponse("We are at search") def prodview(request): return HttpResponse("We are at product view") def checkout(request): return HttpResponse("We are at checkout") Basic.html file :- <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous" /> <title>{%block title%} {%endblock%}</title> <style> {%block css%} {%endblock%} </style> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="#">My Awesome Cart</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#" >Home <span class="sr-only">(current)</span></a > </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" … -
Creating an inline-formset with inlineformset_factory
okay, I still dont get how to create an inlineformset. Following 2 different tutorials and everything I found in the docs I still dont get question to show up. It only displays the 3 Choices for me models.py class Question(models.Model): question_text = models.CharField(max_length=200) pub_date: DateTimeField = models.DateTimeField('date published', default=timezone.now) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) forms.py class QuestionForm(forms.ModelForm): class Meta: model = Question fields = ['question_text'] class ChoiceForm(forms.ModelForm): class Meta: model = Choice fields = ('choice_text',) QuestionFormSet = inlineformset_factory( Question, Choice, form=ChoiceForm, min_num=2, max_num=10, extra=1, can_delete=True ) views.py class IndexView(generic.CreateView): model = Question template_name = 'polls/index.html' form_class = QuestionFormSet success_url = None def get_context_data(self, *, object_list=None, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) if self.request.POST: context['form'] = QuestionFormSet(self.request.POST) else: context['form'] = QuestionFormSet() return context -
My Django website's LINKS is not working on Cpanel
I have already uploaded my Django project file on CPANEL. My website is hosted (https://abccypher.com/) correctly. But when I click on my links it is showing- FILE NOT FOUND. This is the homepage and when you will click sign up or any links it will show "File not found" If anyone is there please guide me. I can discuss this with you. -
How to set uniques values only for the child model?
I have the following related models: class DeviceType(models.Model): type_name = models.CharField(primary_key=True, max_length=64, unique=True) type_description = models.TextField(max_length=512, blank=True) class DeviceTypeMarker(models.Model): marker_status = IntegerField() marker_status_text = models.CharField(max_length=64) marker = models.ImageField(upload_to='images/types/') marker_device_type = models.ForeignKey(DeviceType, on_delete=models.CASCADE, related_name='marker') Where it is possible to define many DeviceType elements. For every DeviceType element there can be many differents marker_status, marker_status_text and marker. The thing is that i don't want that inside a single DeviceType this elements are duplicated. They can be repeated but only in an another DeviceType. For example, if type1 is a DeviceType object, then there can be only a marker_status with value "1", only a marker_status_textwith value "error" and the same for marker. This values could only be repeated in an other DeviceType object. For example, type2.. How is this done? -
Django created_at field not added when creating an object
I'm trying to get Django automatically add a field to an object where the date and time is saved in the field as a timestamp. When I create the object in my view and I go check in admin page, every other field is created but not this one. views.py : newconf = ConfigUser.objects.create( ref=''.join(random.SystemRandom().choice( string.ascii_lowercase + string.ascii_uppercase + string.digits ) for _ in range(20)), name='', user=request.user, # Here I don't add created_at because I want it to be automatic (see models.py) cpu=cpu[0], gpu=gpu[0], ram=ram[0], ssd_m2=ssd_m2[0], ) models.py : class ConfigUser(models.Model): ref = models.CharField(max_length=20, unique=True, default='') name = models.CharField(max_length=128, default='') user = models.OneToOneField(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) cpu = models.ForeignKey(CPU, on_delete=models.CASCADE) gpu = models.ForeignKey(GPU, on_delete=models.CASCADE) ram = models.ForeignKey(RAM, on_delete=models.CASCADE) ssd_m2 = models.ForeignKey(SSD_M2, on_delete=models.CASCADE) def __str__(self): return self.name -
Unauthorized user probllem with jwt tokens in django rest framework
i am logged in with verified credentials then i verified the token which is sent to the user email.then when i am trying to login again i am not able to do so it is showing the below error. System check identified no issues (0 silenced). December 26, 2020 - 16:52:04 Django version 3.1.4, using settings 'backend_api.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Unauthorized: /user/login/ [26/Dec/2020 16:52:10] "POST /user/login/ HTTP/1.1" 401 43 Unauthorized: /user/login/ [26/Dec/2020 16:52:27] "POST /user/login/ HTTP/1.1" 401 34 Unauthorized: /user/login/ [26/Dec/2020 16:52:33] "POST /user/login/ HTTP/1.1" 401 34 -
How can I check user id in Django in order to redirect him based on his role (admin or normal user)?
I want to use the same login form in order to redirect the user into the required page if he is an admin go to the admin page if not go to normal user page. -
Django UpdateView Reverse for 'update_hours' with arguments '('',)' not found
So I have this ListView that work but when I want to put a button on it to update one of the objects I get error Reverse for 'update_hours' with arguments '('',)' not found. update_hours is the namespace VIEWS.PY class HoursList(ListView): context_object_name = 'object' paginate_by = 32 fields = ( 'start_date', 'end_date', 'hours_int', ) k_url_kwarg = 'pk' template_name = 'users/hours-list.html' def get_queryset(self): queryset = TimeLog.objects.filter(id=self.kwargs['pk']) return queryset class update_hours(UpdateView): # model = TimeLog fields = '__all__' template_name = 'users/hours-update.html' success_url = reverse_lazy('hours_list') def get_object(self): return get_object_or_404(TimeLog, pk=self.kwargs['pk']) All is fine at this point, but when I add a button in hours-list.html (the last line as shown below), I get the error. hours-list.html (template) {% for obj in object %} <tr> <td>{{ obj.end_date |date:' l ' }}</td> <td>{{ obj.end_date |date:' M jS ' }}</td> <td>{{ obj.start_date |date:' g:i A' }}</td> <td>{{ obj.end_date |date:' g:i A' }}</td> <td>{{ obj.hours_int }} h</td> <td> <button href="{% url 'update_hours' em.pk %}">pdf></button> </td> </tr> {% endfor %} What I'm I missing? Will really appreciate any help.