Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Get a correct path from random data
my index page,i have image galary when some one click one of ithome page, it shoud show more information with more photos in another page.all are loading from MySQL database with forloop. I'm unable to get the detail of clicled image information from my data base.i am very new for programing. please help mesource cord of my images galley -
Django, how to set inline formset factory with two ForeingKey?
I have create a code that works perfectly except for one little problem. I have created an inline formset factory utilizing two models: Lavorazione and Costi_materiale. class Lavorazione(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali, ) numero_lavorazione=models.IntegerField() class Costi_materiale(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali) numero_lavorazione=models.ForeignKey(Lavorazione) prezzo=models.DecimalField() After I have created the inline formset facotry as the following: CostiMaterialeFormSet = inlineformset_factory( Lavorazione, Costi_materiale, form=CostiMaterialeForm, fields="__all__", exclude=('codice_commessa',), can_delete=True, extra=1 ) But I have in Costi_materiale two ForeignKey, instead in the form the formset recognise only numero_lavorazione and not also codice_commesse. I want that the formset set in the first model the codice commesse and lavorazione fields and subsequently in the inline formset the other fields. In other word: How can I set two ForeignKey in a inline formset factory? -
Django all-auth - Social login - Facebook - Pass without requesting email
So I must be missing something, I've looked for similiar questions and tried their solutions like overhere (Django allauth, require email verification for regular accounts but not for social accounts) I would like to let users interact with my webapp without requesting their e-mailadres after logging in with their social account, in this case with their facebook account. I have the following set up; settings.py ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_VERIFICATION = 'optional' SOCIALACCOUNT_EMAIL_REQUIRED = False SOCIALACCOUNT_EMAIL_VERIFICATION = 'optional' At the moment, whenever someone tries to login with their facebook account, they get redirected to the signup form requesting for their email address. Even though I'm using email as a authentication method for regular signups, this should not be necessary for social signups am I right? Best regards, Kevin -
No module named 'users.urls'
This is my urls.py: from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path( route='', view=TemplateView.as_view(template_name='posts/index.html'), name='index' ), path( route='post/my-post.html', view=TemplateView.as_view(template_name='posts/detail.html'), name='detail' ), path( route='sobre-mi', view=TemplateView.as_view(template_name='about.html'), name='about' ), path('', include(('users.urls', 'users'), namespace='users')), ] And this is the error I get when running python3 manage.py runserver: ModuleNotFoundError: No module named 'users.urls' -
Passing a dictionary to Ajax
I have an Ajax call on a on('click',) event. The data passed from my HTML is value= '{{y.id }} {{ y.id }}'. Ajax passes it to my views.py in python server side as a str . Is there a way to get it straight as a list or dictionary? Or do I have to extract it and convert it in my views.py?