Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does chaining prefetch_related fetch all sub-queries?
Take this for example: user = User.objects.prefetch_related("foo__bar__baz").get(id=id) In this scenario, do I not need to do: user = User.objects.prefetch_related("foo__bar").get(id=id) if I want to access values on bar, or if they are mixed between select_related and prefetch_related due to some being OneToOne and others being FK like this below? user = User.objects.prefetch_related("foo__bar__baz").select_related("foo_bar_baz_qux").get(id=id) Or would skipping the prefetch and only using select be sufficient? user = User.objects.select_related("foo_bar_baz_qux").get(id=id) -
Using prefetch_related / select_related on a GenericForeignKey's own related reverse fields
Is it possible to prefetch a GenericForeignKey that is attached to another GenericForeignKey? For example, the following is not possible (though I'd like it to be): Consider the imaginary model below. Homes are generic and can be attached to many different types of objects via the content_object field as usual. I'd like to do something like prefetch a user, along with their animals, and the animals homes (though I'm aware this below won't work): User.objects.prefetch_related("animals", "animals__home") Is there any way to achieve this? from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.db import models class User(models.Model): ... class Animal(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') user = models.ForeignKey(User, related_name="animals") ... class Home(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.UUIDField() content_object = GenericForeignKey("content_type", "object_id") ... -
Deployment crashing on Railway
I keep trying to deploy my django app using railway. The app will build, but the deployment keeps crashing. This is the error I am getting: Fatal Python error: init_sys_streams: is a directory, cannot continue I have made sure that my Profile had the correct application name include, that did not solve my problem -
How can I show a form by pressing a button in python (using Django framework and Json file)?
I am working on a project in which I should show a form created from a Json file. I am beginner in programming, I try to explain it well. There is a Django app which makes the specific form from a Json file by Json editor. Currently the form can be shown by using an tag in HTML but I want to have a button and by clicking a button, the form be created. Here is the code in HTML: {% for test in tests %} <a href="{{test}}">test</a> {% endfor %} In forms.py, I have a class for creating a form from Json files. I want to have a small form, by taking two values and pressing a button then it shows a form created by the Django app (from Json file) and then I want to access the items of the form. -
Django App Issue with ColumnName changed to lower case in the postgres DB
I have a working Django app with Postgres DB in the backend. However the coulmn names are updated and switched to lowercase name in backend database, for eg: Earlier columnName was AccountName, now changed to accountname all lowercase. This cases the app to break since the model refers to the oldName. I tried changing to the Model to the lowercase name but it breaks at different places like DataFrame name and have to make lot of changes to make it work. class AccountStatus(models.Model): AccountNumber = models.CharField(max_length=255, null=True) AccountName = models.CharField(max_length=255, null=True) is there any simple solution to this issue, maybe using some alias or any parameter to pass etc? Thanks for the help. Tried this : class AccountStatus(models.Model): accountnumber = models.CharField(max_length=255, null=True) accountname = models.CharField(max_length=255, null=True) This results in cascade of changes in Filters, DataFrame key names etc and many other places. I am trying to figure out an easy solution for this? -
By default, is transaction used in Django Admin Actions?
I know that by default, transaction is used in Django Admin when adding, changing and deleting data according to my tests. But, I selected Delete selected persons and clicked on Go in Django Admin Actions. *I use PostgreSQL: Then, clicked on Yes, I'm sure to delete data: Now, only one query DELETE is run without including one or more other queries between BEGIN and COMMIT as shown below so I doubt that by default, transaction is used in Django Admin Actions. *These below are the PostgreSQL query logs and you can check how to log PostgreSQL queries : So by default, is transaction used in Django Admin Actions? -
How to setup guicorn command to start django q
Hello i have my app uploaded on digitalocean server. Whenever i upload it i use gunicorn command to start my app. Currently it looks like this: gunicorn reservationSystem.wsgi:application --bind 0.0.0.0:8080 --worker-tmp-dir /dev/shm My question is how to update it to start django-q service as well. I think this may be cause for my app to crash. After last update (it included django-q for the first time) it crashes whenever i try to open it. Because of that i suspect that the reason for app crashing is that django-q is not started. Just in case you notice something wrong here is my q_cluster setup: Q_CLUSTER = { 'orm': 'default', # should use django's ORM and database as a broker. 'workers': 4, 'timeout': 30, 'retry': 60, 'queue_limit': 50, 'bulk': 10, } Thanks for help -
Working on a django proyect, started using class views and getting TemplateDoesNotExist for the deleteView
enter image description here URLS.py urlpatterns = [ path('',views.ProductList.as_view(), name="products-page"), path('product/<int:pk>', views.SingleProductView.as_view(), name='product-detail-page'), path('product-add', views.ProductAddView.as_view(), name='product-add'), **path('delete/<int:pk>/', views.ProductDeleteView.as_view(), name='product-delete'),** path('update/<int:pk>/', views.ProductUpdateView.as_view(), name='product-update'), VIEWS.py class ProductDeleteView(DeleteView): model = Product template_name = "product/product_delete" success_url = reverse_lazy('products-page') context_object_name = 'product' HTML (Where delete link exists) {% for product in products %} <div class="col"> <div class="card mt-3" style="width: 18rem;"> <div class="card-body"> <h6 class="card-title text-wrap" >{{product.name}}</h6> <h6 class="card-subtitle mb-2 text-muted">{{product.description}}</h6> <h6 class="card-text">Costo: ${{product.cost}}</h6> <a href="{{ product.get_absolute_url }}" class="card-link">Edit</a> <a href="{%url "product-delete" product.pk%}" class="card-link">Delete</a> </div> </div> </div> {% endfor %} Delete HTML <form method="POST" class="row g-3"> <div class="col-auto"> <h6>Are you sure you want to delete {{product.name}}?:</h6> {% csrf_token %} <button type="submit" class="btn btn-danger mb-3" value="Delete">Delete</button> <button class="btn btn-primary mb-3">Cancel</button> </div> </form> Seems simple enough, all I want is to delete that entry from the database. -
Strawberry with social_django
How can i use social_django wih strawberry graphql? With graphene i be inherited my strawberry.type from SocialAuthJWT i used in grapgene like this. class SocialAuth(graphql_social_auth.SocialAuthJWT): user = graphene.Field(UserType) @classmethod def resolve(cls, root, info, social, **kwargs): social.user.is_verified = True social.user.save() token = get_token(social.user) return cls(user=social.user, token=token) I`d like login with google . -
Django access current user fields from derived class?
I have an extended User class, and then a Patient class inherited from it. After the patient logs in I can get first name using request.user.first_name but how can I get the value of address? models.py: class User(AbstractUser): username = None email = models.EmailField(unique=True) is_Patient = models.BooleanField(default=False) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['password'] object = UserManager() class Patient(User): address = models.CharField(max_length=200) class Meta: verbose_name_plural = 'Patients' def __str__(self): return self.first_name + " " + self.last_name -
How to run django app on windows server ec2 instance with mysql database and costum domain
I have Copied my files to the server and also setup the domain in the route 53 and also installed the xampp server now When i try starting the server with the command Python manage.py runserver 0.0.0.0:80 it gives me the following error Error: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions but when i visit the domain it autmatically redirected to domian.com/dashboard/ and there is all the xampp and apache etc stuff i tried to run it with out specifying the ip and port the it redirects to the domian/dashboard i want this to use the xampp server for mysql and run on the domain -
Django tests, how to mock function
I try to mock function, but it is still called. Definitely, I'm doing something wrong. test.py from unittest import mock from rest_framework.test import APITestCase class WalletTest(APITestCase): @mock.patch("apps.some_app.utils.wallets.get_wallet_balance", {"on_hold_balance": 0, "balance": 1000}) def test_delay_payout_with_topup(self): PaymentService().check() apps.some_app.service.py from apps.some_app.utils.wallets import get_wallet_balance class PaymentService: def check(self, *args, **options): data = get_wallet_balance(wallet_id) apps.some_app.utils.wallets.py def get_wallet_balance_data(wallet_id): # some API call is made When I trigger Django tests, API call is still made, instead of using {"on_hold_balance": 0, "balance": 1000} dict What I want, is WalletTest use dict and not go into get_wallet_balance_data func and make API call. How to achieve that? -
What are best practices for adding initial configuration data to a Python Django instance?
I have a Django application that has a Setting model. I've manually added the configuration data to the database through the Django Admin UI/Django Console but I want to package up this data and have it automatically created when an individual creates/upgrades an instance of this app. What are some of the best ways to accomplish this? I have already looked at: Django Migrations Topics Documentation which includes a section on Data Migrations shows a data migration but it involves data already existing in a database being updated, not new data being added. Django Migration Operations Reference show examples using RunSQL and RunPython but both only when adding a minimal amount of data. How to create database migrations looks at moving data between apps. How to provide initial data for models mentions data migrations covered in the previous docs and providing data with fixtures. Still I haven't found one that seems to line up well with the use case I'm describing. I also looked at several StackOverflow Q&As on the topic, but all of these are quite old and may not cover any improvements that occurred in the last 8+ years: Programmatically using Django's loaddata How can I provide the … -
server shows "page not found-404" error while verifying password
I am trying to create a password verification project but when I try to run that, it keeps getting 404 error while it should be redirect on my login page or password do not match error. Although i get the verification email and get the link, when i click the link and try to reset my password, this error comes Not Found: /change-password/263d4b70-c6db-4341-9b56-924d3c9000e6/change-password/263d4b70-c6db-4341-9b56-924d3c9000e6/ can anyone tell me what I am missing here? It would be very helpful Here's a snippet of my code, thanks in advance urls.py from django.urls import path from .views import * urlpatterns = [ path('', home, name='home' ), path('login/', login_attempt, name='login' ), path('register',register_attempt, name='register'), path('logout_user', logout_attempt, name='logout_user'), path('forgetpassword', forgetPassword, name='forgetpassword'), path('change-password/<token>/', changePassword, name='changepassword'), ] views.py from django.shortcuts import render,redirect from django.contrib.auth import authenticate from django.contrib import auth from django.contrib import messages from django.contrib.auth.decorators import login_required from epayapp.helpers import send_forget_password_mail from .models import * import uuid # Create your views here. def forgetPassword(request): try: if request.method == 'POST': username= request.POST.get('username') curr_user= User.objects.filter(username= username).first() if curr_user is None: messages.success(request, 'Username not found') return redirect('forgetpassword') user_obj= User.objects.get(username=username) token= str(uuid.uuid4()) user_obj.forget_password_token= token user_obj.save() send_forget_password_mail(user_obj, token) messages.success(request, 'An email is sent') return redirect('forgetpassword') except Exception as e: print(e) return render(request, 'index/forget_password.html') … -
Django-ckeditor5 how to set codeblock's programming languages in admin template
I am integrating django-ckeditor5 in my Django website but facing some difficulties with adjusting the programming languages that appears on the code-block drop-down from my admin. I want to customize this section to only include programming languages like Python, SQL and JavaScript. I haven't seen a way to configure this via the setting.py file. Please, I need help. -
Django TypeError : create() takes 1 positional argument but 2 were given
I am working on a django chat application whereby I am trying to create a private chat between two users. I have created a django view whereby I am checking if the room name exists and if it does not exist I create it. After calling the function to create the model, I get the error: TypeError at /chat/3/ create() takes 1 positional argument but 2 were given. Here is my models.py: class OneOnOneRoom(models.Model): user1 = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name = 'user1') user2 = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name = 'user2') room_name = models.CharField(max_length = 128, unique=True) def __str__(self): return self.room_name And here is my views.py: def room(request, room_name): if not OneOnOneRoom.objects.filter(room_name=room_name).exists(): OneOnOneRoom.objects.create(...) room = OneOnOneRoom.objects.get(room_name=room_name) if request.User != room.user1 and request.User != room.user2: return HttpResponseBadRequest() return render(request, 'chat/room.html', { 'room_name_json': mark_safe(json.dumps(room_name)) Any help will be highly appreciated. Thanks. -
A custom command for printing generated pdf
I want to get data from database and render it in a printable form. models.py: class PurchaseItem(models.Model): product = models.ForeignKey(Item, on_delete=models.CASCADE, related_name="item") quantity = models.PositiveSmallIntegerField() purchase_price = models.DecimalField(max_digits=6, decimal_places=2) paid_amount = models.DecimalField(max_digits=6, decimal_places=2) date_created = models.DateTimeField(auto_now_add=True) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) I want all this data to be represented in an invoice and be printable.I know many ways to do this but I think I need help from start. VIEWS section in particular is giving me headaches. -
How to make product with different colors/sizes and every color/size has different quantity and different price in Django?
I'm trying to to ad e-commerce website. in my database I want to add t-shirts. but t-shirts can be in different colors and sizes, and each size/color has different price and different quantity in the stock. how can I do that? to have 1 item and when they choose size/color they can see the price and if its out of stock it says out of stock for the specific color/size only. I want to build a model that has a product, contain color, size and price, quantity and title. each color/size has different quantity and different price. -
How to Limit Data in a Django Multiple Form to Display Only the User's Tags
I am currently trying to improve my form by restricting access to user tags. I'm trying to do that inside the get/post function : def post(self, request, *args, **kwargs): form = DateInputForm(request.POST, limit_choices_to={'tags__user': request.user}) def get(self, request, *args, **kwargs): form = DateInputForm(limit_choices_to={'tags__user': request.user}) (1) I get an error. BaseModelForm.init() got an unexpected keyword argument 'limit_choices_to' To solve that error, I added init() to my form. class DateInputForm(ModelForm.__init__()): class Meta: model = Task # exclude = ('user',) fields = ['user', 'title', 'description', 'date_to_do', 'complete', 'tags'] widgets = { 'date_to_do': forms.DateTimeInput(format='%Y-%m-%dT%H:%M', attrs={'type': 'datetime-local', 'class': 'timepicker'}), } (2) Then, I get "Connection Failed" for my page. My view : class TaskUpdate(LoginRequiredMixin, UpdateView): model = Task template_name = "tasks/task_form.html" form_class = DateInputForm Globally: the goal is to limit the tags that can be chosen by the user in my task form; currently, a user can choose another user's tag, which is not what I want. -
Django log level - only WARNING up collected - no INFO
I am runing Django apllication and trying to collect logs from it. I am trying to collect everything from INFO up however in the log file I have only WARNING up. I have replicated settings.py to a basic test Django site where my logging works as inteneded with INFO collected. The problem must be related to the configuration of my Django app. Could you point me please in to any avenue for troubleshooting please. The following variables are collected from the .env file - LOG_MAX_SIZE, LOG_NUMBER_OF_FILES, LOG_LOCATION, LOG_LEVEL. #LOGGING SETTINGS LOG_MAX_SIZE = 52428800 #max size of single log file in bytes LOG_NUMBER_OF_FILES = 5 #number of old log files LOG_LOCATION = 'logs/rotatingLog.log' #default name and location of a log file LOG_LEVEL = 'INFO' #Log level to be collected through all django loggers - options include: DEBUG, INFO, WARNING, ERROR, CRITICAL settings.py file extract: LOGGING = { 'version': 1, # the dictConfig format version 'disable_existing_loggers': False, # retain the default loggers 'handlers': { 'rotatingFile': { 'class': 'logging.handlers.RotatingFileHandler', 'formatter': 'verbose', 'maxBytes': LOG_MAX_SIZE, 'backupCount': LOG_NUMBER_OF_FILES, 'filename': LOG_LOCATION, } }, 'loggers': { '': { 'handlers': ['rotatingFile'], 'level': LOG_LEVEL, }, 'root': { 'handlers': ['rotatingFile'], 'level': LOG_LEVEL, }, 'main': { 'handlers': ['rotatingFile'], 'propagate': False, 'level': LOG_LEVEL, … -
SvelteKit how to handle authenticated WebSocket connections
I have a Django backend that accepts WebSocket connections under a given url. The url takes a JWT token as parameter to authenticate users trying to use a certain websocket. I'm trying to connect to a WebSocket from my SvelteKit frontend. The problem I'm having is that I can only access the Http-Only cookies containing my access & refresh key from within my +page.server.ts endpoint files. How would I go about authenticating the connection while also establishing a connection from the client side to access messages being sent via the WebSocket? Currently I've been following this tutorial using a custom vite plugin as well as socket.io but it doesn't seem to be trying to achieve what I'm trying to work towards. Any help, code samples and ideas on how to handle this problem would be very appreciated! -
Django auto complete light not showing suggestions
I am currently trying to test the django auto complete light. I am able to get it to display the auto complete results when I go directly to the url as it says in the read me. Ie, when I go to localhost:8000/company-autocomplete/ or localhost:8000/company-autocomplete/?q=j it shows the correct json {"results": [{"id": "1", "text": "john", "selected_text": "john"}, {"id": "5", "text": "jjjj", "selected_text": "jjjj"}], "pagination": {"more": false}} The issue arrises when I am trying to have it in the form. My code looks like the following urls.py path('company-autocomplete/', CompanyAutocomplete.as_view(), name='company-autocomplete', ), views.py, forms.py, models.py class Company(models.Model): name = models.CharField(max_length=250) def __str__(self): return self.name class CompanyForm(forms.ModelForm): class Meta: model = Company fields = ('__all__') widgets = { 'company': autocomplete.ModelSelect2(url='company-autocomplete') } class CompanyAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Company.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs class IndexPage(View): def get(self, request): response = render( request, 'base.html', { 'title': 'title', 'description': 'description', 'form': CompanyForm() } ) return response And my base template like so <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> {{ form.as_p }} </fieldset> {{ form.media }} </form> I would greatly appreciate any help -
I have this django model "comments" i want to get the list of comments based on their links to other comments in the same table
class Comments(models.Model): comment_uuid = models.UUIDField(default=uuid.uuid4, editable=False) language_post = models.ForeignKey( PostInLanguages, null=False, related_name='comment_data', on_delete=models.CASCADE) language = models.ForeignKey( Languages, default=2, on_delete=models.CASCADE) is_post_comment = models.BooleanField(default=True) parent_post_comment_id = models.PositiveIntegerField(null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.CharField(max_length=400, blank=False) created_on = models.DateTimeField(default=timezone.now) class Meta: ordering = ["-created_on"] indexes = [ models.Index(fields=['comment_uuid', 'parent_post_comment_id', 'is_post_comment', 'language_post']), ] def __str__(self): return '{}'.format(self.user) def total_comment(self): return self.language_post.count() So the field parent post comment id will refer to comment on the same table And is_post_comment field is boolean field Means if the value is 1 one then its a comment of post and if value is 0 then its a comment of another comment and also when the comment is of other comment we have to provide parent_post_comment_id Im trying to get the queryset of based on how much comments a comment has and also want to filter with minimum comments And also want to know what will total comment method return as it will be called on only one object. I have tried this but doesn't seems to work. Comments.objects.annotate(Count('parent_post_comment_id')).filter(parent_post_comment_id__count__gte=minimum_comment,is_post_comment=False).values_list("parent_post_comment_id")[:100] -
Ubuntu server crash for no reason
I have a problem with Ubuntu 20.04.5 LTS. I have a 1vCPU and 3072MB RAM ubuntu vps. I have run a django project (Gunicorn+Django+Nginx). I also have used postgresql for database. Sometimes, server is not accessible from web or ssh or any other services. From VMware vSphere Client I see that Consumed host Cpu is 2414 MHz (High level). In this situation, I should restart server and then it's good. I checked all of the log files. There's no problem with django applications or Postgres. I also checked iostat, top, htop, ... for finding the process. But I can't find anything. What should I do?Consymed host cpu at high -
make query for filtering where object is in list of objects
ive got three models -Company -Queue -User Company and Queue have a one to one relationship User and Queue have a many to many relationship. Users can be in many queues, and more importantly, a queue can contain many users How do I write a query that filters for companies whose queue contains a specified user? joined_companies should contain companies whose queues contain user def get(self, request, **kwargs): user = request.user companies = Company.objects.all() joined_companies = companies.filter(queue__users__contains=user)