Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the best practice for storing glabal variables of a django App?
There are a few variables that are unique for my website. For Illustrative purposes let's assume it is a Blog, and the variables I am interested in are the total number of users, the total number of posts, the total number of comments in posts, the average length of a user session, and a few others. I can create a model with these parameters, and it will have a single row with all the values, but this might be a bit of an overkill. I was wondering if there was a better (pythonic?) way of doing this. -
Python Django multiple attributes in search
So I have this search form: [Doctor][Specialty][City] This is the form in HTML: <form data-provide="validation" data-disable="true" class="input-glass mt-7" method='POST' action='annuaire/'> {% csrf_token %} <div class="row"> <div class="col-md-4"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"><i class="ti-search mt-1"></i></span> </div> <input type="text" class="form-control" placeholder="Doctor's Name" name="kw_name"> </div> </div> <div class="col-md-4"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"><i class="ti-search mt-1"></i></span> </div> <select class="form-control" name="kw_specialty"> <option value="" disabled selected>Specialty</option> {% for spec in specialties %} <option>{{ spec }}</option> {% endfor %} </select> </div> </div> <div class="col-md-4"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"><i class="ti-search mt-1"></i></span> </div> <select class="form-control" name="kw_city"> <option value="" disabled selected>City</option> {% for city in cities %} <option>{{ city }}</option> {% endfor %} </select> </div> </div> </div> <div class="row mt-2"> <div class="col-md-12"> <button class="btn btn-lg btn-block btn-outline-light" type="submit" name="search_btn">Search</button> </div> </div> </form> Before I talk about my view.py content, I would like to mention my problem first: The search form has many cases, and the users don't have to fill all three filters. But if they leave the text input empty, the results will be ALL. I want the search function to ignore the text field if it's empty (only consider it if it has a value in it). Also, if the 2 dropdowns are Null … -
Django checking if same object exists in database when user trie to add object:
I have an application that users can take what courses they are taking and there is a many to many relationships between users and a course. Now when a user wants to add a course I want to check if they have not added the same course with the partial same value, for example, the same course code and year. Currently, my view is: @login_required def course_add(request): if request.method == "POST": form = CourseForm(request.POST or none) if form.is_valid(): course = form.save(False) for c in request.user.courses.all(): if course.course_code == c.course_code and course.course_year == c.course_year: form = CourseForm message = "It's seems you already have added this course please try again." context = { 'form':form, 'message': message, } return render(request,'home/courses/course_add.html', context) request.user.courses.add(course) return redirect('home:courses') else: form = CourseForm context = { 'form':form } return render(request,'home/courses/course_add.html', context) in my user model I have this line: courses = models.ManyToManyField('home.Course',related_name='profiles') an my course model is: class Course(models.Model): course_code = models.CharField(max_length=20) course_name = models.CharField(max_length=100) course_year = models.IntegerField(('year'), validators=[MinValueValidator(1984), MaxValueValidator(max_value_current_year())]) def __str__(self): return self.course_code As you can see my intention is I don't want the user to be able to add a course if they're code and year exists regardless of the course name. How can I … -
Deploy Django app on Raspberry Pi with Domain Name
I am creating an application which will need to access a database. Since it is a small scale application I do not want to spend a ton on hosting and have a pi lying around. My plan was to have an SQL server and some sort of API on a pi and access it from the application (on other networks also). Is there an easy way to access a Django app via a purchased domain name on the pi and if so could someone list the basic steps. Otherwise, is it just better to spend a few dollars a month to host it on Digital Ocean or something similar? Thanks in advance. -
How to serve a Flutter web app with Django?
After building a flutter web app with flutter build web I want to serve the app using a simple Django server. How can I do that? -
Django-Filters Lookup_expr type 'AND'
Does Django-Filters have a lookup_expr equivalent to 'AND'? I am using Django filters with DRF to filter by multiple categories on the same field. Example: I have a category list field that accepts multiple categories categories = ['baking', 'cooking', 'desserts', 'etc'] Using the solution outlined by udeep below I got the filter to work rather well https://stackoverflow.com/a/57322368/13142864 The one issue I am running into is with the lookup_expr="in" This works as an 'OR' expression. So if I provide a filter query of categories=baking,cooking It will return all results that contain either 'baking' OR 'cooking' Is there a lookup_expr in django_filters that profiles an 'AND' functionality so that when I make the same query I get only results that contain both 'baking' AND 'cooking'? I have looked at all of the django filter docs https://django-filter.readthedocs.io/ And all of the django queryset filter where many of these type of filters seem to originate from https://docs.djangoproject.com/en/3.0/ref/models/querysets/ But unfortunately, I have had no luck. Any direction you can provide would be much appreciated. -
ModuleNotFoundError: No module named 'rest_framework.filtersuser'
I'm getting this weird error after adding rest_framework.filters. Things I tried:- 1) Removing then re-installing. 2) Tried using django-filters instead. I have included rest_framework.filters in installed apps in settings.py. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\python37\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\python37\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "E:\virtual environments\leaseit_api\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "E:\virtual environments\leaseit_api\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "E:\virtual environments\leaseit_api\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "E:\virtual environments\leaseit_api\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "E:\virtual environments\leaseit_api\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "E:\virtual environments\leaseit_api\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "E:\virtual environments\leaseit_api\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "E:\virtual environments\leaseit_api\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework.filtersuser' -
Django-rest-framework: different - django.db.utils.IntegrityError: NOT NULL constraint failed: accounts_user.password
I am using django-rest-auth for authentication. Registration,login,logout are working properly but when I try to edit user detail through admin panel, password field is behaving like not required field neitherless it is not nullable field and therefore giving me following error. Does anything wrong in the code,Please help me out with it. models.py class CustomUserManager(BaseUserManager): def _create_user(self,username, email, password, is_staff,is_admin, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have an username') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, username=username, is_staff=is_staff, is_active=True, is_admin=is_admin, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self,username, email, password=None, **extra_fields): return self._create_user( username, email, password, False, False, False, **extra_fields) def create_staff(self,username, email, password, **extra_fields): user = self._create_user( username,email, password, True, False, False, **extra_fields) user.save(using=self._db) return user def create_admin(self,username, email, password, **extra_fields): user = self._create_user( username,email, password, True, True, False, **extra_fields) user.save(using=self._db) return user def create_superuser(self,username, email, password, **extra_fields): user = self._create_user( username,email, password, True, True, True, **extra_fields) user.save(using=self._db) return user class User(AbstractBaseUser): username = CharField(_('username'), max_length=100,unique=True) email = EmailField(_('email address'), unique=True) is_staff = BooleanField(default=False) is_admin = BooleanField(default=False) is_active = BooleanField(default=True) is_superuser = BooleanField(default=False) last_login = DateTimeField(auto_now=True) date_joined = DateTimeField(auto_now_add=True) full_name = … -
Django 3, non ASCII signs handling
I have a problem with special signs, for example polish signs (ą,ć,ń,ź etc). When I'm adding some model object to database using django server it malform to some completely different signs. It looks like some problem with coding signs, but database looks kind good because when I add new row directly in MySQL Workbench then signs are correct. But when I'm doing it with django and Django rest framework to be more specific, then signs are changing into something else. -
VUE CLI error: Access to XMLHttpRequest has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
Sorry if this question has been answered. I've searched over 40 answers on StackOverflow, vuejs forum, blogs, etc, but they don't work, or I don't understand them. Please point me in the right direction if necessary. I'm running two servers locally. One VueCLI 127.0.0.1:8080 and the other, my django project with django restframework 127.0.0.1:8000. I get the following error when I call the API (note that it includes the last forward slash): Access to XMLHttpRequest at 'http://127.0.0.1:8000/…/‘ from origin 'http://127.0.0.1:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. However, I get a 200 response on my django server (so it's hitting the server, and the server is responding): [03/May/2020 18:20:10] "GET /api/inventory/product/ HTTP/1.1" 200 7893 I've installed django-cors-header and setup settings.py accordingly: CORS_ORIGIN_WHITELIST = [ 'http://127.0.0.1:8080', ] INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', .... ] This is my call from my VueCLI component: const axios = require('axios') let url = `http://127.0.0.1:8000/api/inventory/product/` axios .get(url) .then(response => { console.log(response) }) Please point out what I'm doing wrong or what I should do. -
Django can not find my template, when it is actually in the templates directory inside the app
I am working in some CRUD views using class based views from django but when i want to add a createview Django returns an error saying that the template does not exists when in fact there it is, but i cant not find any error. View class SchoolCreateView(CreateView): model = School fields = ('name','principal','location') school_form.html Template {%extends 'firstapp/base.html'%} {%block body_block%} <h1> {%if not form.instance.pk%} Create School {%else%} Update School {%endif%} <form method="POST"> {%csrf_token%} {%form.as_p%} <input type="submit" value="submit"> </form> </h1> {%endblock%} -
How Can I get the location of a user app from another user of same app
I’m trying to build a simple pick up and delivery app. I want a user to submit a pickup location and delivery location. Then as soon as the user submits I want to be able to get the locations of the riders’ apps but I don’t know how to go about it. It’s just like a normal for example uber app that searches the drivers locations and calculates the nearest one. Calculating the nearest one is not the issue as I can do that with google maps api, but how can I get the riders app location from the backend.? Thank you in advance. -
Inline Boostrap Cards using Django For Loop
I am using Bootstrap to make my website loop better, but I am having trouble organizing my cards in a horizontal line since I am using Django For loop to render information: html <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Coaches</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </head> <body> <div class="container"> {% for programas in programas_entrenamiento %} <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{{programas.foto_programa.url}}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{programas.programas}}</h5> <p class="card-text">{{programas.descripcion|truncatechars:50}}</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> {%endfor%} </div> models.py class ProgramasEntrenamiento(models.Model): programas = models.CharField( choices=EXERCISE_CHOICES, max_length=200, null=True) descripcion = models.TextField() foto_programa = models.ImageField(upload_to='pics/programas', null=True) def __str__(self): return self.programas Current output Expected output (sorry for bad editing) -
DjangoCMS carousel slider doesn't fit to fullscreen
i am working on a project in Djangocms. In frontage i want to put a background carousel. When i put the image sliders on it through edit, it doesn't fit to screen. i try use fluid container but it shows padding/space around it. Besides i tried to use style row column along with alignment through edit in toolbar, padding grows bigger. Should i have to do manual coding? is there any document on Djangocms carousel plugin? what is the way to edit the carousel design in Djangocms? -
Django runserver shows just blank page
I am currently trying to setup the Django web app from https://github.com/fiduswriter/fiduswriter. When I run python manage.py runserver localhost:8000 I do not receive any errors when accessing localhost:8000, but there is no page coming up. However, when I build the Docker image resp. pull the one from https://hub.docker.com/r/moritzf/fiduswriter/, I can start it and it shows the starting page. How is this phenomenon explicable? -
send_mail only works in terminal in django
I'm trying to get my website to send a email when a button is pressed. However, it only sends a email when I use send_mail in the shell and does nothing when the button is pressed. I currently have the following in my settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = '#' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_PASSWORD = '#' The # is of course only there for this question In my html file I have <form method="post"> {% csrf_token %} <button type="submit" name="place_order" class="btn btn-success"> Place Order</button> </form> the place_order links up with my views.py which checks whether or not the button is clicked checkout = request.POST.get('place_order') if checkout: send_mail('Django test mail', 'this is django test body', '#', ['#'], fail_silently=False,) messages.info(request, f'Your order has been placed!') -
Django Index not took in account for existing table
I use existing mysql table with Django Rest Framework. On a big mysql table, a simple select request in phpmysql tooks 10 seconds without index. With an index on a field, it tooks 3ms. So I added manualy the index with phpMysql, but Django still takes 10 seconds to execute the request and dosn't see the new index. I added db_index=True in my field in models.py. But make migration didn't see any update on my already existing models, and the speed is still 10s. (Any updates on tables created by django work very well) I decided to remove my index manualy with phpmysql, and I created by my self a 0002_initial.py file with this code : from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tutorials', '0001_initial'), # or last mig ] operations = [ migrations.RunSQL("CREATE INDEX idx_last_name ON crm_users (us_last_name(64))") ] I ran migrate, and django creates the index in the table. But Django still takes 10s to perform one select on the indexed field and dosn't use the mysql index. My question : Where and how can I say to django to use indexes for existing table not created by Django ? Thank you very much ! -
Django serializer error expected number but got [28]
I'm new to Django and Python, I'm using Django-rest-framework for building RESTfull API. I have a view like this class ProfileViewSet(APIView): # to find if isAuthenticate then authentication_classes = (TokenAuthentication,) permission_classes = [permissions.IsAuthenticated] def post(self, request): user_id = request.data['user_id'] request.data.pop('user_id') request.data['user_id'] = int(user_id) serializer = ProfileSerializer( context={'request': request}, data=request.data) if serializer.is_valid(): serializer.create(validated_data=request.data) return Response(serializer.data) return Response(serializer.errors) and my serializer goes something like this class ProfileSerializer(serializers.ModelSerializer): # id = serializers.IntegerField(source='profile.id') user_id = serializers.IntegerField(source='user.id') user = serializers.PrimaryKeyRelatedField( read_only=True, default=serializers.CurrentUserDefault()) profile = Profile # depth=2 class Meta: model = Profile fields = ('id', 'user', 'image', 'first_name', 'last_name', 'description', 'mobile', 'current_location', 'user_id') read_only_fields = ('user', 'user_id') from my frontend, I'm sending user_id as a string so I'm parsing it to number. error:- TypeError: Field 'id' expected a number but got [28]. -
receiving updates from server in multi user environment
So I'm currently working on an application with react frontend and django backend. My application is a multi user application ,i.e, at max 20 users would be connected for a single task. Now, UserA makes some updates and calls the REST API, how to tell UserB,C,D ..etc that a change has happened? One way would be to create another rest api which all users will hit in some setIntervalto get updates but I don't think that is a good idea. What are the best ways to this in the scenario? Also, I would have a chat room for this , should I go for xmpp or rather use django channels? -
Updating content without refreshing page in django
Can someone give me a code for django template for updating time without refreshing the page? Currently ive stored time in a variable in views and im passing it dynamically to the html, but it does not update without reloading. People suggest ajax but im new to all this and idk much, so please provide the easiest ans😅. Thanks in advance :) -
how to read and process doc files in Django to count words inside the file
I'm trying to let the user add a .doc file using a form in Django, but it keeps giving me the error : a bytes-like object is required, not 'str' Here is my code : def upload_quota(request): upload_file_form = FileReplaceForm(request.POST , request.FILES) if request.method == 'POST': if upload_file_form.is_valid(): file = upload_file_form.cleaned_data['file'] data = file.read() word = data.split(" ") print(len(word)) -
Problemas con login Pagina de incio Django 3.0
Estoy tratando de aplicar mi pagina de inicio con contraseña, pero me dice que la orden no funciona, y he podido encontrar por que. este es el error que me mustra: mis urls del propyecto: from django.contrib.auth import views urlpatterns = [ path('admin/', admin.site.urls), path("empleado/", include("apps.empleado.urls")), path("liquida/", include("apps.liquida.urls")), path("usuario/", include("apps.usuario.urls")), path("login/", views.LoginView.as_view(),{'template_name':'index.html'}), ] esta es mi template para el login: % extends 'base/base.html' %} {% block title %} {% endblock %} {% block navbar%} {% endblock %} {% block content %} <br> <h1>Iniciar sesión - Login</h1> <form method="post"> {% csrf_token %} <div class="row"> <div class="col-md-8 col-md-offset-3"> <div class="form-group"> <label for="username">Nombre de usuario:</label> <input class="form-control" type="text" name="username"> </div> </div> </div> <div class="row"> <div class="col-md-8 col-md-offset-3"> <div class="form-group"> <label for="username">Contraseña:</label> <input class="form-control" type="password" name="password"> </div> </div> </div> <div class="row"> <div class="col-md-8 col-md-offset-3"> <div class="form-group"> <a href="#">Olvidé mi contraseña</a> <input class="btn btn-primary" type="submit" value="Ingresar"> </div> </div> </div> </form> Mi settings: #LOGIN_URL = '/login/' LOGIN_REDIRECT_URL = reverse_lazy('empleado:empleado_listar') Cuelaquier ayuda lo agradeceria, no logro poder aplicar el login, no me genera la plantilla de inicio y contraseña. -
I am trying to add an image in html using django framework, image does not appear
{% extends "basic_app/base.html" %} {% load staticfiles %} {% block body_block %} <div class="card text-center"> <div class="card-body" style="background-color:#F22A00"> <h5 class="card-title" style="color:black;text-align:center;">TSEC CODESTORM</h5> <p class="card-text" style="color:black;text-align:center;">A campus chapter of codecheff</p> </div></div> <img src="{% static "basic_app/images/hckathon.jpg" %}" alt="Uh Oh, didn't show!"> {% endblock %} This is the code ive used in extended index file however after trying different browsers the image is not visible. Here is a screenshot of my webpage -
How can I set up my unread message counter with my models?
So I am attempting to set up an unread message counter through a simple tag and get that in my template. Now, I'm running into a problem where a message that's sent to another user is showing up as 'unread' from my user even though it's being sent to the other user. I obviously only want messages that are sent to only MY user to be shown as unread. I'm not sure if I need to add another field to my InstantMessage model such as 'receiver' or if there's someway I can check user against request.user in my unread_messages_counter.py. unread_messages_counter.py register = template.Library() @register.simple_tag def unread_messages(user): return user.sender.filter(viewed=False).count() models.py/InsantMessage and Conversation class Conversation(models.Model): members = models.ManyToManyField(settings.AUTH_USER_MODEL) class InstantMessage(models.Model): sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'sender',on_delete=models.CASCADE ) conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE) message = models.TextField() date = models.DateTimeField(verbose_name="Data creation",default=timezone.now(), null=False) viewed = models.BooleanField(default=False, db_index=True) def __unicode__(self): return self.message -
authentication with google in django graphql app
I have a Django web application and I am using graphql APIs with graphene_django. I have my own authentication system with django_graphql_jwt. I want to have an authentication system with google too and It would be better if I can customize it Do you have any idea that what modules or libraries I can use?