Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to make django-filter lookup_expr work for JSONField via declarable fields
you can configure django-filter to apply multiple lookup expressions (lookup_expr) to various fields. this is done according docs via declarable fields as following: class UserFilter(django_filters.FilterSet): class Meta: model = User fields = { 'username': ['exact', 'contains'], 'last_login': ['exact', 'year__gt'], } source: https://django-filter.readthedocs.io/en/master/ref/filterset.html#declaring-filterable-fields in my case for field "elevation" (JSONField) unfortunately this is not working (it always returns the full result): # api/views.py from django import forms from django_filters import rest_framework as drf_filters from segment.models import Segment from rest_framework import filters class FloatFilter(drf_filters.Filter): field_class = forms.FloatField class SegmentFilter(drf_filters.FilterSet): elevation = FloatFilter(field_name='data__properties__ele__max') class Meta: model = Segment fields = { 'id': ['lt', 'lte', 'gt', 'gte'], 'elevation': ['lt', 'lte', 'gt', 'gte'], } which I use in: # api/views.py class SegmentViewSet(viewsets.ReadOnlyModelViewSet): queryset = Segment.objects.all() serializer_class = serializers.SegmentSerializer filter_backends = [filters.OrderingFilter, drf_filters.DjangoFilterBackend] filterset_class = SegmentFilter # api/serializers.py from drf_queryfields import QueryFieldsMixin from rest_framework import serializers from segment.models import Segment class SegmentSerializer(QueryFieldsMixin, serializers.HyperlinkedModelSerializer): data = serializers.DictField() class Meta: model = Segment fields = ['id', 'data'] note: on field "id" this is working. any ideas why it is not working on field "elevation"? -
In django, can I make a form from an array of objects gotten by my_model.objects.all() (for a bulk edit)
Really a list of forms for each instance of the model the form is based on.... currently: I have a list of data, currently, in the view I do a: def get_booking_list(request): object_list = HousingRequests.objects.all() return render(request, 'template.html', {'housing_list':object_list}) With this I can then in my template have a nice table built: <table> <tr> <th> User </th> <th> Check in Date </th> <th> Check out Date</th> <th> Room </th> </tr> {% for hou in housing_list %} <tr> <td> {{ hou.user.first_name }} {{ hou.user.last_name}} </td> <td> {{ hou.checkin_date}} </td> <td> {{ hou.checkout_Date }} </td> <td> {{ hou.room }} </td> </tr> {% endfor %} </table> This makes sense to me, I see a list of all my objects found that needed updating (I can even filter this list further in the view). The problem is: When a user books a room, the admin has to select which room to put them in so all the rooms say 'none', I want from the list the admin to have access to all the rooms (a list of just about 9 or so) and select which room to put each person in. So I almost want to do a bulk edit. I thought I could … -
Get value of related object by list of fields in @property
I have two model like this with following fields: Profile: -user(OTO Relation to User) -address(OTO to Address) -bio -gender ... Address: -postal_code -phone_number -zip_code I Also I have this list of fields name: my_list = ["bio","gender","address.postal_code","address.phone_number", "address.zip_code"] And finally I want to I create this @property: @property def is_complete_profile(self): ''' Checks if all the fields have been filled ''' if self.pk: for field_name in my_list: value = getattr(self,field_name) if not value: return False return True else: return False But for related objects this isn't the correct way and I got this error: 'Profile' object has no attribute 'address.postal_code' How Can I use this list for get value of field of Profile objects and related object values? Notice: I could solve this problem by using eval function, but because of this and this post, I preferred to throw this solution away. -
CSS not loading in Django project?
I'm new to Django but have been tasked with doing the front-end work for the project. I've been researching how exactly to load the css files and the methods I've found just aren't working. Here is the .html file layout: {% load static %} <html> <head> <title class="title"> NHSEE Homepage </title> <!--<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> --> <link rel="stylesheet" href="{% static 'css/homepage.css' %}"> </head> <body> <div class="container"> <h1> NHSEE </h1> <a class="btn btn-1" href="/judges">Judges</a> <br> <a href="{% url 'students' %}">Students</a> <br> <a class="btn btn-1" href={% url 'scoring-sheet' %}>Scoring Sheet</a> <br> <a href="/students">Students</a> <br> <a href="/projects">Projects</a> </div> Here is the layout of the files (not sure if its where I'm putting the files that causing the issue) Any help is greatly appreciated. Its very frustrating as I've done frontend work professionally before and can't get a stupid css file to show up. -
Python Flask Creating an Infinite scroll feature
i am new to python flask and have been struggling to implement a scroll feature. I have a database (SQLAlchemy) with text, and i would like to display the text as the person scrolls until it reaches the end. Currently, i have all of the text displaying at once. I have tried googling it no end; i might have not searched the right terms. My Questions: 1.Does anyone know a good resource, or have some pseudocode? 2. Do i have to use JS? -
Djang Exception Type: SMTPAuthenticationError on the server
I want to register on my site http://193.124.206.34/accounts/register/ received error Request Method: POST Request URL: http://193.124.206.34/accounts/register/ Django Version: 2.1.1 Exception Type: SMTPAuthenticationError Exception Value: (534, b'5.7.14 Please\n5.7.14 log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 t24sm267392edc.56 - gsmtp') Registration works correctly on the localhost What should I do to fix the error? I think that I should change utilities.py variable host = "http://localhost:8001" settings.py DEBUG = True ALLOWED_HOSTS = [ '193.124.206.34', '2a00:f940:2:4:2::fea', '193-124-206-34.cloudvps.regruhosting.ru', '127.0.0.1', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') AUTH_USER_MODEL = 'vacancy_list.AdvUser' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'alekmosk25@gmail.com' EMAIL_HOST_PASSWORD = '*****' DEFAULT_FROM_EMAIL = 'Alex' DEFAULT_TO_EMAIL = '****@gmail.com' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' ... models.py from .utilities import send_activation_notification user_registrated = Signal(providing_args=['instance']) def user_registrated_dispatcher(sender, **kwargs): send_activation_notification(kwargs['instance']) user_registrated.connect(user_registrated_dispatcher) ... utilities.py signer = Signer() def send_activation_notification(user): if ALLOWED_HOSTS: #host = "http://" + ALLOWED_HOSTS[0] host = "http://localhost:8001" else: host = "http://localhost:8001" context = {'user': user, 'host': host, 'sign': signer.sign(user.username)} subject = render_to_string('vacancy_list/activation_letter_subject.txt', context) body_text = render_to_string('vacancy_list/activation_letter_body.txt', context) user.email_user(subject, body_text) forms.py class RegisterUserForm(forms.ModelForm): email = forms.EmailField(required=True, label="Email") password1 = forms.CharField(label="Password1", widget=PasswordInput, help_text=password_validation.password_validators_help_text_html()) password2 = forms.CharField(label="Password2", widget=PasswordInput, help_text=password_validation.password_validators_help_text_html()) def clean_password1(self): password1 = self.cleaned_data['password1'] if password1: password_validation.validate_password(password1) return password1 def clean(self): super().clean() password1 = … -
Showing different results for saved machine learning model in ipynb file and in django
The results in ipynb : array([[0.99998873, 0.34232343, 0.97835689, 0.11738408, 0.96085243, 0.03861971]]) Results in django : [[0.07742869 0.00020369 0.00456771 0.00032158 0.00515316 0.00088939]] The code of views.py is shown below, vect = TfidfVectorizer(max_features=40000,stop_words='english') target = ['toxic','severe_toxic','obscene','threat','insult','identity_hate'] data = pd.read_csv('train.csv') X = data.comment_text xt = vect.fit_transform(X) input_comment1 = str(input_comment) input_comment1 = [input_comment1] input_comment1 = vect.transform(input_comment1) load_model = joblib.load('lr.pkl') output_class = load_model.predict_proba(input_comment1).toarray() print(output_class) -
Use django filter_horizontal with images
I use filter horizontal between some model and Image model as m2m I want to use it with not only title of image in filtering windows, but also image render. Whats the right way to resolve it? -
Check is_null for list of field in Django queryset filtering
I have create model with this fields: field_1 , field_2, field_3, ... , field_n And I want to filter all objects that these k fields: field_1 , field_2, .... , field_k of those objects is n't Null. My wrong answer: I did think that I must create this list of fields that I want to set in my query: my_list = [`field_1` , `field_2`, .... , `field_k`] and create my query like this: my_objects = Class.objects.filter([ (eval(field_name +"__isnull = False") ) for field_name in my_list ]) But it was wrong. How can I do that? -
Change datetime format in django or convert it to default
How do I convert custom datetime value ex. "15:22:03 13/11/2019" to "13/11/2019 15:22:03" to add value as datetime in models? Or how do i change default django datetime format? thank you -
Problem with making a post request in django rest testing
I am working on testing a view that requires authentication to make a post request user = User.objects.get(id=1) self.client.force_login(user=user) response = self.client.post(url, data, format="application/json") self.assertEqual(response.status_code, status.HTTP_201_CREATED) I am trying to get a specific user object to make force authentication but it fails to retrieve the objects and pops up the following error System check identified 6 issues (0 silenced). WARNING:rollbar:Rollbar already initialized. Ignoring re-init. WARNING:django.request:Unauthorized: /v2/smsreader .EWARNING:rollbar:Rollbar already initialized. Ignoring re-init. . ====================================================================== ERROR: test_create_valid (dialer_app.tests.SMSReaderViewTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/ehab/Desktop/raseedi/raseedi/dialer_app/tests.py", line 45, in test_create_valid user = RaseediUser.objects.get(id=1) File "/home/ehab/Desktop/raseedi/envraseedi/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/ehab/Desktop/raseedi/envraseedi/lib/python3.6/site-packages/django/db/models/query.py", line 408, in get self.model._meta.object_name users.models.User.DoesNotExist: User matching query does not exist. ---------------------------------------------------------------------- Ran 3 tests in 0.031s FAILED (errors=1) Destroying test database for alias 'default'... any help with that error? -
Editing the uploaded picture in Django
I want to give the user the opportunity to edit a picture to the post. Below I give the full code of the function responsible for this action. But unfortunately, when editing a post, the user can only delete the existing picture, there is no way to upload a new one. It seems that the function does not see the transmitted "request.FILES" - if i take this away her behavior will not change. What am I doing wrong? full function code in views.py: def edit_post(request, post_id): post = Post.objects.get(id=post_id) if request.method != 'POST': form = PostForm(instance=post) else: form = PostForm(request.POST, request.FILES, instance=topic) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('app:post', args=[post_id])) context = {'post': post, 'form': form} return render(request, 'app/edit_post.html', context) -
Django: Difference between localhost:8000 and 127.0.0.1:8000?
I am running a Django project, and upon using python manage.py collectstatic in my terminal, my admin page stopped loading the css files and is in a raw html format. This is when I ran it using 127.0.0.1:8000. However, using localhost:8000, the css files load normally. What is the difference and why doesn't it work both ways ? -
Page not found Error. Am new to web development with the framework
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/music/1/ Using the URLconf defined inenter code hereVibezT.urls, Django tried these URL patterns, in this order:enter code heredmin/enter code heremusic/ ^$ [name='index']enter code heremusic/ (?p[0-9]+) [name='detail'] The current path, music/1/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and django will display a standard 404 page. enter code hereurls.py enter code herefrom django .urls import path enter code herefrom . import views check the URL the user is requesting enter code hereurlpatterns = [ enter code herepath(r'^$', views.index, name='index'), /music/71/ enter code herepath(r'(?p[0-9]+)/', views.detail, name='detail'), ] enter code hereviews.py enter code herefrom django.shortcuts import render Create your views here. enter code herefrom django.http import HttpResponse enter code heredef index(request): enter code herereturn HttpResponse("This is My First App HomePage") function for details page enter code heredef detail(request, album_id): enter code herereturn HttpResponse("Details for Album: "+ str(album_id) +"") -
django:redis:CommandError: You have not set ASGI_APPLICATION, which is needed to run the server
I am trying to create socket in django. I installed asgi_redis as per this link. When I ran the command python manage.py runserver, I am getting below error. >python manage.py runserver CommandError: You have not set ASGI_APPLICATION, which is needed to run the server. As I havent started the redis, above error might be because of this. I am bit confused , do I need to install Redis separately or just need to start the redis as I have already installed the asgi_redis? project/settings.py file entry for redis. CHANNEL_LAYERS = { 'default': { 'BACKEND': 'asgi_redis.RedisChannelLayer', 'CONFIG': { 'hosts': [('localhost', 6379)], }, 'ROUTING': 'example_channels.routing.channel_routing', } } -
Django CITextField unique name field, cant change casing of name without error
We want to ensure case-insensitive uniqueness for our product names so switched the model field type to CITextField. This works great however if we want to change the casing on an existing product it complains that the product already exists when you try and save it. (when it doesn't of course) Any ideas on how we can get around this? Ta -
Django select_related does nothing
I have a comment model in django which contains a foreign key reference to the User model and I'm trying to lookup comments (of a certain post ID) and then join/get the user data of the author of the commment. This is what I'm doing result = Comment.objects.filter(post=post).select_related('user').order_by('-created_at') When I return the result, I get the same exact object I got before I added the select_related() function. Am I missing something here? -
AssertionError: False is not true, the tests failed every time because that reason?
i deleted the user and change the data = {} part and the issue still exist and i don't understand what is the problem . This is the other app tests : from django.contrib.auth.models import User from django.urls import resolve, reverse from django.test import TestCase from .views import signup from .forms import SignUpForm class SignUpTests(TestCase): def setUp(self): url = reverse('signup') self.response = self.client.get(url) def test_signup_status_code(self): self.assertEquals(self.response.status_code, 200) def test_signup_url_resolves_signup_view(self): view = resolve('/signup/') self.assertEquals(view.func, signup) def test_csrf(self): self.assertContains(self.response, 'csrfmiddlewaretoken') def test_contains_form(self): form = self.response.context.get('form') self.assertIsInstance(form, SignUpForm) def test_form_inputs(self): ''' The view must contain five inputs: csrf, username, email, password1, password2 ''' self.assertContains(self.response, '<input', 5) self.assertContains(self.response, 'type="text"', 1) self.assertContains(self.response, 'type="email"', 1) self.assertContains(self.response, 'type="password"', 2) class SuccessfulSignUpTests(TestCase): def setUp(self): url = reverse('signup') data = { 'username': 'johndoe', 'email': 'johndoe@gmail.com', 'password1': 'user123', 'password2': 'user123' } self.response = self.client.post(url, data) self.home_url = reverse('home') def test_redirection(self): ''' A valid form submission should redirect the user to the home page ''' self.assertRedirects(self.response, self.home_url) def test_user_creation(self): self.assertTrue(User.objects.exists()) def test_user_authentication(self): ''' Create a new request to an arbitrary page. The resulting response should now have a `user` to its context, after a successful sign up. ''' response = self.client.get(self.home_url) user = response.context.get('user') self.assertTrue(user.is_authenticated) class InvalidSignUpTests(TestCase): def setUp(self): url = … -
How to iterate through Reverse ManytoOne sets, Attribute Error
key = modelobj.__class__.__name__ keyval = modelobj.pk sets = ['cat_set', 'dog_set'] for x in set: test = eval(key).objects.get(pk=keyval).eval(x).values() print(test) The entries in the 'sets' list have a ManytoOne relationship (already defined in the model file) with the 'key'. When I run this script I get the error: "AttributeError: 'Activities' object has no attribute 'eval'" for the "eval(x)" part (the first eval(key) works fine). For instance, if I change the line to the following code, it runs fine but I need to be less explicit: test = eval(key).objects.get(pk=keyval).cat_set.values() -
How to use virtual environnement with VS Code?
I used Sublime Text so far for my Django / Python developments but I want a more complete IDE including debug and console built and my choice was focused on VS COde the problem is that I have a little trouble to start, or more exactly to launch a project I developed a project in a virtual environment venv I can not activate this virtual environment from VS Code Console I read the VS Code doc about it and you have to select a Python interpreter Ctrl + Shift + P but I do not see my virtual environment can someone explain to me and help me? thanks in advance -
Can I change the language of UserCreationFrom() html to Spanish?
I've done a register page in my django app for the users to introduce their username and password and register, I wanted to know if I could change the HTML text that the UserCreationForm() shows to spanish. This is my code so far: Views.py def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) return redirect('login') else: form = UserCreationForm() context = { 'form' : form } return render(request, 'registration/register.html', context) Urls.py urlpatterns = [ path('registration/', views.register, name='register'), ] register.html <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Register</title> </head> <body> <h1>Pagina de Registro</h1> <form method= "post" action="{% url 'register' %}"> {% csrf_token %} {% if form.errors %} <p>Hay errores en el formulario</p> {% endif %} {{ form }} <input type="submit" value="Register"> </form> </body> </html> The HTML page shows this in the browser, I want to change the HTML text to spanish but as the function creates it by itself I was wondering if I could do that. -
Update record in create mixin
Is there a "correct" way to update a record if it exists using the CreateModelMixin through the serializer?. Or this way of thinking is totally wrong ? I have the following code which i paste only the necessary code. def create(self, request): serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): //Do something if record exists for example... serializer.save() return Response(status=status.HTTP_201_CREATED) -
Why am I seeing over-eager inotify behaviour in Python/Django/runserver_plus?
I have an application (Django with Werkzeug/runserver_plus) on Linux (Fedora 30) with code-reloading when the filesystem detects a change. Unfortunately, after some upgrade (perhaps an OS upgrade) the inotify handler is picking up changes to .pyc files on each request. I start the server, then each request triggers a slew of IN_MODIFY events for .pyc files which subsequently restarts the server. It takes a while for the server to "settle" as the .pyc files are generated. There are indeed on-the-fly modifications of .pyc files happening as verified by watching inotify events independently, but they have not caused the server to restart before. How can I suppress the .pyc modifications on each HTTP request causing the server to restart when there are not source changes? (Python 2.7, Django 1.6 ... upgrading isn't an option) -
django_oauth_toolkit is returning non-sense
Recently one of my colleagues left the company and so, as the only other backend developer here, I had to take on his tasks. I'm more of a node.js, elixir,golang developer but he was a django developer. In one of his projects, he used django_oauth_toolkit for authentication and it was working until a few days ago, according to the android developer, it suddenly started returning this: access_tokenexpires_intoken_typescoperefresh_token If you pay attention, its actually all the keys that are expected to be in the response, stuck together. I have no idea what the problem is. There is no log relating to this and the settings.py seems to be fine. I really can't think of any way to go about figuring it out. What should I do? Thanks -
Error overriding jwt_response_payload_handler to send back serialized user
I've added a call to UserSerializer This is my Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model=user fields="__all__" My Custom Model from django.db import models class user(models.Model): username=models.CharField(max_length=150) firstname=models.CharField(max_length=20) lastname=models.CharField(max_length=20) email=models.CharField(max_length=40) password=models.CharField(max_length=40) type=models.CharField(max_length=10) def __str__(self): return self.firstname I have added a custom JWT Handler from login.serializers import UserSerializer def my_jwt_response_handler(token, user=None, request=None): return { 'token': token, 'user': UserSerializer(user, context={'request':request}).data } And in settings.py I have JWT_AUTH = { 'JWT_RESPONSE_PAYLOAD_HANDLER': 'login.utils.my_jwt_response_handler' } When I try to log in, I get this error? AttributeError: Got AttributeError when attempting to get a value for field `firstname` on serializer `UserSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `User` instance. Original exception text was: 'User' object has no attribute 'firstname'. Any help would be appreciated