Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to integrate Fast API and Django
I wanna to write e-commerce website on django. My project will have two DBs: PostgreSQL (For storing users data, django tables, orders handling etc) MongoDB (For storing Products and their categories) Django works well with Relational DBs, but working with NoSQL DBs in Django it's so painfully. FastAPI has good NoSQL DBs support. And I wanna to use Django and FAST API in one project. If you have solution of my problem, please drop me a link to solution. Maybe will be better if I'll use them separately (1 django server and 1 Fast API server) and frontend will request data from 2 different servers? -
Error in Serving media images with Django
Problem - When trying to fetch an image leads to 404 error URL Declarations - from django.urls import include, path from rest_framework import routers from django.conf.urls.static import static from django.conf import settings from my_awesome_api.views import PersonViewSet, SpeciesViewSet router = routers.DefaultRouter() router.register(r'people', PersonViewSet) router.register(r'species', SpeciesViewSet) urlpatterns = [ path('', include(router.urls)), ] urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) print('avail url patterns') print(urlpatterns) VIEW DECLARATION - from django.shortcuts import render from rest_framework import viewsets from rest_framework.parsers import MultiPartParser, FormParser from rest_framework import permissions from my_awesome_api.serializers import PersonSerializer, SpeciesSerializer from my_awesome_api.models import Person, Species class PersonViewSet(viewsets.ModelViewSet): queryset = Person.objects.all() serializer_class = PersonSerializer parser_classes = (MultiPartParser, FormParser) #permission_classes = [permissions.IsAuthenticatedOrReadOnly] def perform_create(self, serializer): serializer.save() class SpeciesViewSet(viewsets.ModelViewSet): queryset = Species.objects.all() serializer_class = SpeciesSerializer parser_classes = (MultiPartParser, FormParser) #permission_classes = [permissions.IsAuthenticatedOrReadOnly] def perform_create(self, serializer): serializer.save() MODEL DECLARATION - from django.db import models # Create your models here. class Species(models.Model): name = models.CharField(max_length=100) classification = models.CharField(max_length=100) language = models.CharField(max_length=100) image_url = models.ImageField(blank=True, null=True) class Person(models.Model): name = models.CharField(max_length=100) birth_year = models.CharField(max_length=10) eye_color = models.CharField(max_length=10) species = models.ForeignKey(Species, on_delete=models.DO_NOTHING) image_url = models.ImageField(blank=True, null=True) SETTING DECLARATION MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media') print(MEDIA_ROOT) print('value of media root') # URL used to access the media MEDIA_URL = 'media/' In an effort to troubleshoot the problem, I … -
How to implement datatable server side from this code using django
Currently I have this code that shows me the normal data table but if I have millions of records it becomes very slow, I understand that serverside of datatable can be used but I don't know how I can implement it list.html <table class="table table-striped table-hover responsive" style="width:100%" id="buyer"> <thead> <th>#id</th> <th>Fecha</th> <th>Cod Cliente</th> <th>Cliente</th> <th>Dirección</th> <th>Comentario</th> <th>Tipo Retiro</th> <th>Total</th> <th>Guias a Generar</th> </thead> <tbody> {% for item in ResulOrdenes %} <tr> <td>{{item.DOCNUM}}</td> <td>{{item.DOC_DATE|date:"Y-m-d"}}</td> <td>{{ item.CARDCODE }}</td> <td>{{ item.CARDNAME }}</td> <td>{{ item.ADDRESS }}</td> <td>{{ item.COMMENTS }}</td> <td>{{ item.URETIRO }}</td> <td>{{ item.DOCTOTAL }}</td> <td>{{ item.NGUIAS }}</td> </tr> {% endfor %} </tbody> </table> </div> {% endblock %} {% block content_wrapper %} <p></p> {% endblock content_wrapper %} {% block js_page %} <script> $(document).ready(function() { $('.table').DataTable({ dom: 'Bfrtip', }); </script> {% endblock %} view.py def Listado_guia(request): template_name='app_listguia/lista.html' conn = dbapi.connect(..) cursorSol2 = conn.cursor() sql_command = 'select a."DocNum" as "DOCNUM", a."DocDate" as "DOC_DATE", a."CardCode" as "CARDCODE", a."CardName" as "CARDNAME", a."DocTotal" as "DOCTOTAL", CEILING(a."DocTotal"/20000) as "NGUIAS", a."DocStatus" as "DOCSTATUS", a."Address" as "ADDRESS", a."Address2" as "ADDRESS2", a."Comments" as "COMMENTS", a."U_Retiro_mercaderia" as "URETIRO" ' sql_command = sql_command + 'from "'+ connections.databases[ConfigBaseHana]["NAME"] +'"."ODLN" as a ' cursorSol2.execute(sql_command) RES_ORDENES = cursorSol2.fetchall() cursorSol2.close() conn.close() dnow = today.strftime("%Y-%m-%d") contexto = { "ResulOrdenes":RES_ORDENES, … -
How to append a string to url in django template tag?
I have two sections in my demo site. blog and tweets. In header of parent HTML file I have Blog, Tweets and "New +". To create object for one of these two. I want for "new +" link to go http://127.0.0.1:8000/blog/new or http://127.0.0.1:8000/tweets/new How to append new to both of these link when I'm in either of these two links <a href="{% url 'tweets' %}">Tweets</a> <a href="{% url 'blog' %}">blog</a> Both of these links work but I want blog/new or tweets/new when I'm in one of these links without hardcoding. -
Optgroup/Option dropdown Django
I am working on a form which has a select dropdown that requires an optgroup and select options… Optgroups are Regions (Asia, Europe etc) and options are countries belonging to the countries… I have developed a Form for this and applied choicefield and has written the logic inside the form itself… and then applied the HTML using FormHelper Layout so that I can just pass {% crispy form %} in the template… For some reason I cannot figure out, the data in the select option does not appear… I’d appreciate if you could help me debug the problem… Please note, there is no error message, just that when i go to webpage, the data in the dropdown isnt there… Models.py class CountryRegion(models.Model): id = models.AutoField(primary_key=True, editable=False) country_name = models.CharField(max_length=50, unique=True, verbose_name='Segment') region_name = models.CharField(max_length=50, verbose_name='Industry') class Meta: verbose_name_plural = 'RegionCountry' def __str__(self): return self.country_name + '-' + self.region_name Forms.py from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Row, Column, HTML from crispy_forms.bootstrap import FormActions from django.contrib.auth.models import User from django.forms import ModelForm from .models import Portfolio, Project, SegmentIndustry, CountryRegion class ProjectForm(forms.ModelForm): fk_project_location = forms.ChoiceField(choices=[]) def __init__(self, *args, **kwargs): super(ProjectForm, self).__init__(*args, **kwargs) region_list = CountryRegion.objects.values_list( "region_name", … -
ListView get_context_data
question about Django. Would like to ask you guys if it's possible to use get_context_data in ListView? I am interested in using the following template tags in my ListView: {% if liked %} <i class="fa-solid fa-thumbs-up"></i> {% else %} <i class="fa-regular fa-thumbs-up"></i> {% endif %} This works in my DetailView but I can't figure out how to implement it in ListView maybe you guys can help me? This is my views.py class PostList(generic.ListView): model = Post queryset = Post.objects.order_by('-created_on') template_name = 'blog/blog.html' class PostDetail(generic.DetailView): model = Post template_name = 'blog/post_detail.html' def get_context_data(self, **kwargs): context = super(PostDetail, self).get_context_data(**kwargs) context['comments'] = self.object.comments.order_by('-created_on') context['liked'] = self.object.likes.filter(id=self.request.user.id).exists() return context I'm testing get_context_data i ListView but can't get it to work. -
How to pass text argument to custom widget in django form?
I'd like to display a dynamic text value in a custom widget. It will more or less be a bootstrap input group with some dynamic text in a input-group-append element. I'm having difficulty understanding how I can pass this through to the template, as when I define the field in the Form class, I can't seem to reference arguments from the Form constructor. I'm inexperienced with both python and django so its very likely I'm missing some foundational python knowledge that's causing my confusion. If I do this, the widget renders partially ok (There is an automatic label "Site prefix" rendered that I don't want but that seems like a different problem) class SiteNameForm(forms.Form): site_prefix = forms.CharField(widget=SiteNameInputWidget(prefix_for='T E S T'), label=None) And create the form like so form = SiteNameForm() However, I need to pass in a dynamic value, so I tried class SiteNameForm(forms.Form): def __init__(self, prefix_for=None, *args, **kwargs): self.prefix_for = prefix_for self.site_prefix = forms.CharField(widget=SiteNameInputWidget(prefix_for=self.prefix_for)) super().__init__(self, args, kwargs) While creating the form form = SiteNameForm(prefix_for='TEST') But when I do that, nothing is rendered at all, not even the automatic label that I didn't want. The template specified as template_name <div class="row"> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text">https://</span> </div> <input … -
How can I test render methods for django template Node?
I have written a django template Node for templatetag. How can I test render method (render method only) for Node? Here is my code sample: class SVGNode(Node): child_nodelists = () def __init__(self, svg_name, args: list, kwargs: dict) -> None: ... def __repr__(self) -> str: return ... def render(self, context: Context) -> str: ... return svg And I want to test it using pytest(preferably). -
Problem with docker-compose, django and mysql during testing
I am using docker-compose along with django and mysql, and I want in the custom entrypoint of django I want to do tests via python manage.py test. Since I am connected to mysql, by default it goes to look for the database test_NAMEDATABASE, but it doesn't find it. So I tried to create it as it says here, but I have several problems with permissions. I think this is a very common situation, how did you solve it? This is my mysql service in docker-compose.yml: db: image: mysql:latest command: --default-authentication-plugin=mysql_native_password ports: - 3306:${MYSQL_DATABASE_PORT} environment: - MYSQL_RANDOM_ROOT_PASSWORD - MYSQL_USER - MYSQL_PASSWORD - MYSQL_DATABASE - MYSQL_DATABASE_HOST - MYSQL_DATABASE_PORT volumes: - mysql_data:/var/lib/mysql And this is my settings.py settings in django: 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ.get('MYSQL_DATABASE'), 'USER': os.environ.get('MYSQL_USER'), 'PASSWORD': os.environ.get('MYSQL_PASSWORD'), 'HOST': os.environ.get('MYSQL_DATABASE_HOST'), # Or an IP Address that your DB is hosted on 'PORT': os.environ.get('MYSQL_DATABASE_PORT') } It gives me this error when I try to manually create the database "test_NAMEDATABASE" inside the mysql container: "Access denied for user 'django'@'%' to database 'test_NAMEDATABASE" Heading -
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, …