Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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', … -
Creating a webclient to send and receive emails
I have to create a webclient to send and receive emails from gmail and outlook accounts. It should be able to run directly in a browser with any setup on the computer. Here are the important details: I have planned to use imaplib and smtp library in python. It will be a django project. I will use react for the frontend. And mondodb to store some data in a database. And aws for deployment. The webclient will be used by approximately 10 people. The webclient will have many functionalities not available in other clients. So my question is, Is it possible to create such webclient or am i missing anything like protocols, security or hardware requirements? You might find this question as not exactly related to programming, but it is important for me to get an answer. As I am new to djando and mongodb, i want to make sure that I don't waste my time trying to create something which is not possible. -
Django: How can I create a group in django similar to a Facebook group?
Hello guys I am quite new to django. I am thinking of creating a group like feature where a user can create a group and be an admin and can add other users to the group similar to a facebook group. How to do this with django? any leads or a rough idea to start with will be much appreciated. Thanks -
Ajax POST request 200 but Form is not valid
I am working to add comments and replies via Ajax and the POST.request is ok however the form itself is not valid hence no data is being saved in the DB. Please see below some of my code: Views def view_post(request, slug): post = Post.objects.get(slug=slug) comments = post.comments.filter(approved_comment=True, reply=None).order_by('-date_posted') form = CommentForm() if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) reply_id = request.POST.get('comment_id') data = None if reply_id: data = Comment.objects.get(id=reply_id) comment.author = request.user comment.post = post comment.reply = data comment.save() else: print('form not valid') else: form = CommentForm() context = { 'post' : post, 'comments' : comments, 'form' : form } if request.is_ajax(): html = render_to_string('blog/comments.html', context, request=request) return JsonResponse({ 'form' : html }) return render(request, 'blog/post.html', context) and here is the Ajax request $.ajax({ method: 'POST', url: `/post/${slug}/`, data: $(this).serialize(), dataType: 'json', success: function(response) { $(event.target).parents('.reply-form').hide() $('main-comment-section').html(response['form']); $('textarea').val(''); }, error: function(rs, e) { console.log(rs.responseText); }, }) event.preventDefault(); }) I would appreciate any guidance. Thanks! -
How can I position an icon next to a label in a crispy modelform?
I have a modelform and append a font awesome icon next to the first_name field: class StudentForm(forms.ModelForm): class Meta: model = Student fields = ['first_name',] def __init__(self, *args, **kwargs): ... self.helper.layout = Layout( AppendedText('first name', mark_safe('<span class="fas fa-user"></span>')), } How can I appen an icon to the fields label? I want to append a help icon which the user can click on to get hints on the field. -
Handling multiple types of users in Django
I am building a django app that will need to have two types of accounts (Merchant and Buyer), not that it matters but just to provide more context, on my sign up page, I have a radio button to let the user choose if they want to register as a Merchant account or as Buyer account, and each account type will have a separate sign in page to login to the website. I was thinking of using this approach. Please ignore discrepancies in the code, it was simplified just for the question. class User(AbstractBaseUser): first_name = models.CharField() last_name = models.CharField() date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) class Merchant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(unique=True) ph_number = models.CharField() class Buyer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(unique=True) As you can see each account can have unique fields like the ph_number so I came up with this approach after some research. Question 1 While inheriting AbstractBaseUser I need to have a uniquely identifiable field to assign to USERNAME_FIELD, in my case I don't really have one for the User, so what do I use here? I intend to have two custom authentication back-ends to use the email field from the Merchant … -
How to send request ` update view` from django rest_framwork
I'm doing a project - where the front-end vuejs and back-end drf - It works after I request a gate on my api, but when someone clicks on my content, there will be one view count and the property name of my api's view account will change one by one - but it doesn't move. Because the post method is the second time that the value is not updated - What can be done for this -
ImportError: cannot import name 'cmdoptions' from 'pip._internal.cli'
Has anyone seen this particular error, "ImportError: cannot import name 'cmdoptions' from 'pip._internal.cli'"? This preventing any pip installs. Is there a fix for this. I am currently running python 3.8. Thanks!! -
Changing property on model when all foreign key objects have property set to true
I am just starting with django, django rest api. And I created first easy Todo app in django rest API. I was wondering how i would achieve changing Task Complete status to true automatically if all subtasks are completed Thanks in Advance for all answers -
how to insert in parent model if i add in chield model in django using django admin
i have 3 Models as the follwing: 1- parent models "Batches" contain id & tabel name class Batch(models.Model): table_name = models.CharField(max_length=255) 2- Chield model 1 "Table 1" class Table1(models.Model): text = models.CharField(max_length=255) batch_num = models.ForeignKey(Batch, on_delete=models.CASCADE) 3- Chield model 1 "Table2" class Table2(models.Model): text = models.CharField(max_length=255) batch_num = models.ForeignKey(Batch, on_delete=models.CASCADE) i need if add any transaction in table1 or table2 cereat transaction in parent model "Batch" and fill class name in parent table. is there any good idea to make this throug django admin note: i tried TabularInline but this is work when i add parent frist then allocate chield to parent. -
Change default permissions for Users
I want to change the default permissions for Users so that they are only permitted to delete other objects that they created themselves. Currently, they are permitted to delete anything. How do I change the model so that they are only permitted to delete only the objects they created and not objects that other Users created? -
Access Nested Data from JSONField in Django
I have the following model: class BaseTransaction(models.Model): """Model to store JSON data""" name = models.CharField(max_length=255) json_data = JSONField(null=True) If I create an instance with the following data: base_transaction = models.BaseTransaction.objects.create( name="Test Transaction", json_data={{"sales": 3.24, "date": "2020-06-05"}, {"sales": 5.50, "date": "2020-06-04"}, {"sales": 256.53, "date": "2020-06-02"}} ) How would I access the second row of data without a key? Or is this the wrong format for JSON? I am using this format because the original data is from a CSV and this is how it converts to JSON. -
how to deploy a system built with angular and django on Centos7?
I'm trying to deploy an application that I built using AngularJS for frontend and Django for backend on Centos7, but when I get both, frontend and backend, on the server, I can only connect to angular page, but it do not make the request to the django API endpoint. On development environment both work correctly, angular running on localhost:4200 and django on localhost:8000 but when on server they do not comunicate. How should I deploy both of them to make they communicate? -
autocomplete fields in Django
Trying to set up autocomplete_fields in django. I have following model: from django.db import models class Genre(models.Model): title = models.CharField(max_length=255) class Movie(models.Model): title = models.CharField(max_length=255) year = models.IntegerField() time = models.CharField(max_length=255) director = models.CharField(max_length=255) genre = models.ManyToManyField(Genre) image = models.ImageField(upload_to='images/') actors = models.TextField() summary = models.TextField() admin.py: from django.contrib import admin from .models import Movie, Genre class SettingAdmin(admin.ModelAdmin): search_fields = ['genre'] class MovieAdmin(admin.ModelAdmin): autocomplete_fields = ['genre'] admin.site.register(Movie, MovieAdmin) admin.site.register(Genre) Error Message: Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\ali\appdata\local\programs\python\python38\lib\threading.py", line 932, in _ bootstrap_inner self.run() File "c:\users\ali\appdata\local\programs\python\python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Ali\Desktop\cinemaEnv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Ali\Desktop\cinemaEnv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Ali\Desktop\cinemaEnv\lib\site-packages\django\core\management\base.py", line 441, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'movies.admin.MovieAdmin'>: (admin.E040) ModelAdmin must define "search_fields", because it's referenced by MovieAdmin.autocomplete_fields. i try this code with User model from django.contrib.auth.models and it worked. i try this code with User model from django.contrib.auth.models and it worked. -
How to implement download data option for web app
I am developing a feature to a web app ( dictionary-like app ) - a download option. It means that a user can request to download data ( of certain models ). As a reference I can mention the download button here https://wals.info/languoid. I want to keep the files that I want to download up to date and it consists of millions of record. Example... I want to download all the words of English language in some format (word, csv etc). Querying everything from the db would be impossible as it would take a lot of time. I am using Django framework with a postgreDB. Can you suggest me some efficient way of approaching that. -
How do i specify the version of a module(django) on atom?
I'm trying to run a code I imported from github on my laptop. I think i know where the problem is; as the code is using django v2, and when I do : python -m django --version on my laptop it tells me I'm running on django v1. I installed django v2 but can't "connect it". I guess my problem is in the path taken, could anyone help? -
Getting Forbidden (CSRF token missing or incorrect.): /accounts/login while making post request through postman
I am trying to login to my user model in django using postman views.py from django.shortcuts import render from rest_framework.viewsets import ModelViewSet from useraccount.serializer import UserSerializer from useraccount.models import User class UserViewSet(ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() urls.py from django.urls import path,include from rest_framework.routers import DefaultRouter from useraccount.views import UserCreateViewSet from django.contrib.auth.views import LoginView user_router = DefaultRouter(trailing_slash=False) user_router.register('user',UserCreateViewSet) user_router.register('signup',UserCreateViewSet) urlpatterns = [ path('',include(user_router.urls)), path('login',LoginView.as_view()), ] when trying using postman providing the username and password i am getting Forbidden (CSRF token missing or incorrect.): /accounts/login i am using default auth.view to login like LoginView i am not using any kind of authentication method like basicauth,tokenauth or session auth while working with django rest framework please tell me if while dealing with rest framework i have to use one of the above three method of auth or if not necessary then how to deal with this problem in postman