Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Increase number of supported request by django on dev
I have a doc project where I have to test a massive ammount of urls and links. To do that I was using python 2 linkchecker. I upgraded to django 2.2 and python 3.6 and I am using a go binary called muffet (https://github.com/raviqqe/muffet). linkchecker was gentle with the server, muffet on the other hand is more brutal (even with timeout options and other settings). The problem I have is after some time, the requests timeout and the django local server crashes. I heard about somme kind of queue or cache for the local django server. Is anyone knows how to increase the django limit in order not to DDOS myself while I am running my tests before deployment (this tool is not running in production). Or any out of the box thinking to solve this. Just for you to know, I run the server in background, and call the tool on the localhost url. (from another terminal) Thanks -
django is installed but still django-admin.py command not found
i was running this command PYTHONPATH=/opt/graphite/webapp django-admin.py migrate --settings=graphite.settings but it is showing this error: -sh: django-admin.py: command not found django directory is present in /usr/local/bin.what can be the reasons? -
Django How to create tables in views.py and display it to the Html
Good day guys, I am new here please good to me :) I hope the title is enough to understand what the problem is, I want to create a table in my views.py and display it to my html, I have this code in my views.py students = studentsEnrolledSubjectsGrade.objects.filter(Teacher=m.id).filter( grading_Period=period.values_list('id')).filter( Subjects__in=student_subject.values_list('id')).filter(Grading_Categories__in=cate.values_list('id')).filter(GradeLevel__in=student_gradelevel.values_list('id')).order_by( 'Students_Enrollment_Records', 'Grading_Categories' ).values('Students_Enrollment_Records', 'Grading_Categories', 'Grade').distinct() teachera = studentsEnrolledSubjectsGrade.objects.filter(id__in=students.values_list('id')) teacherStudents = StudentsEnrolledSubject.objects.filter( id__in=students.values_list('Students_Enrollment_Records')) Categories = studentsEnrolledSubjectsGrade.objects.filter(Grading_Categories__in = students.values_list('id')).order_by('Grading_Categories') table = [] student_name = None table_row = None columns = len(Categories) + 1 table_header = ['Student Names'] table_header_Period = ['Period'] table_header.extend(Categories) table.append(table_header) for student in students: if not student['Students_Enrollment_Records'] == student_name: if not table_row is None: table.append(table_row) table_row = [None for d in range(columns)] student_name = student['Students_Enrollment_Records'] table_row[0] = student_name table_row[Categories.index(student['Grading_Categories']) + 1] = student['Grade'] table.append(table_row) This is my Models.py class studentsEnrolledSubjectsGrade(models.Model): Teacher = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True, blank=True) GradeLevel = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+', on_delete=models.CASCADE, null=True) Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE, null=True, blank=True) grading_Period = models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE, null=True, blank=True) _dates = models.CharField(max_length=255,null=True, blank=True) Grade = models.FloatField(null=True, blank=True) @property def dates(self): # you have Year-month-day dates from the form return [datetime.strptime(date, '%Y-%m-%d') for date in self._dates] @dates.setter def dates(self, … -
Django Model data in views as variable
Need help, Very new to Django. I have created a model as below class Redirect_url(models.Model): hosturl = models.CharField(max_length=100) path = models.CharField(max_length=100) redirectpage = models.CharField(max_length=200) I need the hosturl, path and redirectpage as a variable in my views page for me to make some logic before I render to the html page. I don’t know from django.shortcuts import render,redirect from django.http import HttpResponseRedirect from django.http import HttpResponse from .import models def home(request): return render(request,'home.html') def redurl(request): b = request data = (models.Redirect_url.objects.all()) print(data) return HttpResponse(data, content_type="text/plain") I am getting print as Redirect_url object (1)Redirect_url object (2). How to get all the models data. Thanks. -
eval() in python crashing the server
From the UI, I am currently getting a list of strings to my python function in the back-end via ajax as shown below in ans variable. ans = ["Address().address()", "Address().number()", "Address().city()", "Address().continent()"] Address is the class name and address, number and city are its methods I am using eval() to evaluate each of the strings in a for loop of 1000 which means 1000 such lists with evaluated strings will be stored in a final list. but when i loop for 1000, the server crashes due to this. Also, when i loop till 50, its runs fine...but gets crazy for large number of input number. are there any alternatives for eval()? Please suggest. -
How can I prevent losing cookies in a Django app, upon a callback done by 3rd party API?
I am trying to integrate Spotify login for a logged/registered user of my Django app. I am facing issues with preventing losing the session id (stored in cookies). The session id is lost when the api requests the callback uri. The flow so far is: Django/Website View: Login the user (using Django's authentication system; this sets the session id cookie in the browser) Django/Website View: User chooses to connect Spotify account (redirected to Spotify's login screen) Spotify View: User logs in and grants permissions Django/Website View: Spotify redirects to my application (redirect uri is set in the API dashboard; the browser is now missing the session id cookie) After the redirect, Django logs my user out of the app. I have noticed the reason to be a loss of cookies namely, session id and csrftoken. I need to preserve the session id cookie in order prevent the logging the user out. Is there anyway I can prevent the loss of session id after the redirect takes place? -
How to metronic theme integration in django?
I have metronic theme how i am run metronic theme with django or integrate the theme i want to create front-end with metronic theme and back-end using django. how can i do this. -
How to properly add the checked users in a certain group?
views I have a checkbox to check the users in order to add them in a group.Here If the checked user is already in the group then it fails now with this code but I want proceed(if checked users are already in) and add the remaining user to the group and leave the already added user as it is. It throws this error if the checked users are in the group already UNIQUE constraint failed: user_registration_user_groups.user_id, user_registration_user_groups.group_id def assign_users_to_group(request, pk): group = get_object_or_404(Group, pk=pk) if request.method == 'POST': users = request.POST.getlist('users') for user in users: if user in group.user_set.all(): pass group.user_set.add(user) messages.success(request, 'users added to this group') return redirect('user_groups:view_group_detail', group.pk) -
Django model query with not equal exclusion
I would like to create query that has a not equal parameter, but in exclusion part. All posts suggest to exclude the parameters that should be not equal. So what I need is : Object.objects.filter(param1=p).exclude(param2=False, param3=False, param4 != q) I try Object.objects.filter(param1=p).exclude(param2=False, param3=False).exclude(param4=q) but, as expected, doesn't work it is the same as exclude(param2=False, param3=False, param4=q) So how to do it, or how to rightly chain exclude statements, so that second exclude is pointed to first exclude and not first filter. -
How to use javascript string as variable name in django html template?
I have a django view that passes a multiple of values to my html page. based on some client side process, I want to process one of those values. consider the example: views.py return render(request,'output.html',{ 'k1'=x, 'k2'=y, 'k3'=z, } output.html: <script> var temp; if( ....... ){ temp='k1'; } else if ( ...... ){ temp='k2'; } else{ temp='k3'; } now i want to access value in variable whose name is stored in temp, to perform some jquery operations. So i need the value stored in a javascript variable. Note: the given is just a small example, i am actually using a loop of about 60 iterations, i.e. k1 to k60. -
How to store user created through signup page to google cloud mysql database thorugh python3 django?
Can anyone provide me a link or guidance on how to proceed to store the users created through signup page using django's auth libs to google cloud sql? I am unable to store the data as well as retrieve it in order for the person to login into the website. -
How to add columns through django admin panel
I have a table named tableA with columns "name" and "age" built using model.py. Now I wanted to add another column like "gender" but this time not by changing model.py but directly through admin panel. I know that admin panel allows to add values to the existing table but i wanted to add a feature where we can add columns too through the admin panel and not by hardcoding in model.py So is it possible? -
Unable to migrate changes from Django to Oracle database
I am unable to migrate changes in Oracle version 6 database. After creating the model and write: python manage.py makemigrations python manage.py migrate I get: django.db.utils.DatabaseError: ORA-02000: missing ALWAYS keyword -
Radio buttons not validating with done() method in django form?
I'm having issues getting my forms to submit radio button selection. The forms work fine, but I keep getting a Your SessionWizardView class has not defined a done() method, which is required. error. My code is shown below: forms.py from django import forms class PresidentForm(forms.Form): CHOICES=[('choice 1', "Choice 1"), ('choice 2', "Choice 2"), ('choice 3', "Choice 3"), ('choice 4', "Choice 4"), ] ballot = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect, label="U.S President / Vice President") class SenatorForm(forms.Form): CHOICES=[('choice 1', "Choice 1"), ('choice 2', "Choice 2"), ('choice 3', "Choice 3"), ('choice 4', "Choice 4"), ] ballot = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect, label="U.S Senator") class RepresentativeForm(forms.Form): CHOICES=[('choice 1', "Choice 1"), ('choice 2', "Choice 2"), ('choice 3', "Choice 3"), ('choice 4', "Choice 4"), ] ballot = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect, label="U.S Representative") class PropositionForm(forms.Form): CHOICES=[('yes', "Yes"), ('no', "No"), ] ballot = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect, label="Proposition 123") views.py Note: I have 2 done() methods, one of which is commented out. This is a result of me experimenting and the final product will only have 1 done() method from django.http import HttpResponseRedirect from .forms import PresidentForm, SenatorForm, RepresentativeForm, PropositionForm from formtools.wizard.views import SessionWizardView class FormWizardView(SessionWizardView): template_name = "templates/form.html" form_list = [PresidentForm, SenatorForm, RepresentativeForm, PropositionForm] # def done(self, form_list, **kwargs): # return render(self.request, 'done.html', { … -
Django: The UI throws a "This field is required" error after uploading a file
My template: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <table> {{ form.as_table }} </table> </form> My view: def create_batch(request): form = BatchForm(request.POST or None, request=request) if form.is_valid(): form.save_batch(request=request, create_batch_flag=True) return redirect('list_batch_url') return render(request, template_name, {'form': form}) My form: class BatchForm(ModelForm): csv_file = FileField(label='CSV File') class Meta: model = Batch fields = ('project', 'name', 'csv_file', 'filename') def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super(BatchForm, self).__init__(*args, **kwargs) #limit to projects created by the logged in user self.fields['project'].queryset = Project.all_created_by(self.request.user) def clean(self): cleaned_data = super().clean() csv_file = cleaned_data.get("csv_file", False) The clean method does not pick up "csv_file" and the UI throws a "This field is required" on the CSV FILE input button. I cant seem to get what im doing wrong here. Can you please help. Thanks -
How to switch design for each cards in django templates
How to switch between different card designs for each data in the for loop. <div class="col-1-of-3"> <div class="card"> ... </div> </div> <div class="col-1-of-3"> <div class="card"> ... </div> </div> <div class="col-1-of-3"> <div class="card"> ... </div> </div> These three cards have different designs, Currently facing trouble in switching these cards for each loop in the Django template. {% for cont in data %} {% ifequal forloop.counter|divisibleby:"3" True %} <div class="col-1-of-3"> <div class="card"> ... </div> </div> {% endifequal %} {% ifequal forloop.counter|divisibleby:"2" True %} <div class="col-1-of-3"> <div class="card"> ... </div> </div> {% endifequal %} {% ifnotequal forloop.counter|divisibleby:"2" True %} <div class="col-1-of-3"> <div class="card"> ... </div> </div> {% endifnotequal %} {% endfor %} Third card logic is wrong. I need to change this logic so that for each loop each cards need to be displayed alternatively. And another challenge is that after 3 loop it should close the section, since in a row only 3 cards are allowed. <section class="section-tours" id="section-tours"> {% ifequal forloop.counter|divisibleby:"3" True %} {% endifequal %} {% ifequal forloop.counter|divisibleby:"2" True %} {% endifequal %} {% ifequal forloop.counter|divisibleby:"2" True %} {% endifequal %} </section> -
Is it recommended to Install and configure UFW for a new Django project?
I'm deploying a new project on Google Cloud Platform using Django certified by Bitnami that comes with pre-installed Debian 9, Apache, MySQL, Python. My end goal is to build a web application, but nothing is close to production yet and I'm still running on an ephemeral external IP address assigned to the VM instance. So my question is that is it recommended that install an ufw (Uncomplicated Firewall) ? -
Django channels: Alternative of Redis for windows machine?
As per documentation of redis, A.3.1 Drawbacks of Redis on Windows Windows doesn’t support the fork system call, which Redis uses in a variety of situations to dump its database to disk. Without the ability to fork, Redis is unable to perform some of its necessary database-saving methods without blocking clients until the dump has completed. Questions: 1) If I'm not wrong, this issue will occur when concurrent users increases? Is that correct? 2) Is it really a issue, if we deploy channels on windows machine(production server)? If yes, is there any better alternative of redis? Note: Can't use wsl2(as officially not released) or wsl as current windows server won't support. -
Django OSMGeoAdmin Cross Origin Issue
It's basically this question: cross origin access issues - django 2.1.7 But it's still not correctly answered. Is this still a JS thing? Or are we missing something? The original question: I have gone through literally all SO links, reinstalled django and django-cors-headers and followed this to the T and yet we get pre flight error cross origin not allowed Django version 2.1.7 relevant sections of settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'uploads.core', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True Even with corsheader middlewear at the top, same error code arrives. [Error] Cross-origin redirection to https://a.tile.openstreetmap.org/14/4684/6268.png denied by Cross-Origin Resource Sharing policy: Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin. [Error] Cannot load image http://a.tile.openstreetmap.org/14/4684/6268.png due to access control checks. -
Connect django with postgres db which is in clojure platform
I have a clojure server which is a game server and need to communicate with django channels. Do anyone have any idea how to proceed with the above requirement? Clojure platform server is already up. Next need to establish a communication using python. Expecting suggestions to solve the issue Thanks in advance Details of project Django version:2, Server:Postgres in clojure environment. Need to connect django to postgres inorder to get some data values like time samples,userlogin time etc. How can I connect the django to postgres db which is in clojure platform? -
Docker connection error 'Connection broken by NewConnectionError'
I am new to docker i just installed it and did some configuration for my django project. when i am running docker build . i am getting these error whats wrong here? WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f1363b604f0>: Failed to establish a new connection: [Errno -3] Try again')': /simple/django/ Dockerfile FROM python:3.8-alpine MAINTAINER RAHUL VERMA ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app WORKDIR app COPY ./app /app RUN adduser -D user USER user requirements.txt file Django==2.2 djangorestframework==3.11.0 -
Django Reverse for 'post-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['post\\/(?P<pk>[0-9]+)\\/$']
I am working on a personal fitness blog app and am running into this error when trying to allow a user to "comment" on a post. Python 3.6.4, Django 3.0.2 models.py class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') comment_id = models.AutoField(primary_key=True) author = models.ForeignKey(Profile, on_delete=models.CASCADE) content = models.TextField(max_length=1000, blank=False, default="") date_posted = models.DateTimeField(default=timezone.now) class Meta: ordering = ['date_posted'] def __str__(self): return 'Comment {} by {}'.format(self.content, self.author.first_name) urls.py urlpatterns = [ # path('', views.home, name="main-home"), path('', PostListView.as_view(), name="main-home"), path('admin/', admin.site.urls), path('register/', views.register, name="register"), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('about/', views.about, name="main-about"), path('search/', SearchResultsView.as_view(), name="main-search"), path('post/<int:pk>/comment/', views.add_comment_to_post, name='add_comment_to_post'), ] post_detail.html {% extends "main/base.html" %} {% block content %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ object.author }}</a> <small class="text-muted">{{ object.date_posted }}</small> </div> <h2 class="article-title"><u>{{ object.title }}</u></h2> <p class="article-content">{{ object.content }}</p> <div class="row"> <div class="col-xs-6 col-sm-4"><b>Distance: </b>{{ object.distance }} miles</div> <div class="col-xs-6 col-sm-4"><b>Time: </b>{{ object.time }} minutes</div> <div class="clearfix visible-xs-block"></div> <div class="col-xs-6 col-sm-4"><b>Pace: </b>{{ object.pace }} mins/mile</div> </div> </div> </article> <hr> <a class="btn btn-default" href="{% url 'add_comment_to_post' pk=post.pk %}">Add comment</a> {% for comment in post.comments.all %} <div class="comment"> <div class="date">{{ comment.date_posted }}</div> <strong>{{ comment.author }}</strong> <p>{{ comment.content|linebreaks }}</p> </div> {% empty %} <p>No comments here … -
Django connect to MSSQL - django/sql_server - pyodbc
I've tried to install django_pyodbc but when I try make migrations got the error: django.core.exceptions.ImproperlyConfigured: Django 2.1 is not supported. My setttings.py: 'Test_DB': { 'ENGINE': 'django_pyodbc', 'NAME': 'TEST', 'HOST': '127.0.0.1', 'USER': 'sa', 'PASSWORD': '123456', 'OPTIONS': { 'driver': 'ODBC Driver 12 for SQL Server', }, }, When I try to install django-pyodbc-azure, I got the other error: Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' My setttings.py: 'Test_DB': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'TEST', 'HOST': '127.0.0.1', 'USER': 'sa', 'PASSWORD': '123456', 'OPTIONS': { 'driver': 'ODBC Driver 12 for SQL Server', }, }, So what should I do so that I can connect the SQL Server 2012? -
Setting username in steam OpenID authentication with Django Allauth
I'm trying to configure a new django application to use Steam's OpenID authentication. The issue i'm running into is that when a new user sign's in (no form to allow them to customize username/specify email address) the something (either allauth or django.contrib.auth) defaults their User object's username to user. That field is unique... so a 2nd user can't login. I can't figure out what/where the new user object is created so we can customize that field. We want it to pull from extra_data['personaname']) ideally. -
django pass argument from view to form only once
I have an OTP generator mechanism, whereby in GET method, a unique 4-dit OTP is generated and is sent to the OTPAuthenticationForm() as follows: views.py if request.method == 'GET': otp = 'abcd' # code to send otp via mail form = OTPAuthenticationForm(request=request, otp=otp) # this is how the OTP is passed only once. return .... elif request.method == 'POST': form = OTPAuthenticationForm(request.POST, request=request) if form.is_valid(): # the clean_field() method is not invoked/throws error. print("OTP is valid") else: print("OTP is invalid") forms.py from django.contrib.auth.forms import AuthenticationForm class OTPAuthenticationForm(AuthenticationForm): otp = forms.CharField(required=True, widget=forms.TextInput) def __init__(self, otp, *args, **kwargs): self.otp = kwargs.pop("otp") super(OTPAuthenticationForm, self).__init__(*args, **kwargs) def clean_otp(self): if self.otp!= self.cleaned_data['otp']: raise forms.ValidationError("Invalid OTP") How should the generated_otp be passed only once to the OTPAuthForm() so that it could be validated against the user input OTP (OTP received via email).