Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to host Django using ngrok
I am trying to publish Django local host using ngrok. But I am getting an error. Can anyone resolve it? error is ERROR: unknown shorthand flag: 'o' in -ost-header-localhost:8000 -
Django Cms - How to add customise menu in djangocms
Hi Im new to cms I was implementing djangocms in my project I have already have my html files im added placholders in that for making that content editable for example: {% block content %} {% placeholder "content" %} {% endblock content %} I have added placeholder for all the places i needed when i come to menu i used placeholder it only changes in the current html page i need to change in all the page which have same header and footer I Have tried {% show_menu 0 100 100 100 %} But it comes default cms menus i need menu with my default style. I have also tried {% include "header.html" %} But the placeholder only coming the plugin i need to add link again and again in every page. Is there any solution for while im adding plugin in header.html it will display on all the pages which have the same header ? -
Django doesn't raise form error on client side if form isn't valid
So I have the following model and modelform which are handled by a view. Now if a user enters a number > 99.99 on the number input the form validation fails due to the specified parameters of field monthly_amount which is fine. However, there is no error displayed on the frontend. class Benefit(models.Model): company = models.ForeignKey('company.Company', on_delete=models.CASCADE) monthly_amount = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True) ... def __str__(self): return f'ompany {self.company.name}' class BenefitForm(ModelForm): class Meta: model = Benefit exclude = ('company', ) ... monthly_amount = forms.DecimalField(label='Monthly $ equivalent', widget=forms.NumberInput(attrs={'class': benefit_tailwind_class})) And this is y view handling the form def render_dashboard_benefits(request): # Get a qs of available Benefits the company of the authenticated user offers current_user = request.user qs_benefits = Benefit.objects.filter(company__userprofile=current_user).order_by('-created_at') ctx = { 'page': 'Benefits', 'qs_benefits': qs_benefits, } # Create a blank form instance on GET requests and add it to the context if request.method == 'GET': form = BenefitForm() ctx['form'] = form else: # Create clean form form = BenefitForm() ctx['form'] = form # Create new Benefit instance on POST request new_benefit = BenefitForm(request.POST) if new_benefit.is_valid(): # If the instance is valid create it but dont save it yet new_benefit_instance = new_benefit.save(commit=False) # Get the related company instance and assign it … -
django channels Disconnects after Handshake on deployment
i'm new to using websocket and i'm trying to use channels for a simple chat. everything works perfectly on local development but in production, when i deployed the project it doesn't work and disconnects after handshaking i don't know where the problem is and what to do consumers.py class ChatConsumer(AsyncWebsocketConsumer): async def websocket_connect(self, event): print("connected", event) await self.accept() Type = self.get_user_type() if Type == "Pationt": id = self.scope["session"]["User_id"] user = UserInfo.objects.first() # user = await self.get_pationt_object(id) else: id = self.scope["session"]["Provider_id"] user = Providers.objects.first() # user = await self.get_doctor_object(id) chat_room = f"user_chatroom_{user.id}" self.chat_room = chat_room await self.channel_layer.group_add(chat_room, self.channel_name) async def websocket_receive(self, event): print("receive", event) received_data = json.loads(event["text"]) msg = received_data.get("message") sent_by_id = received_data.get("sent_by") send_to_id = received_data.get("send_to") thread_id = received_data.get("thread_id") if not msg: print("Error:: empty message") return False Type = self.get_user_type() if Type == "Pationt": sent_by_user = await self.get_pationt_object(sent_by_id) send_to_user = await self.get_doctor_object(send_to_id) else: sent_by_user = await self.get_doctor_object(sent_by_id) send_to_user = await self.get_pationt_object(send_to_id) thread_obj = await self.get_thread(thread_id) if not sent_by_user: print("Error:: sent by user is incorrect") if not send_to_user: print("Error:: send to user is incorrect") if not thread_obj: print("Error:: Thread id is incorrect") mess = await self.create_chat_message(thread_obj, msg) print(mess) other_user_chat_room = f"user_chatroom_{send_to_id}" response = {"message": msg, "sent_by": sent_by_user.id, "thread_id": thread_id} # await self.send({"type": … -
Django: How can I get a joined table from Child model?
I created OneToOneField in the child model, Return Rate, and tried to get a joined table based the child table using select_related() method. However the result queryset doesn't show the joined result, but only the child data. Models.py: class Coin(models.Model): name = models.CharField(primary_key=True, max_length=100) ticker = models.CharField(max_length=20, unique=True) class ReturnRate(models.Model): ticker = models.OneToOneField(Coin, primary_key=True, on_delete=models.CASCADE, to_field='ticker', related_name='tick') Views.py: def get(request): models.ReturnRate.objects.selected_related('ticker') -
using model method in the django orm query
I have a model which has the model method called cancelled_date which returns date when a record from the models is cancelled how can i access this method in my query set to get the particular data. class Record(models.Model): name = models.CharField(max_length=255) def cancellation_date(self): return cancelled_date the function cancellation date returns the date the day record is cancelled i want to filter the Cancellation date from Record model and do smething Record.objects.filter() -
_MultiThreadedRendezvous with the debug_error_string = "None"
Problem Statement I'm implementing a gRPC communication service between the Java application (spring-boot as a backend service) and the Python application (Django as a middleware). A huge volume of the data is available in the Mongo database and is connected to the spring application, from which I want to retrieve the data, and perform the CRUD operations, using the gRPC framework, therefore, the spring application works as a service provider in gRPC callbacks. On the client side of the gRPC framework, i.e. on Django output, I need the data to be available in JSON format so that the data can be passed to another frontend application where the user can interact with the dashboard. The Error Message After running the Django application, this is the error message displayed on the method call. Request Method: GET Request URL: http://127.0.0.1:8000/api/info/ Django Version: 4.1 Exception Type: _MultiThreadedRendezvous Exception Value: <_MultiThreadedRendezvous of RPC that terminated with: status = StatusCode.INTERNAL details = "Exception deserializing response!" debug_error_string = "None" > Exception Location: /Users/Bhavesh/Codebase/gsoc-smiles/grpc_listener/venv/lib/python3.9/site-packages/grpc/_channel.py, line 826, in _next Raised during: client.views.client Python Executable: /Users/Bhavesh/Codebase/gsoc-smiles/grpc_listener/venv/bin/python Python Version: 3.9.12 Python Path: ['/Users/Bhavesh/Codebase/gsoc-smiles/grpc_listener', '/opt/anaconda3/lib/python39.zip', '/opt/anaconda3/lib/python3.9', '/opt/anaconda3/lib/python3.9/lib-dynload', '/Users/Bhavesh/Codebase/gsoc-smiles/grpc_listener/venv/lib/python3.9/site-packages'] Server time: Sun, 28 Aug 2022 23:45:40 +0000 gRPC protobuf syntax = "proto3"; … -
How to show excel workbook in the django web application before downloading?
I want to display excel sheet in web application (in the same format like pdf or any other format) before downloading.AS per my current code, excel sheet is downloading to my system. code: from io import BytesIO as IO import xlsxwriter from django.http import HttpResponse def export_page(request): excel_file = IO() workbook = xlsxwriter.Workbook(excel_file, {'in_memory': True}) worksheet = workbook.add_worksheet() worksheet.write('A1', 'Some Data') workbook.close() excel_file.seek(0) response = HttpResponse(excel_file.read(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename="Report.xlsx"' return response Can anyone suggest a solution to show the excel sheet in web page using Django? -
Seperate Test Cases of Django Rest API Project
I created DRF project with some test cases. now I want to separate project test cases. so I can give tests to anyone to work on those tests without giving them my complete project. what is the approach to achieve this requirement? Any help would be much appreciated. -
pagination without sending all data in database
I was finding the way how pagination works without reloading. I'm using django, and it seems django recommends to change page data at view, not template. So, I think it says we need to give all paginated data for pagination without reloading. Or, is there any way with not reloading? If that's only way for pagination, when using django, we need to give all data to client whenever we do pagination. If you say about iframe, I'd say django doesn't allow iframe. -
Initial data for template form
I would like to fill my form in templates with data from my local db.sqlite3.How would I go about this? or can you point me 2 some documentation -
Where to put Django rest framework code in a Django project?
I'd like to know where/in which file I should put a set of DRF python code in a Django project. Here's why/what happening to me now. As I'm trying to migrate from the default sqlite database to postgres, I have a trouble; $ IS_PRODUCTION=true python manage.py showmigrations .. django.db.utils.ProgrammingError: relation "django_content_type" does not exist LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_co... that error tells me relation "django_content_type" does not exist, so I checked the stack trace in the error; .. File "/root/pg/django/snippetapp/app/urls.py", line 623, in PostViewSet _content_type_id = ContentType.objects.get_for_model(Post).id .. It seems that I got the error because I have the set of DRF scripts on ./appname/urls.py, and I imported/used ContentType, one of core Django classes in the file; since it seemingly Django loads the top urls.py file in a very early phase, over dealing with ContentType stuff. So, I guess I got to move the whole set of DRF, so where should I? But one thing, I guess we have urlpatterns include-ing DRF router urls as such: router = routers.DefaultRouter() router.register(r'users', UserViewSet) router.register(r'posts', PostViewSet) .. urlpatterns = [ path('api/', include(router.urls)), .. Then isn't we also need to have DRF scripts "before" the ./appname/urls.py -> urlpatterns...? So I'd also like to … -
How to access to attrbuite of another model or table using ManyToMany in django
Please, I need your help. how can access to get attruite of another models using ManyToMany in django Thank you in advance :) ---this is the Models.py => class User(AbstractUser): est_association = models.BooleanField(default=False) est_benevolat = models.BooleanField(default=False) class ProfileBenevole(models.Model): user = models.OneToOneField(User,related_name="benevole", on_delete = models.CASCADE, primary_key = True) photo_profile = models.ImageField( upload_to='uploads/images',null=True,blank=True) nomComplet = models.CharField(max_length=50,null=True) class Mission(models.Model): nom=models.CharField(max_length=50,null=False,blank=False photo_mission = models.ImageField( upload_to='uploads/images',null=True,blank=True) slug=models.SlugField(null=True,blank=True) association=models.ForeignKey(User,on_delete = models.CASCADE,null=True,blank=True) class Participer(models.Model): id_benevole = models.ManyToManyField(User) id_mission = models.ManyToManyField(Mission,related_name="mission") est_participer = models.BooleanField(default=False) --- this is Views.py def demande_participer(request): context={ 'participers':Participer.objects.filter(id_benevole=request.user) } return render(request,'Association/success.html', context) this method for get attr not working -
unsupported operand type(s) for *: 'QuerySet' and 'IntegerField'
Im trying to multiply the result from subquery with 1000 but instead i got the error "unsupported operand type(s) for *: 'QuerySet' and 'IntegerField'" this is my code : last_lrpa = LRPA_File.objects.order_by('-file_export_date').first() last_mou = FileMouPengalihan.objects.order_by('file_export_date').first() sq_1 = MacroData.objects.filter(macro_file=skai_1.macro.macro_file_1, prk=OuterRef('prk')) sq_2 = MacroData.objects.filter(macro_file=skai_2.macro.macro_file_1, prk=OuterRef('prk')) sq_3 = MacroData.objects.filter(macro_file=skai_3.macro.macro_file_1, prk=OuterRef('prk')) sq_mou = MouPengalihanData.objects.filter(file=last_mou, prk=OuterRef('prk')) lrpa = LRPA_Monitoring.objects.select_related('prk').filter(file=last_lrpa). \ annotate(ai_1 = Round(sq_1.values('ai_this_year')*1000), aki_1 = sq_1.values('aki_this_year'), status_1 = sq_1.values('ang_status'), ai_2 = Round(sq_2.values('ai_this_year')*1000), aki_2 = sq_2.values('aki_this_year'), status_2 = sq_2.values('ang_status'), ai_3 = Round(sq_3.values('ai_this_year')*1000), aki_3 = sq_3.values('aki_this_year'), status_3 = sq_3.values('ang_status'), mou_jan = sq_mou.values('jan'),mou_feb = sq_mou.values('feb'),mou_mar = sq_mou.values('mar'),mou_apr = sq_mou.values('apr'), mou_mei = sq_mou.values('mei'),mou_jun = sq_mou.values('jun'),mou_jul = sq_mou.values('jul'),mou_aug = sq_mou.values('aug'), mou_sep = sq_mou.values('sep'),mou_okt = sq_mou.values('okt'),mou_nov = sq_mou.values('nov'),mou_des = sq_mou.values('des'), sd_1 = sq_1.values('sumber_dana'), sd_2 = sq_2.values('sumber_dana'), sd_3 = sq_3.values('sumber_dana'), ) context["lrpa"] = lrpa -
Exporting Django models to Excel (different sheets) using Django-tables2
I've checked django-tables2 documentation, however I haven't find an easy way to export models to different sheets in Excel. To make it simple, let's suppose I have two different models: Sales and Products. I would like to export an excel document with two different sheets: Sales and Products. I can export the first model with the code shown below, but I'm not sure if there's a way to export the Products model to another sheet. Any help would be appreciated. export_format = request.GET.get('_export', None) if TableExport.is_valid_format(export_format): table = [[Sales Table Object]] exporter = TableExport(export_format, table) return exporter.response('File_Name.{}'.format(export_format)) ``` -
Django multitenant using middleware - can you persist connections
I'm using django with django-tenants for a SaaS app and it is using the user's subdomain to set the db schema in postgresql. So a call to user1.app.com will use the 'user1' schema. Each call to a view creates a new database connection by default. If the view call ajax, a new connect/disconnect happens. Using this method works as each call gets it's postgresql search path set to the correct schema using the django-tenants middleware. My question is if I set CONN_MAX_AGE to persist connections for a period of time to reduce the heavy connect/disconnect load on the server, will django pool connections from multiple users potentially using different schemas? I am concerned, because: All users are using the 'default' DATABASE. (just the search path changes) I don't see any logic that binds a connection to a unique user session. The built in development server ignores the CONN_MAX_AGE setting so I can't test locally. I have looked into the connection_created signal, but I would be duplicating logic with django-tenants and I'm not sure of any unintended consequences. Using django 4.0.7 and posgresql 12 Any insight or suggestions are appreciated. -
How to set another instance as foreign key on delete in django?
so if I have a "company" model and a "person" model, and the "company" model has an owner ( a "person" model instance), and a co-owner( a "person" model instance too), I want to make it so that when the owner is deleted the co-owner becomes the owner and the co-owner becomes empty, is that possible in Django? -
How I can use Nested serializer in Django Rest Framework
Hi I'm creating a serializer where I wanna show user profile details and all his products from the product model but it's not working serializer.py class UserSerializer(serializers.ModelSerializer): related_products = ProductSerializer( source="user.product_set.all", read_only=True, many=True ) class Meta: model = User fields = [ "first_name", "last_name", "bio", "phone", "agency", "related_products", ] views.py class ProfileView(generics.RetrieveAPIView): serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated, onlyuser] def retrieve(self, request, *args, **kwargs): serializer = self.serializer_class(request.user) return Response(serializer.data, status=status.HTTP_200_OK) -
Why i have already installed modules in my virtualenv?
I have globally installed modules in my pc, but when i create a virtualenv some of the modules are already preinstalled in it, but when i execute 'pip freeze' in my virtualenv there are no installed modules. commands like 'django-admin' , 'cookiecutter' already work in my virtualenv though i have never installed them in it. But other commands like 'numpy' or 'pandas' do not work , though i have installed them in my machine globally like django or cookiecutter. How do i fix this? I am using python version 3.9.6. -
Django DM model constraint: uniqueConstraint or checkConstraint?
I am trying to define a unique constraint for my DB model. I have 3 constraints and have no trouble with 2. But the 3rd one is doing my head a little. So the model class is fairly simply; its a social media connection request model (between user accounts). These are the constraints I am trying to enforce: User1 should have only one connection request to User2: UniqueConstraint works fine. User1 should not be able to send a connection request to User1 (ie self): CheckConstraint works fine. If User1 sends a connection request to User2, then User2 should not be able to send a connection request back to User1: this is the one I am struggling with. How can I enforce the 3rd constraint here? I initially thought the 1st one enforces the reverse constraint actually (where the uniqueness of the 2 entries in the table are enforced regardless of the order) but it doesnt seem it like (and makes sense too). class ConnectionRequest(models.Model): senderAccount = models.ForeignKey( Account, related_name='sender_Account', on_delete=models.CASCADE) recipientAccount = models.ForeignKey( Account, related_name='recipient_Account', on_delete=models.CASCADE) requested = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.senderAccount.id) + ' to ' + str(self.recipientAccount.id) class Meta: constraints = [ # duplicate connection request constraint models.UniqueConstraint(name='duplicate_connreq_constraint', … -
TemplateDoesNotExist at / chat_app/dashboard.html
I am makeing a chat app, and I have run into some issues. I think I hace had this problom befor but I can not figure out how to fix it. Django is sitting the error is where I have the bootstrap import in y base HTML. I have checked I have included the template DIRs. any help would be appreciated. base.html <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap-theme.min.css" integrity="sha384-6pzBo3FDv/PJ8r2KRkGHifhEocL+1X2rVCTTkUfGk7/0pbek5mMa1upzvWbrUbOZ" crossorigin="anonymous"> <!-- Latest compiled and minified JavaScript --> <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script> <meta charset="utf-8"> <title>Chatter</title> <link rel="stylesheet" href={% static "css/master.css" %}> </head> <body> {% block content %} {% endblock %} </body> </html> setting.py """ Django settings for chatapp project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = Path(BASE_DIR) / "templates" MEDIA_ROOT = Path(BASE_DIR) / "media" STATIC_DIR = Path(BASE_DIR) / 'static' MEDIA_URL = "/media/" # Quick-start development settings - unsuitable … -
Django updating username results in unusable password. How to prevent this?
I am using code to update the user details and whilst the values are updating I have noticed that when I update the username, which is an email address, the password is set to an unusable password, as if set_unusable_password() were used. If I don't update the username but change the first_name and last_name everything is fine. Why? And how can I stop this behaviour? User.objects.filter(username=username).update( first_name=first_name, last_name=last_name, username=username/new_user_name, ) FYI, this is base User model in django. -
Django Rest Framework when doing a POST getting TypeError at Function.objects.create()
I have the following model class Funcion(models.Model): idPelicula = models.ForeignKey(Pelicula, on_delete=models.PROTECT) idSala = models.ForeignKey(Sala, on_delete=models.PROTECT) horaEntrada = models.TimeField(auto_now=False, auto_now_add=False) horaSalida = models.TimeField(auto_now=False, auto_now_add=False) fecha = models.DateField(auto_now=False) And the next serializer class FuncionSerializer(serializers.ModelSerializer): pelicula = PeliculaSerializer(read_only=True) idPelicula = serializers.PrimaryKeyRelatedField(write_only=True, queryset=Pelicula.objects.all(), source='pelicula') sala = SalaSerializer(read_only=True) idSala = serializers.PrimaryKeyRelatedField(write_only=True, queryset=Sala.objects.all(), source='sala') class Meta: model = Funcion fields = '__all__' When I try to post a new Funcion with the Django api root I get the following error: TypeError at /funcion/ Got a `TypeError` when calling `Funcion.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Funcion.objects.create()`. You may need to make the field read-only, or override the FuncionSerializer.create() method to handle this correctly. I have used this method before for other project practices and it worked correctly. If i delete the source='pelicula' argument for the PrimaryKeyRelatedField() it post the new funcion but when I do a get to bring al the data it doesn't show the Pelicula or Sala field just the rest I tried deleting those arguments because the error at the end shows this message TypeError: Funcion() got unexpected keyword arguments: 'pelicula', 'sala' -
Filters for CBV ListView using GET from Previous and Current Page
I am trying to add search functionality to a ListView in two places in my Django application. From the homepage, I want users to be able to filter by zip code, and on the ListView template, I also want users to have the ability to filter by another attribute in the model. My issue is that the self.request.GET.get('q') returns None when filtering from the ListView page, and I want it to retain the zip code filter that I used in the previous page. For search functionality, I am using Q. How can I retain the zip code filter from the initial request so that I can query on both zip code and category? views.py class ListingsView(ListView): model = Listing template_name = 'listings/list.html' context_object_name = 'listing_list' def get_queryset(self): query_zip = self.request.GET.get('q_zip_code') query_category = self.request.GET.get('q_category') if query_category == None: queryset = Listing.objects.filter(Q(zip_code__icontains = query_zip)) else: queryset = Listing.objects.filter(Q(zip_code__icontains = query_zip) & Q(category__icontains = query_category)) return queryset home.html <p> <form class="form-homepage-search" action="{% url 'rental_listings_list' %}" method="get"> <input name="q_zip_code" class="form-zip" type="text" placeholder="Zip Code" aria-label="Zip Code"> <button class="button" type="submit">SEARCH</button> </form> </p> list.html <form class="form-listing-search" action="{% url 'rental_listings_list' %}" method="get"> <input name="q_category" class="form-category" type="text" placeholder="Category" aria-label="Category"> <button class="button" type="submit">UPDATE</button> </form> -
Persisting external classes in Django
I am working on a Django application that uses the SimpleGmail package to fetch mails from a Gmail inbox and I need to persist them. Normally I'd have written a model for the class, but given it's an external class, I can't figure out how to cleanly persist it. I have come across solutions such as making it an attribute of a new model that is persisted or multiple inheritance of the desired class, but none of these seem correct to me. How do I properly register an external class as a model for Django's persistence?