Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access field values/attrs in an inlineformset_factory?
Sometimes browsers can render an empty label in a select box as -----: In a ModelForm it's easy to fix this by replacing the empty_label attr as below: class CustomModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CustomModelForm, self).__init__(*args, **kwargs) # Loop over the ModelForm fields to update field types and attributed for field_name in self.fields: field = self.fields[field_name] if hasattr(field, 'empty_label'): # Remove the first empty label '-----' field.empty_label = None However, when using an inlineformset_factory how does one do similar? E.g. MyFormSet = inlineformset_factory( Author, Book, fields=MYFIELDS, extra=0 ) -
How is GoogleAPI + Python supposed to work in 2020? Conflicting information
I have been trying to manually utilize the GoogleAPI with Django for the first time but there seems to be so much conflicting information that it's really difficult for me to figure out what the actual flow that I need to follow is in 2020. Tools: Django 2.0, Python 3.7. Google API creds are created. Everything I can find on getting me through this is from 2011-2014 and appears to be deprecated or on its way out so I'm not sure which API I'm supposed to use. I've reviewed every topic on SO I can find but each one looks different and uses different APIs. However, some people recently commented that the scopes can still be used so you can understand my confusion. The actual problem with this code is that I receive a null value back from the GoogleAPI and I can't figure out how to get the actual data from the authorized user. import json from django.http import JsonResponse import google.oauth2.credentials import google_auth_oauthlib.flow from googleapiclient.discovery import build from users.models import CustomUser, OAuthCredentials from django.shortcuts import render, redirect, get_object_or_404 from urllib.request import urlopen JSON_PATH = 'users/client_secret.json' REDIRECT_URI = 'http://localhost:8000/users/oauth/google/callback/' API_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'openid', ] def oauth_google(request): flow … -
How to handle Nonetype Error with Mommy.make?
I am trying to create a user using mommy.make, sometimes the user created successfully, but others produces and error: AttributeError: 'NoneType' object has no attribute 'scheme' Here is my code: user = mommy.make(User,first_name='lisa') I imported the User model and it has a field called first_name. -
Validation always True (blank=False) for CharField but not with DateField
I have an inlineformset_factory containing a field. When this field is a CharField (blank=False) and I run is_valid() on the formset, True is always returned even though the CharField is left blank. When I replace the CharField with a DateField (default=timezone.now(), blank=False), is_valid() will return True only when the field is filled as expected. Why is the CharField always returning True when running is_valid() on the formset but the DateField does not? Note that I want the CharField to behave like the DateField. Interestingly enough, the formset behaves as expected when both the CharField and DateField are present. Code below is shown with title and date but I have tried with only title and only date as well. Any help is appreciated. This is driving me up the wall! models.py class Author(models.Model): author = models.CharField(max_length=128) description = models.CharField(max_length=1000) class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(blank=False) date = models.DateField(default=timezone.now(), blank=False) forms.py class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ('author', 'description') class BookForm(forms.ModelForm): class Meta: model = Book fields = ('title', 'date') BookFormSet = forms.inlineformset_factory( Author, Book, form=BookForm, fields=('title', 'date'), extra=1, can_delete=False, can_order=False ) views.py class CreateAuthorView(CreateView): template_name = "author_create.html" model = Author form_class = AuthorForm def get_context_data(self, … -
Django referrer get short domain in template
I save visits referrer address on db. But It save like this domain.com/domainurl_page1.php I want to delete after from .com, How can i cut domain like this ; domain.com i call referrers list in template; {% for i in get_all_referer %} {{ i.referer }} {% endfor %} my view.py ref = request.META.get('HTTP_REFERER', 'Direct') -
Django ORM: Sum value and then create extra field showing rolling average
Is it possible, using Django's ORM to create a Sum based on a Date column and then add an extra field with a rolling average. Let's say I have a table like this, called "Sales": |---------------------|------------------|--------------| | Date | Category | Value | |---------------------|------------------|--------------| | 2020-04-01 | 1 | 55.0 | |---------------------|------------------|--------------| | 2020-04-01 | 2 | 30.0 | |---------------------|------------------|--------------| | 2020-04-02 | 1 | 25.0 | |---------------------|------------------|--------------| | 2020-04-02 | 2 | 85.0 | |---------------------|------------------|--------------| | 2020-04-03 | 1 | 60.0 | |---------------------|------------------|--------------| | 2020-04-03 | 2 | 30.0 | |---------------------|------------------|--------------| I would like to group it by Date (column "Category" is unimportant) and add the Sum of the values for the date. Then I would like to add a rolling Average for the last 7 days. I tried this: days = ( Sales.objects.values('date').annotate(sum_for_date=Sum('value')) ).annotate( rolling_avg=Window( expression=Avg('sum_for_date'), frame=RowRange(start=-7,end=0), order_by=F('date').asc(), ) ) .order_by('date') This throws this error: django.core.exceptions.FieldError: Cannot compute Avg('sum_for_date'): 'sum_for_date' is an aggregate Any ideas? -
i want to scrap and find the mp3 url
this a website that play audio mp3 and I want to use it inside my APP react native but first i must find the url of mp3 audio https://www.maghreb.space/Music/Labess/144115/Ecouter -
Gunicorn isnt finding 'memcache' module but it is found when I run python3 manage.py runserver 0.0.0.0:8000
I'm having trouble with my server. This is a multitenant project, the one in the Windows server is working fine, but the one in Ubuntu is giving me a "No module named 'memcache'" error although it is installed. I know it is installed because I ran a "python3 manage.py runserver 0.0.0.0:8001' and when I accessed by my personal browser worked fine. Gunicorn is pointing properly to my virtual env and there are no log errors when I restart the service, I'm quite desperate now. -
Problem dockerizing django api losing statics
Hi I built my docker image with my django api. When I run and go into the page the default css is missing. I realized that the STATIC_URL='/static/' worked when I work with the virtualenv activated but when I run the docker the server doesn't find the files. So to force that it finds the files I saw where the files are installed when I run the docker and open a terminal in the container. Then I changed static_url to: STATIC_URL = '/usr/local/lib/python3.6/dist-packages/rest_framework/static/' STATICFILES_DIRS = [ '/usr/local/lib/python3.6/dist-packages/rest_framework_swagger/', '/usr/local/lib/python3.6/dist-packages/rest_framework/static/', '/usr/local/lib/python3.6/dist-packages/django/contrib/admin/', '/usr/local/lib/python3.6/dist-packages/', ] With this I was trying to force the server get the files from the url where they are inside the container but even with the correct url the server returns me NOT FOUND: /usr/local/lib/python3.6/dist-packages/rest_framework/static/rest_framework/js/csrf.js Even when I use find / -name csrf.js it returns me the same url where the server says not found and I don't know how to fix this kind of problem. Any ideas? -
Abstractbaseuser and Forms in Django
I use abstractbaseuser as an option in customization, whats things that i must change in working in admin and aslo the type of forms(modelForm or form.Forms or UserCreationForm ) which i have to use ? -
How to change HiddenInput value of form
I am trying to create a url from the title of an object which is given by the user. I figured I could do this in the clean_url method of the form but it does not seem to work. def clean_url(self): url = re.sub(r'\W+', '', str(self.cleaned_data['title'])) return url How can I add form.url data to the form before saving? -
Catch externally added data to Postgres database in Django
I have a Django backend for my project using Postgres as a DB. Apart from it, I have a systemd service running and inserting a new row in a specific table in the DB. I would need to detect the moment in which a new row is inserted in the table to run a callback function, which is defined in Django. The service takes different times to complete. I would also like to make it efficient. I thought of these options: I used to use celery in the project but don't anymore. It is kind of set up already, so I thought one option would be a PeriodicTask that checks if something has been addedd. I dislike periodic tasks, though, and it is not quite precise (there could be a gap between the time the service finishes and the time the task runs). So EASY but UGLY If it were possible, I would like to use a Postgres TRIGGER to insert my callback task in the Celery queue. On paper, that sounds fast and clean. I have NO CLUE how to add something to the Celery task queue though. So CLEAN and EFFICIENT but DIFFICULT I thought of implementing a … -
howto login with CustomUser
my application have two types of users Admin(not the admin of SuperUser) , Entrepreneur i create 3 class CustomUser, Admin, Entrepreneur: models.py #user-------------------------------------------------------------------------- class CustomUser(AbstractUser): user_type=((1,"admin"),(2,"entrepreneur")) user_type=models.IntegerField(default=1,choices=user_type) email=models.EmailField(unique=True,blank=True) objects = UserManager() def __str__(self): return self.first_name #admin----------------------------------------------------------------------- class Admin(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE,primary_key=True) date_naissance = models.DateField(default=timezone.now) adresse = models.CharField(max_length=20, blank=True) def __str__(self): return self.user.first_name # Entrepreneur---------------------------------------------------------------- class Entrepreneur(models.Model): user= models.OneToOneField(CustomUser,on_delete=models.CASCADE,primary_key=True) date_naissance=models.DateField() adresse_entr=models.CharField(max_length=20,blank=True) telephone=models.IntegerField() statut_social=(('ce','celébataire'), ('ma','marié'), ('di','divorcé'), ('ve','veuf'), ) statut_social=models.CharField(default='ce',choices=statut_social,max_length=50) occupation=models.CharField(max_length=50) annnee_exp=models.IntegerField() def __str__(self): return self.user.first_name then i create a class form to use it for login forms.py class LoginForm(forms.ModelForm): class Meta: model =Entrepreneur fields={'email','password'} also a function for login and redirect to another home page views.py def login(request): if request.method =='POST': form =LoginForm() email=request.POST['email'] password=request.POST['password'] user=authenticate(request,email=email,password=password) if user is not None: login(request,user) return redirect('home.html') else: messages.warning(request,'email ou mot de passe invalide') return render(request,'login.html') in my login.html i have 2 tabs(1 by type of user) and one login form for each tab i want to login to the right place for each type of user it didn't work correctly what is my mistake? -
How do I attach a listener to a date selection in the Django admin?
I have a Django admin page for a model with a DateField called 'date': # models.py class Article(models.Model): date = models.DateField( help_text="Article publication date" ) # admin.py @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): change_form_template = "article_extension.html" I've extended the Admin add/change template for this model to include JavaScript to execute when a date is selected. In the Admin add/change page, the default widget for this field is a text element accompanied by a calendar selector. The page source does not show any code for the selector, so the only thing I can attach JavaScript to is the input box: <input type="text" ... id="id_date"> In the template's JavaScript, I've attached an EventListener for 'input' events on this input box: # article_extension.html {% extends "admin/change_form.html" %} {% block extrahead %} block.super <script type="text/javascript"> window.onload = function() { var dateInput = document.getElementById("id_date"); dateInput.addEventListener('input', dateListener); function dateListener() { console.log("date event recognized"); } } </script> {% endblock %} When I then select a date from the calender selector, the contents of the input box change to reflect the selected date, but the EventListener doesn't fire. If I manually type something into the input box, however, the EventListener fires and "date event recognized" shows up in the console. Evidently, … -
Log in with Ajax Django
I want to do my log in stuff with an ajax request so that the page doesn't reload. So instead of using a form with method="POST", I will just make a post request with the email and password field values. What are the upsides and downsides to this? How do I ensure security of the credentials? Please let me know if you have any questions! Thanks! -
how can i send formated date to api with react-datepicker
I'm trying to send a date to my API with react-datepiker and even though I set the dateFormat to yyyy/MM/dd I'm still getting "2020-06-19T04:00:00.000Z" as the value and it is whats being pushed to my API only to get an error to set the date format to yyyy/MM/dd Any ideas as to what this could be. Is this a bug? I am using react 16.5 and Django with drf for my backend the model uses DateField() and expects yyyy/MM/dd. Is there a workaround that anyone can think of? Thank you in advance! <DatePicker dateFormat="yyyy/MM/dd" selected={values.config[index].date} name={`config[${index}]['date']`} value={getIn(values, `config[${index}]['date']`) || "" } onChange={(e) => setFieldValue(`config[${index}] ['date']`, e)} className={"form-control" + (errors.date && touched.date? " is-invalid" : "") } /> -
Is django-allauth suitable for large scale applications?
recently I have come across a fairly large scale project which requires me to connect with google and facebook for login. It seems it can be easily done using django-allauth which is a third party package. I would like some experienced wisdom on the following questions: 1. Regarding safety: Is it safe to use the package on my application as my client has security at the utmost priority. 2. Regarding licences: Is it free to use commercially or will I have to purchase specific licenses. I am a beginner in the web development world so I apologize if my questions seem silly. -
How can I run a chronometer on my django host webpage?
I'm trying to insert a chronometer into my webpage, so that when a button is clicked they will have certain time to solve certain challenges. This chronometer should be unique for the hole server (anyone who can get inside will see this chronometer) and it has to be global for all the views in my web. I'm using Django. I can't find information about this, I know how to make chronometer, but how can I run it on my server and put it on all the views of my website. Thank you! -
django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2'
I am trying to run postgresql on django on docker. But it fails. Here is the docker-compose file: version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - ./django_project:/django_project command: > sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=django_project - DB_USER=postgres - DB_PASS=supersecretpassword depends_on: - db db: image: postgres:10-alpine environment: - POSTGRES_DB=app - POSTGRES_USER=postgres - POSTGRES_PASSWORD=supersecretpassword The settings.py file is: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': os.environ.get('DB_HOST'), 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASS'), } } Command to run Docker: docker-compose run --rm app python manage.py runserver Requirements.txt file: django==3.0.6 #Python-PostgreSQL Database Adapter psycopg2==2.8.5 -
Django filter parent where ALL child values meet criteria
Based on these models: class Job(models.Model): status = models.CharField(max_length=30) class Task(models.Model): job = models.ForeignKey('Job', related_name='tasks') status = models.CharField(max_length=30) I need a query that returns each Job where Job.status is null and ALL child Task.status's are "COMPLETE". For context, when all Task.status's are complete, a comparison between values in each sibling Task will occur, it should not be carried out until all siblings Task is set to "COMPLETE", so the query will return those that are complete. -
Django different output
Hello I wrote the following code: class Analyzer: def __init__(self, flashscore_id, number_matches=10): self.flashscore_id = flashscore_id self.number_matches = number_matches self.fixture = Fixture.objects.get(flashscore_id=flashscore_id) self.results = {"home": {"win":0, "lose": 0, "draw": 0}, "away": {"win": 0, "lose": 0, "draw": 0}, "h2h": {"win": 0, "lose": 0, "draw": 0}} def get_home_fixtures(self): fixtures = Fixture.objects.filter((Q(date__date__lt=self.fixture.date) & Q(league=self.fixture.league)) & (Q(home=self.fixture.home) | Q(away=self.fixture.home))).order_by('-date').all()[:self.number_matches] if(len(fixtures) == self.number_matches): logger.debug(f"Found: {self.number_matches} matches in history for: {self.fixture.home.name} in league: {self.fixture.league.name}") return fixtures logger.error(f"Could not find {self.number_matches} matches in history for: {self.fixture.home.name} in league: {self.fixture.league.name}") return None def get_away_fixtures(self): fixtures = Fixture.objects.filter((Q(date__date__lt=self.fixture.date) & Q(league=self.fixture.league)) & (Q(home=self.fixture.away) | Q(away=self.fixture.away))).order_by('-date').all()[:self.number_matches] if(len(fixtures) == self.number_matches): logger.debug(f"Found: {self.number_matches} matches in history for: {self.fixture.away.name} in league: {self.fixture.league.name}") return fixtures logger.error(f"Could not find {self.number_matches} matches in history for: {self.fixture.away.name} in league: {self.fixture.league.name}") return None def get_h2h_fixtures(self): fixtures = Fixture.objects.filter((Q(date__date__lt=self.fixture.date) & Q(league=self.fixture.league)) & ((Q(home=self.fixture.home) & Q(away=self.fixture.away)) | Q(home=self.fixture.away) & Q(away=self.fixture.home))).order_by('-date').all()[:self.number_matches] if(len(fixtures) == self.number_matches): logger.debug(f"Found: {self.number_matches} matches in history for H2H between: {self.fixture.home.name} - {self.fixture.away.name} in league: {self.fixture.league.name}") return fixtures logger.error(f"Could not find {self.number_matches} matches in history for H2H between: {self.fixture.home.name} - {self.fixture.away.name} in league: {self.fixture.league.name}") return None def validate(self, required, actual): if(actual == None): return None if(actual > required): return True return False def validate_1x2(self, x, y): if(x > y): return 1 … -
overwrite extra fields in django inlineformset factory from template
hi i want to overwrite extra parameter in inlineformset_factory from my template using js . if its possible or not please let me know class Book(models.Model): book = models.CharField(max_length=20,unique=True) author = models.ForeignKey(Author,on_delete=models.CASCADE) class Author(models.Model): author = models.CharField(max_length=30,unique=True) count = models.IntegerField() class AuthorForm(ModelForm): class Meta: model = Author fields = ['author','count'] class BookForm(ModelForm): class Meta: model = Book fields = ['book'] inlineformset_author = inlineformset_factory = (Author,Book,form=AuthorForm,extra=1) whenever a new author increase the admin define the number of book he/she writes inside count: meaning the number of books he/she writes , for example if warren buffet writes 5 books then when we add warren buffet as an author then we should generate 5 input boxes for book names , i dont want to increase input fields manually this is my template html+js i have done from front end but it still only save the last one , if extra=1 <form method="POST">{% csrf_token %} {{book.management_form}} <div class=" col-12 "> <div class="col-12 col-sm-9 col-md-12 divColor mt-2 mx-auto row " > {{form.author | add_class:'form-control col-12 col-sm-10 mx-auto'}} {{form.count | add_class:'form-control col-12 col-sm-10 mx-auto' | attr:'id:count'}} <div class="col-12 mt-5 clearfix"> <button class="col-4 mx-auto shadow-lg border-right border-left">insert</button> </div> </div> </div> <div id="BOOK" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="my-modal-title" … -
Changing the name of the sub folder inside Django Template path
I am new to Django and I have a path to my HTML file as ./templates/registration/login.html and I want to change it to ./templates/index/login.html After renaming it to /templates/index/login.html, it is still picking up the old directory /templates/registration, could not find login.html screen and it throws an error. Could someone tell me what changes we have to make in settings.py when we rename a folder name inside templates structure? -
'card' object has no attribute 'get' Django
I have a problem it allways show's me this error msg cant open the page 'katalog' (photo bottom of the post) Models.py from django.db import models # Create your models here. class card(models.Model): titulli = models.CharField(max_length= 30, null=False) desc = models.CharField(max_length= 60, null=False) qmimi = models.IntegerField( null=True) Views.py from django.shortcuts import render from django.http import HttpResponse from .models import card # Create your views here. def katalog(request, id): lista = card.objects.order_by('titulli') param = { 'listaC': lista } return HttpResponse('Hello Katalog', param) Error msg on web browser -
Images disappears from django web app deployed to heroku
I am working on a django project, writing rest APIs with django rest framework to use them in android application, my main idea is develop back end in django and front end in android, project is deployed on heroku. My application contains some inventory with the item pictures, issue is while i am uploading the image it successfully upload the image but after some time or more specifically after some hours the image disappears by it self. Here is my setting.py file """ Django settings for forBirds project. Generated by 'django-admin startproject' using Django 3.0.6. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/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 = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account', 'rest_framework', 'rest_framework.authtoken', 'Birds', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', …