Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django channels. How to select consumer when sending through channel layer?
In my application, I got two consumers with same handler names: class GeneralConsumer(AuthenticatedOnlyAsyncConsumer): async def new_message(self, data): ... async def message_update(self, data): ... async def message_delete(self, data): ... class ChatVisitorConsumer(AuthenticatedOnlyAsyncConsumer): async def new_message(self, data): ... async def message_update(self, data): ... async def message_delete(self, data): ... Consumers share same functionality, but used in different cases. I wonder, how I can pick specific consumer handler in channel layer object to use .send or .group_send, obtained from function channels.layers.get_channel_layer. -
Values from the second form - depending on the selected value of the first?
I have a Django form. In which there are two select fields from several values. The data from them is contained in the Django model database. The first field of the form contains car brands. In the second field of the form, I would like to display car models - depending on the car brand selected above. How can I make the data appear in the second field of the form depending on the selected value of the first field? class Model_for_form(models.Model): name_1 = models.CharField(max_length=150, verbose_name="Name_1") name_2 = models.CharField(max_length=150, verbose_name="Name_2") def __str__(self): return self.name_1, self.name_2 class Form_1(forms.ModelForm): class Meta: model = Model_for_form fields = "__all__" def form_1(request): context = {} form = Model_for_form(request.POST or None) if form.is_valid(): form.save() return redirect("form_0") context['form_1'] = form return render(request, "form_1.html", context) {% extends "base.html" %} {% block content %} <hr/> <div class="row"> <div class="col-6"> <form method="POST" class="post-form"> {% csrf_token %} {{form_1.as_p}} <button type="submit" class="save btn btn-light">button</button> </form> </div> </div> <br/> -
Django filter queryst after retrieving
I'm making a django website and due to the load on the database I'd like to filter the queryset after retrieving it. files = Files.objects.get(folder_id=folder_id) first_file = files.objects.filter(sequence = 0) This example throws me error, same if I tried for loop. So is it possible to filter the retrieved queryset without interacting with database ? -
How we can match Two fields from two different tables, without any relation between them?
`class ModelB(BaseModel): id = models.IntegerField() class ModelB(BaseModel): model_a_id = models.PositiveIntegerField() ` i want all the Records of ModelB where model_a_id == Model.id. Want to match Two fields from two separate models -
Django Public and private posts
I was trying to implement the public and private posts features for that i've created is_private in models and check it's values if it's true or false. Based on that i want to display private and public posts.`(E.x if is_private is set to false then posts should be visible to all user and if it is private then should be visible to only authenticated user.. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class post_model(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_private = models.BooleanField(default=True) def __str__(self) -> str: return self.title + "\n" + self.description``` views.py @login_required(login_url='/login') def home(request): form = post_form(request.POST or None) posts = post_model.objects.all() if form.is_valid(): posts = post_model.objects.all().values('is_private') for post in posts: if post['is_private']: posts = posts.exclude(is_private=False) else: posts = posts.exclude(is_private=True) else: form = post_form() return render(request, 'main/home.html', {'posts': posts, 'form': form}) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from . models import post_model class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class post_form(forms.ModelForm): class Meta: model = post_model fields = ['title','description','is_private'] post.html {% extends 'main/base.html' %} {% … -
Graphene "InputObjectType" causing encoding issues with JSONField
I have the following Django model with a JSONField inside: from django_jsonfield_backport import models as mysql class RaceReport(TimeStampedModel): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='race_reports') parameters = mysql.JSONField(blank=True, default=dict) Then, there's a custom InputObjectType which looks like this: class ParametersInput(graphene.InputObjectType): start_point = BigInteger(required=True) end_point = BigInteger(required=True) data_type = DataType() I am using the above input type inside the following Mutation: class CreateRaceReport(graphene.Mutation): class Arguments: parameters = ParametersInput(required=True) def mutate(_root, info, parameters): # noqa: N805 race_report = RaceReport.objects.create(user=info.context.user, parameters=parameters) return CreateRaceReport(race_report=race_report) A few points to note before proceeding further: The main purpose for having this custom input is to validate what gets stored in my model's JSONField. I want to allow my Frontend app to pass javascript objects as parameters instead of passing JSON strings. I can not use the GenericScalar type as mentioned here because it accepts anything and requires custom validations. Here's what I've tried/discovered so far: On executing the mutation, it throws this Object of type proxy is not JSON serializable on the following line: race_report = RaceReport.objects.create(user=info.context.user, parameters=parameters) Tried converting it to dictionary by using parameters.__dict__ method but got the same error. Tried a manaul json.dumps(parameters) but still same results. Did some research and found out the the JSONField … -
Django - User Validation
In my User Model, I have set the following fields: is_deactivated = models.BooleanField(default=False) deactivation_initiated = models.DateTimeField(null=True) deactivate_at = models.DateTimeField(null=True) Whenever any User interacts with anything on the App (clicking a button, refreshing a page, etc.), I would like to check whether 'is_deactivated' is True. If it is True, then I would like to compare the current real-world time with the 'deactivate_at' time. If the 'deactivate_at' time has passed. Then I would like to automatically log the user out, and set 'is_active=False' for the user. I am unsure of how to implement something like this. Could somebody please help me? Thank You. -
How to fix Django A server error occurred [closed]
I got this error :: A server error occurred. Please contact the administrator. -
how to make notification icon - django
navbar.html {% load custom_tags %} <div id="noti"> <i class="fa fa-bell" aria-hidden="true">{% show_notifications %}</i> </div> templatetags/custom_tags.py from django import template from nol.models import Notification register = template.Library() @register.inclusion_tag('notification/show_notification.html', takes_context=True) def show_notifications(context): request_user = context['request'].user notifications = Notification.objects.filter(to_user=request_user).exclude(user_has_seen=True).order_by('-date') return {'notifications': notifications} models.py class Notification(models.Model): notification_type = models.IntegerField() to_user = models.ForeignKey(CustomUser, related_name='notification_to', on_delete=models.CASCADE, null=True) from_user = models.ForeignKey(CustomUser, related_name='notification_from', on_delete=models.CASCADE, null=True) date = models.DateTimeField(default=timezone.now) user_has_seen = models.BooleanField(default=False) I'm trying to make notification but how to connect notification bell with count? -
Cannot add model instance to ManyToManyField in django - "None has no attribute add"
I already have seen this bug in other post, but still in trouble. I'm trying to create a social network like instagram where users will be able to publish posts (photos). I have User class which herit from AbstractUser, and got a ManyToManyField of connections: each user can connect and be connected to many users. After successfully pulling my photo from: PostForm(request.POST, request.FILES) and saving it correctly, I cannot add this photo to the current user's publications/posts and got error: 'NoneType' object has no attribute 'add' def blog_and_photo_upload(request): form = PostForm() if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): user = get_user(request) # user instance is correct with good pk post = Post.objects.create(image=form.cleaned_data['image']) # post instance looks correct also post.save() user.save() user.posts.add(post) # row doesnt work redirect('home') return render(request, 'base/upload_post.html', {'form': form}) models.py class Post(models.Model): ... image = ResizedImageField(size=[300, 300], blank=True, upload_to='posts') class User(AbstractUser): ... connections = models.ManyToManyField("self", symmetrical=True) -
in django do we need to edit the model.py to fetch the data from database and show it in html
I am working on a blog application and i am trying to modify my Sqlite table through the DB browser for Sqlite I have modified my table and created column in my sqlite3 database through DB browser for SQLite and now when i am trying to fetch the data in my django app it's not showing. My exact problem is how do i get the data of column which i modified in the database Through the db browser. When i try it with that in py shell i can see the data in my column. When i'm trying to add the column name in models.py it says duplicate column. -
Minimal reproducible example of a django project using appengine task queue (dev_appserver.py)
I am trying to create a django project which uses AppEngine's task queue, and would like to test it locally before deploying (using gclouds dev_appserver.py`). I can't seem to find resources that help in local development, and the closest thing was a Medium article that helps setting up django with Datastore (https://medium.com/@bcrodrigues/quick-start-django-datastore-app-engine-standard-3-7-dev-appserver-py-way-56a0f90c53a3). Does anyone have an example that I could look into for understanding how to start my implementation? -
Is there any possibilities to send form from fields backend to frontend with rest API?
Is there any possibilities to send form from fields backend to frontend with rest API? I tried to write form by myself with frontend, but this is not the best practice. I am expecting to get input Fields with API, so I can render it right away -
Let the user adapt the width of columns on a table
I am working on a web app (Django, Bootstrap). I would like to display a table and let the user adapt the width of the colums (as it's done on Sharepoint libraries display page). Any idea of the tools and documentation explaining how to achieve that? Notice: I am far from being an expert... let's say beginner + :-) -
I made an Apple token revocation code in Django, but don't know why it doesn't work
I wrote code like below def unlink_apple(apple_token): P8_PATH = os.getcwd() + '/config/AuthKey_Key_ID.p8' private_key_file = open(P8_PATH, 'r', encoding='utf-8') APPLE_PRIVATE_KEY = private_key_file.read() private_key_file.close() jwt_headers = { 'alg': 'ES256', 'kid': settings.APPLE_KEY_ID } jwt_payload = { 'iss': settings.APPLE_TEAM_ID, 'iat': datetime.now(), 'exp': datetime.now() + timedelta(days=180), 'aud': 'https://appleid.apple.com', 'sub': settings.APPLE_CLIENT_ID, } encoded_client_secret = jwt.encode( jwt_payload, APPLE_PRIVATE_KEY, algorithm='ES256', headers=jwt_headers, ) apple_headers = CaseInsensitiveDict() apple_headers["content-type"] = "application/x-www-form-urlencoded" apple_response = requests.post('https://appleid.apple.com/auth/revoke' + 'client_id=' + settings.APPLE_CLIENT_ID + 'client_secret=' + encoded_client_secret + 'token=' + apple_token + 'token_type_hint=access_token', headers=apple_headers) print(apple_response) print(apple_response.text) return apple_response You may understand the code if you have experience for Sign in with Apple. I want to make a token revocation function but it always responses with 'Iinvalid_client' I checked that all the ID value have no problem... Please help me to find some possible reasons for error -
How to fix the NoReverseMatch error in Django at /auth/password_change/?
When you click on "Change password" an error appears: NoReverseMatch at /auth/password_change/ Reverse for 'tabel_list' with arguments '('',)' not found. 1 pattern(s) tried: ['groups/(?P[-a-zA-Z0-9_]+)/$'] header.html {% if request.user.is_authenticated %} <li class="nav-item"> <a class="nav-link {% if view_name == 'schedules:tabel_list' %}active{% endif %}" href="{% url 'schedules:tabel_list' student.group.slug %}" > Расписание </a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Модульный журнал</a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Библиотека</a> </li> {% endif %} schedules/views.py @login_required def tabel_list(request, slug_group): DAY_WEEK_LIST = ({ 'MONDAY': 'Понедельник', 'TUESDAY': 'Вторник', 'WEDNESDAY': 'Среда', 'THURSDAY': 'Четверг', 'FRIDAY': 'Пятница', 'SATURDAY': 'Суббота', 'SUNDAY': 'Воскресенье', }) group = get_object_or_404(Group, slug=slug_group) tablets = Tablet.objects.filter(group=group) username = request.user.username student = Student.objects.get(student_id__username=username) day_week_en = [] set_day_week = [] for lesson in tablets: if lesson.day_week not in day_week_en: day_week_en.append(lesson.day_week) for day_en in day_week_en: set_day_week.append(DAY_WEEK_LIST[day_en]) context = { 'tablets': tablets, 'group': group, 'set_day_week': set_day_week, 'student': student, } return render(request, 'schedules/tabel_list.html', context) schedules/urls.py ``from django.urls import path from . import views app_name = 'schedules' urlpatterns = [ path('', views.index, name='index'), path('groups/', views.group_list_all, name='groups_list_all'), path('groups/<slug:slug_group>/', views.tabel_list, name='tabel_list'), ]` ` users/urls.py from django.contrib.auth.views import (LoginView, LogoutView, PasswordResetView, PasswordChangeView, PasswordChangeDoneView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView ) from django.urls import path from . import views app_name = 'users' from django.contrib.auth.views import (LoginView, LogoutView, PasswordResetView, PasswordChangeView, PasswordChangeDoneView, PasswordResetDoneView, … -
Django Admin restrict users to be added to more than one group
I am creating a customised Django Admin and I want to restrict users to be associated to no more than one group. I am using Django 4.1 and Python 3.11 my admin.py: from django.contrib import admin from typing import Set from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin from django.utils.translation import gettext_lazy as _ from .models import User @admin.register(User) class UserAdmin(DjangoUserAdmin): ordering = ('is_staff', 'is_active', 'email', 'organisation') list_display = ('email', 'name', 'organisation', 'is_staff', 'is_active', 'is_superuser', 'date_joined') fieldsets = ( ("Personal info", {'fields': ('name', 'email', 'password', 'organisation')}), ("Permissions", {'fields': ( # 'is_active', # 'is_staff', # 'is_superuser', 'groups', # 'user_permissions' )})) add_fieldsets = ( (None, {'classes': ('wide',), 'fields': ('name', 'email', 'password1', 'password2', 'organisation')}), ) Is there a way to change this in the admin code? Or it is possible to disable the group widget ("Choose all") on the page? if so which html page is used for groups? Thanks for any help! -
Using @fontface with DigitalOcean Spaces
I've started learning to use django and have starting working on hosting one on Digital Ocean's App platform. I'm hosting my static files on Digital Ocean's Spaces. My CSS file loads just fine. My fonts, however, do not. My file structure is as folows: Project --Static ---CSS -CSS files ---Fonts - font files I set up my @font-face in the CSS file like this: @font-face { font-family: 'poppins'; src: url('../static/fonts/Poppins-Light.woff2') format('woff2'); } and apply the font as follows: .div-name{ height: 100px; font-family: 'poppins'; font-size: 40px; } Like I said, my CSS loads just fine, the fonts are just not showing up. What am i missing? Thanks for the help. -
want to sum the Price i get in dictionary in django rest. I want to do it using Model serializers
Hii there I want to add the price field of the 2 dictionary data using model serializers. Hoever i am able to access the data but not able to sum it .Also i want to show whole data as well as the sum of price but if i use this function it only shows me wether price or data one at a time class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = "__all__" def to_representation(self, instance, a=0): a+=instance.Price return a class GenericViews(generics.ListCreateAPIView, generics.CreateAPIView, generics.DestroyAPIView,generics.UpdateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer lookup_field = 'Product_name' def filter_queryset(self, queryset): get_data = self.request.GET if get_data.get('Product_name'): return queryset.filter(Product_name=get_data['Product_name']) return queryset I get this if i add this to_representation function in Serializers i want to get the sum of these values i want to show whole data as well as the sum of price but if i use this function it only shows me wether price or data one at a time -
Why is my debug Django server takes so long to load on my localhost? I'm using Django, django-compressor, django-libsass and bootstrap
I have a problem with developing a Django website. I started out with using CDN Boostrap and JS as recommended in Boostrap 5 docs but then I wanted to customize the CSS, so I changed the setup to compile Bootstrap's source scss files with django-libsass. I followed the installation guides for django-libsass and django-compressor. What I discovered is that while everything works, it works very slow on my local machine (5-6s per opening a new page). I'm not very experienced in web development so I'm not sure what could be causing this. If it's relevant, I don't use a frontend yet and I'm sticking to Django's templates. I tried to download a sample django libsass project and put bootstrap there and the outcome was the same. I expected the time for loading the pages to increase slightly due to the fact that now it has to compile scss files but not so much. Googling turned up no results:( Is this an expected behavior when debugging from a local machine or am I missing something? Huge thanks! -
Is there a way to implement select all/select none option in django-select2?
I found a few (older) answers where someone attempted to implement a select all/select none option in a jQuery dropdown list: https://github.com/select2/select2/issues/195 Select2 select all dropdown option I was wondering, is there a way to implement such a thing also in django-select2? My JavaScript coding capabilities are unfortunately very limited. Simply replacing select2 with djangoSelect2 or django-select2 in the proposed JavaScript didn't do the trick. It starts with the fact that $.fn.djangoSelect2.amd is undefined. -
Call to Stripe API leads to unexpected user logout from Django session
I have a simple Django view where I issue a call to Stripe API (PaymentMethod.detach), and then I am redirecting to a new page: from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.shortcuts import redirect import stripe stripe.api_key = "secret" @login_required def view(request, method_id): if request.method == 'POST': stripe.PaymentMethod.detach(method_id) return redirect('new-page') else: template = " ... " context = { ... } return HttpResponse(template.render(context, request)) DEV settings.py: DEBUG = True SESSION_ENGINE = "django.contrib.sessions.backends.db" SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SECURE = not DEBUG CSRF_COOKIE_SECURE = not DEBUG The problem is that I recently found out that my user is getting logged out from Django when redirected to the new-page. This happens 100% of the time. I believe this is related to the Stripe call because there is nothing else in that view and also when I comment out the Stripe call, then no logout occurs. I have tried a bunch of different SESSION settings but nothing worked so far. I am currently trying to understand what is triggering the logout in the SESSIONS middleware. Any tips on what the issue might be will be greatly appreciated! python == 3.10.6 django == 4.1.6 stripe == 5.1.1 -
Permission denied (publickey,password) Apache in Ubuntu 20.04LTS
I obtain the above mentioned error "Permission denied (publickey,password)" when trying to connect with ssh using my apache server. The framework I have used is Django and when deploying it locally (with python) the ssh communication works perfectly. However, when I deploy it with apache on every ssh, scp communication I obtain the error. I have changed apache User to other than www-data and I got the same result. Obviously, ssh keys for both users are stored in both machines and they work perfectly without using apache. I dont know if it would be possible for apache to look for ssh keys at any specific folder or how to change the default directoy. Any help is much appreciated! -
Find the nearest longitude and latitude
I have a table with latitude and longitude columns with 1000 rows I want when I give latitude and longitude It should return a matching lat-long result and if lat and long are not found in the database can give the nearest lat long from the database table table ------------------------------------------------| id | name | lat | long| | ---|------|-----------------|-------------------| 1 | test |27.988865824076 | 77.8523526316 | I am passing in the request body { "latitude": 27.98681188240762, "longitude": 77.86585050166316 } and expecting ht nearest matching result -
Django Python MQTT Subscribe onMessage got executed two times
I've my Mosquitto MQTT broker and I've created a simple Django APP that subscribes to the topic $SYS/broker/uptime like below from django.apps import AppConfig from threading import Thread import paho.mqtt.client as mqtt class MqttClient(Thread): def __init__(self, broker, port, timeout, topics): super(MqttClient, self).__init__() self.client = mqtt.Client() self.broker = broker self.port = port self.timeout = timeout self.topics = topics self.total_messages = 0 # run method override from Thread class def run(self): self.connect_to_broker() def connect_to_broker(self): self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.connect(self.broker, self.port, self.timeout) self.client.loop_forever() # The callback for when a PUBLISH message is received from the server. def on_message(self, client, userdata, msg): self.total_messages = self.total_messages + 1 print(str(msg.payload) + "Total: {}".format(self.total_messages)) # The callback for when the client receives a CONNACK response from the server. def on_connect(self, client, userdata, flags, rc): # Subscribe to a list of topics using a lock to guarantee that a topic is only subscribed once for topic in self.topics: client.subscribe(topic) class AppMqtteConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'app_mqtt' def ready(self): MqttClient("localhost", 1883, 60, ["$SYS/broker/uptime"]).start() For some reason, the print statement on the on_message callback got executed two times, at least from what I'm seeing from the console. See screenshot. I can't understand why