Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django crispy input from Ajax data
I need to Auto-fill up the crispy fields so I called the needed data from my database using ajax function as: views.py def load_record(request): PUITS_id = request.GET.get('PUITS') record = SurveillanceDesPuits.objects.filter(PUITS_id__id__exact=PUITS_id)[:1] my_record= [str(record[0].PUITS) , str(record[0].MODE), str(record[0].CS)] print(my_record) return render(request, 'measure/Surveill_Wells/Add_wellMntr.html', {'record': my_record}) And my HTML file is : <form method="POST" id="SurveillanceDesPuits_F" data-record-url="{% url 'ajax_load_record' %}"> {% csrf_token %} <!-- form from views.py--> <div class="border p-2 mb-3 mt-3 border-secondary"> <div class="form-row"> <div class="form-group col-md-3 mb-0"> {{ form.PUITS|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.CS|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.MODE|as_crispy_field }} </div> </div> </div> <input class="btn btn-success mb-4" type="submit" value="ADD Record"> </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_PUITS").change(function () { var url = $("#SurveillanceDesPuits_F").attr("data-record-url"); var PUITSId = $(this).val(); $.ajax({ url: url, data: { 'PUITS': PUITSId }, success: function (data) { $("#id_MODE").html(data); } }); }); </script> After selecting an item (PUITS) from the dropdown list, I want to set the value of CS and MODE automatically from the received data. so in the console, it gives me this error: File "D:\WikiPED\venv\lib\site-packages\crispy_forms\templatetags\crispy_forms_filters.py", line 102, in as_crispy_field raise CrispyError("|as_crispy_field got passed an invalid or inexistent field") crispy_forms.exceptions.CrispyError: |as_crispy_field got passed an invalid or inexistent field [07/Sep/2021 17:30:05] "GET /ajax/load-record/?PUITS=1 HTTP/1.1" 500 25693 what I … -
Where to add Many to Many in django?
So, Am creating a app where user can add universities to their fav or wishlist ! The problem is, am just confused how and where add ManyToMany ? Model Student: name = models.CharField ..... Model University: name = models.CharField ..... Model Wishlist: wish = models.ManyToMany(University) Is this correct, is it okay to create a seprate model class as "wishlist" or can i have the wishlist on the Student: Am totally confused, all i need to do is "user needs to able to click heart button and add university to wishlist and if they reclicks it needs to removed" -
Django - create many to many objects inline simirly to inlinetabular for admin
I want to allow users to create inline/on-the-fly an object of model A that has a many to many relationship with a field of a model B, while creating an object B...basically just like TabularInline allows you to do on the admin. -
Why is my template html file not using bootsrap css?
[This is the output of my django website im working on, bootstrap css are not being applied on tags for some reason][1] This is the template code of django website im referring to. [This is the output of my command prompt, i'm newbie at using django im currrently learning and i have no idea how to fix this idea and get ahead with learning.][3] [this is my bootstrap file folder, as you can see the file path in link tag of my html file is correct, i dont know what is wrong with those errors[][4]4 -
How to add tokens to URL for running CSS file? [django]
when I run the program, the CSS file doesn't work with the project. when I see that on AWS and click on the "open file" button I see the file opening with the appendix query string which I can't add and I don't know where I should get it and placed it in. this query looks like this: ?response-content-disposition=inline&X-Amz-Security-Token=xx&X-Amz-Algorithm=xx&X-Amz-Date=xx&X-Amz-SignedHeaders=xx&X-Amz-Expires=xx&X-Amz-Credential=xxx&X-Amz-Signature=xxx but the real path I get from my own machine is the real path that precedes the query string that looks like: https://django-testing-files.s3.us-east-2.amazonaws.com/static/student_grade/css/style.css?... so, can anyone tell me where I should get and put this tokens? I googled then I understood that there's something called "disposition" that I should use but don't understand how can I get it. these are the codes I used: # settings.py AWS_ACCESS_KEY_ID = "xxx" AWS_SECRET_ACCESS_KEY = "xxx" AWS_STORAGE_BUCKET_NAME = "django-testing-files" AWS_HEADERS = {'Cache-Control': str('public, max-age=3')} AWS_DEFAULT_ACL = 'public-read' AWS_S3_FILE_OVERWRITE = True DEFAULT_FILE_STORAGE = "website.storage_backends.MediaStorage" AWS_S3_REGION_NAME = 'us-east-2' AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_LOCATION = 'media' AWS_S3_CUSTOM_DOMAIN = '%s.s3.us-east-2.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATICFILES_STORAGE = "website.storage_backends.StaticStorage" STATIC_LOCATION = 'static' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] # storage_backends.py from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings class MediaStorage(S3Boto3Storage): location = 'media' file_overwrite = True class StaticStorage(S3Boto3Storage): … -
How to render custom return_uri in google_auth_oauthlib
I have tried to add custom return_uri but it's now allowing to add. It assigns default its own localhost URL. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'client_secrets.json', SCOPES) creds = flow.run_local_server() # Save the credentials for the next run with open('token.json', 'w') as token: token.write(creds.to_json()) enter image description here Please anyone could help me with this -
temp emails and avoid them using django
i want to block temp emails and just make user can to register just if the email is real (like gmail , outlook , yahoo) forms.py class SginupForm(UserCreationForm): class Meta: model = User fields =('username', 'first_name','last_name','email','password1','password2' ) views.py @unauthenticated_user def signup_form(request): if request.method == 'POST': form=SginupForm(request.POST) if form.is_valid(): user=form.save() send_action_email(user,request) messages.add_message(request, messages.SUCCESS, 'we v sent ur activtion link') return redirect('core:login') else: form=SginupForm() return render(request,'user/sign-up.html',{'form':form}) -
How do I reload Django model-forms?
Currently my models look similar to this, def feature_tuples(): features = (('a', 'a'), ('b', 'b')) return features class Sample(models.Model): choices_tuple = models.CharField(max_length=20, blank=True, null=True, choices=feature_tuples()) I than created a model form of this model. However, at some point i want to change the choices of choices_tuple from a, b to c, d. I can't find a way to reload the choices of choices_tuple in the form. Help? -
How to get QuerySet of ForeignKey field Django
I have two models. First one: class KvantMessage(models.Model): text = models.TextField(blank=True) style_text = models.TextField(blank=True) receivers = models.ManyToManyField(MailReceiver) date = models.DateField(default=timezone.now) files = models.ManyToManyField(FileStorage, blank=True) title = models.CharField(max_length=120, default='Письмо') sender = models.ForeignKey(KvantUser, on_delete=models.CASCADE, related_name='sender') And second one: class ImportantMail(models.Model): user = models.ForeignKey(KvantUser, on_delete=models.CASCADE) mail = models.ForeignKey(KvantMessage, on_delete=models.CASCADE) The question is, how to get all mails instances as "KvantMails" from "ImportantMail" where user is equal to some user. P.S. Hope you understand my question -
How to get a unique serial_number for a abstract base class in Django?
I have a abstract base model and two child models: class Component(models.Model): serial = models.PositiveIntegerField(unique=True) last_modified = models.DateTimeField(auto_now_add=True) class Meta: abstract = True class ChildComponentA(Component): name = models.CharField(max_length=200, null=True, blank=True) class ChildComponentB(Component): name = models.CharField(max_length=200, null=True, blank=True) I want the serial field to be unique for all children but this does not work for me. How can I achieve this? -
What is the difference between Django and Flask [closed]
I want to start backend development with Python and am confused on which web framework to choose. Which one should i start with Django or Flask -
How to pass S3 URL instead of file in DRF request?
I am currently migrating an application from a low-code application to a full backend. As a part of the migration, I'm currently in the middle of DB migration. The values of the current proprietary DB are fetched as a JSON via an API and the files are stored in an S3 bucket. I am using DRF serializers to remap the values and I want to retain the S3 URLs when mapping them to an ImageField. However, DRF keeps expecting a file object and I am unable to figure out a way to set the URL into the DB with DRF Viewsets. -
Speaking and Listening simultaneously like Alexa [closed]
I am trying out on something which is very new to me. I wanted to develop a feature which is something like Alexa. So, Here goes the feature I wanted to develop. When I click on play button, the system has to read out the contents stored as a pdf. While speaking it also has to listen out for any queries from the user. What have I tried so far? I have tried working out this feature using pyttsx3 module. But this module only speaks but it doesn't listen. I also have a problem in pausing and resuming the speech. import pyttsx3 import pdfplumber import PyPDF2 file = 'C:/Users/Downloads/Books/Eleven Minutes.pdf' #Creating a PDF File Object pdfFileObj = open(file, 'rb') # creating a pdf reader object pdfReader = PyPDF2.PdfFileReader(pdfFileObj) #Get the number of pages pages = pdfReader.numPages speaker = pyttsx3.init() if 'play' in request.GET: with pdfplumber.open(file) as pdf: #Loop through the number of pages for i in range(0, pages): page = pdf.pages[i] speaktext = page.extract_text() speaker.say(speaktext) speaker.runAndWait() if 'stop' in request.GET: speaker.endLoop() spaker.stop() What is my system based on? It is based on Python, Javascript, SQlite. I would appreciate any help with this. TIA -
How do I set the default value for instance variable?
class SafetyValveSerializer(serializers.ModelSerializer): # Instead of exposing the state's primary key, use the flag field state_flag = serializers.SlugRelatedField(source='sv_state', queryset=SafetyValveState.objects.all(), slug_field='flag') class SafetyValveState(models.Model): sv_state_key = models.AutoField(primary_key=True) flag = models.IntegerField(unique=True) description = models.CharField(max_length=50) How do I set the default value of state_flag to 0 when call SafetyValveSerializer partially not passing state_flag? -
How can i in Django Oscar filter EAV Attributes in Frontend?
In Django Oscar when i add a new product class i can insert new dynamic attributes. This is a implementation from Django EAV. Now i want in frontend to view a form with all EAV Attributes and when this form is submit then Django Oscar filter products after this EAV attributes. Have anyone a idea how i can implement this? I try nothing till yet. I know that i can filter with products.objects.filter(eav_attributename='blabla') but how can i make a form with all EAV Attributes? When user submit it how can a filter products after several EAV fields? -
Django - Annotate Count() of distinct values grouped by Date
I have the following Model: class Visualization(models.Model): .... user: FK user start_time: DATETIME product: FK product .... Example data: | User ID | Start Time | Product ID | | :----: | :----------: | :-------: | |1|2021-09-07 14:03:07|3| |2|2021-09-07 13:06:00|1| |1|2021-09-07 17:03:06|1| |4|2021-09-07 04:03:05|5| |1|2021-09-07 15:03:17|4| |1|2021-09-07 19:03:27|1| |2|2021-09-06 21:03:31|3| |1|2021-09-06 11:03:56|9| |1|2021-09-06 07:03:19|9| I need to get the active users for days, the active users are those who made at least one reproduction, if a user made many reproductions, it still counts as 1. A correct answer would be: | Total | Date | | :----: | :----------: | |3|2021-09-07| |2|2021-09-06| First I make an annotation a Truncate of StartTime to keep only the Date and then I make Group By for this annotation, so far everything without problems. The problem is when I try to count the Users since they have repetitions. I have tried to count the User_id with Distinct = True, but the numbers still give me bad, also by a very big difference. I also tried grouping by user_id and period (annotation of Truncate StartTime) but it didn't work for me either -
how can i replicate admin.TabularInline outside of the admin (on the user side?)
Given a mode A and a model B that has a field with a many to many relationship with model A, I am trying to allow users creating an object of model B to also create an object of model A inline/on-the-fly just like TabularInline allows you to do on the admin. -
React Django Auth
I'm trying to login thru ReactJS app and here is the error I get: Access to XMLHttpRequest at 'http://localhost:8000/auth/login/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. even though I added CORS_ALLOW_CREDENTIALS: True to the settings.py: """ Django settings for config project. Generated by 'django-admin startproject' using Django 3.2.6. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] CORS_ALLOWED_ORIGINS = ["http://localhost:3000"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "corsheaders", 'rest_framework', 'service_get_data', 'background_task', 'service_append_data', ] MIDDLEWARE = [ … -
Django - render django-filter(filterset) bar with crispy forms
I'm quite new and would appreciate some help. I created a filter bar (with filterset from th django-filter module) but I'm unable to render it with crispy forms. Are crispy-forms compatible with django-filter? I tried it and crispy works well with all my other forms and modelforms, but it seems like django-filter rejects to render in bootstrap. HTML <div class="row"> <div class="col"> <div class="card card-body"> <form method="get"> ****{{ myFilter.form}}**** */tried also {{ myFilter.form|crispy}} {{ myFilter.form.variablefieldhere|as_crispy_field}}** <button class="btn btn-primary" type="submit"> Search</button> </form> </div> </div> </div> Filter.py import django_filters from .models import log class logFilter(django_filters.FilterSet): class Meta: model = log fields = { 'varfliedhere': ['icontains'], 'varfliedhere': ['icontains'], 'varfliedhere': ['icontains'], 'Boolean varfliedhere': ['exact'], } Shoul i try to set the FormHelper in forms? But in that case, how do i render it in crispy? In the others forms i rendered them 1 by 1 as: {{ myFilter.form.variablefieldhere|as_crispy_field}} and works, but can't understand how to solve this problem. Thanks in advance! -
Django3.2.6 : TypeError: 'NoneType' object is not callable
I am learning this Django Framework from this summer. I have get the error <TypeError: 'NoneType' object is not callable>. I am trying to narrow down the problem. However, after I have delete a lot of code, I still cannot figure this out from the most simple code. My code is showed as below. admin.py from django.contrib import admin from rest_framework.renderers import AdminRenderer from .models import Car @admin.site.register(Car) class CarAdmin(admin.ModelAdmin): list_display = ('id', 'brand', 'model') models.py from django.db import models from django.contrib import admin class Car(models.Model): brand = models.TextField(default='Honda') model = models.TextField(default='EK9') class Meta: db_table = 'car' def __str__(self): return self.model the error LeodeMacBook-Pro:sharky leo$ python ./manage.py runserver /Users/leo/opt/anaconda3/lib/python3.8/site-packages/environ/environ.py:628: UserWarning: /Users/leo/Documents/python_test/leo_first_python_side_project/sharky/sharky/mysite/.env doesn't exist - if you're not configuring your environment separately, create one. warnings.warn( /Users/leo/opt/anaconda3/lib/python3.8/site-packages/environ/environ.py:628: UserWarning: /Users/leo/Documents/python_test/leo_first_python_side_project/sharky/sharky/mysite/.env doesn't exist - if you're not configuring your environment separately, create one. warnings.warn( Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/leo/opt/anaconda3/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Users/leo/opt/anaconda3/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/leo/django/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/leo/django/django/core/management/commands/runserver.py", line 114, in inner_run autoreload.raise_last_exception() File "/Users/leo/django/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/leo/django/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() … -
How to get name from id of ForeignKey in django?
Issue When I call {{cats}} I'm getting an id, How can I get the category name in the same place? My Html File {% extends 'base.html' %} {% load static %} {% block title %} Blogue | {{cats}} {% endblock %} {% block content %} Views.py def CategoryView(request, cats): category_posts = Post.objects.filter(category=cats) return render(request, 'categories.html', {'cats':cats.title(),'category_posts':category_posts}) Urls.py urlpatterns = [ ......... path('category/<str:cats>/', CategoryView, name='category-list'), ] Models.py class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name def get_absolute_url(self): return reverse('home') class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.ForeignKey(Category ,max_length=60 ,default='Others', on_delete=models.CASCADE, related_name= 'cats') def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('article-detail', args=(str(self.id))) I've tried changing using the category class but not getting the correct output yet, and also tried using 'categories_post' but that too didn't help. Any help would be appreciated! Thank You in Advance. -
Deploying two Django projects in the same port in sub directories NGINX + GUNICORN
I have a Django project running with NGINX, GUNICORN and SUPERVISOR. I want to deploy another Django project in a sub-directory, in the same domain and port. -
504 browser request timed out- Ajax+django
Browser is queuing my ajax requests and the requests are being timed out if they are not getting a response under 1 minute(TTFB>1). I tried changing timeout and setTimeout values in ajax . I checked if it is Nginx server timeout and increased the proxy_timeout values still there is no result. Can someone please explain how can I increase browser timeout values. -
In Django project, styling through JavaScript is not working
I am new in Django and Python. During working, I am trying to fix the problem all day long but failed. Everything seems okay and working on w3schools and others testing sites also. Here is the two line code from index.js- alert(window.innerWidth); document.getElementById("body2").style.color = "#0000ff"; first line shows the window's width but the second line doesn't do anything. I have tried to change color, font-size, weight...etc but nothing works where everything works fine on inline, internal or external css. Only problem on styling from JS. Here, Head section of base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>CSP: Home</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <link rel="shortcut icon" type="image/png" href="{% static 'favicon.png' %}"> <link rel="stylesheet" type="text/css" href="{% static 'base.css' %}"> {% block ecss %} {% endblock %} </head> I have linked index.js and index.css through ecss block.... -
Random database disconnects with Django and Postgresql in AWS
I'm trying to get to the bottom of a problem with Django and database connection errors. At this point I'm after debugging tips as I think the symptoms are too non-specific. Some background - I've been using this stack, deployed in AWS for many years without issue: Ubuntu (in this case 20.04 LTS) Nginx Uwsgi Postgresql (v12 in RDS - tried v13 but same errors) An AWS load balancer sends traffic to the Ubuntu instance, which is handled by Nginx, which forwards on to Django (3.2.6) running in Uwsgi. Django connects to the database using psycopg2 (2.9.1). Normally this setup works perfectly for me. The issue I have it that the database connection seems to be closing randomly. Django reports errors like this: Traceback (most recent call last): [my code...] for answer in q.select_related('entry__session__player'): File "/usr/local/lib/python3.8/dist-packages/django/db/models/query.py", line 280, in __iter__ self._fetch_all() File "/usr/local/lib/python3.8/dist-packages/django/db/models/query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python3.8/dist-packages/django/db/models/query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/usr/local/lib/python3.8/dist-packages/django/db/models/sql/compiler.py", line 1173, in execute_sql cursor = self.connection.cursor() File "/usr/local/lib/python3.8/dist-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/django/db/backends/base/base.py", line 259, in cursor return self._cursor() File "/usr/local/lib/python3.8/dist-packages/django/db/backends/base/base.py", line 237, in _cursor return self._prepare_cursor(self.create_cursor(name)) File "/usr/local/lib/python3.8/dist-packages/django/db/utils.py", line 90, in __exit__ …