Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"Django-filter" Is it possible to use FilterClass(FilterSet) MultipleChoiceFilter within ViewSet methods? Django 1.11, Python 2.7
I have my class ClassFilter(FilterSet) with some of the Filters fx. MultipleChoiceFilter, ModelMultipleChoiceFilter etc. in it: class ClassFilter(FilterSet): something_severity = MultipleChoiceFilter(choices=Something.SEVERITY_CHOICES, method='something_severity_filter', widget=CSVWidget) def something_severity_filter(self, queryset, name, severities): if severities: queryset = queryset.filter(something_state=Something.STATE_SOMETHING) ... return queryset class Meta: model = Something fields = [] It works perfect when it comes to filtering endpoints. It is assigned to the class like: class ClassViewSet(mixins....., DefaultApiViewSet): filter_class = ClassFilter by having filter_class = ClassFilter. Everything works just fine but now I am in in doubts if I may use the ClassFilter MultipleChoiceFilter within ClassViewSet methods. This means by executing POST method in ClassViewSet, I want to get the MultipleChoiceFilter from FilterClass to filter on my method by getting it as SomethingFilter.get_filters() method @action(detail=False, methods=['post']) def something_update(self, req): ... all_filters = SomethingFilter.get_filters() for serializer_filter in serializer_filters: for filter in all_filters: if(serializer_filter == filter): f = all_filters[filter] Now the f is a filter which I require so that is MultipleChoiceFilter. But when I try to filter with that filter it throws an error. f.filter(queryset, [('LOW')]) #filter the queryset with the filter based on LOW choice Throws: assertionError: Filter 'something_severity' must have a parent FilterSet to find '.something_severity_filter()' In documentation for django-filter it is exactly line: … -
Django custom foreign key representation
If i have two models class Parent(models.Model): attribute_1 = .... attribute_2 = .... class Child(models.Model): parent = models.ForeignKey(Parent) Django by default will do lazy fetching to parent as it will hit the database when i try to access attribute_1 or attribute_2, so how can I make it fetch them by default for this specific use case -
Django templates not picking static files
Following is the my static folder structure: ProjectABC - App1 - App2 - App3 - ProjectABC - resources - static - imgs - css - templates This is how the project structure looks like. This is how the static configuration in settings.py looks like: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) This is how the base.html looks like: <!doctype html> {% load static %} <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, maximum-scale=1, initial- scale=1, user-scalable=0"> <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible"> <link rel="stylesheet" href="https://fonts.googleapis.com/css? family=Open+Sans:400,600,800"> <title>{{SITE_NAME}}</title> <link rel='shortcut icon' href= "{% static 'img/favicon.png' %}"/> <link href="{{STATIC_URL}}css/application.css" media="screen" rel="stylesheet" type="text/css" /> <link href="{{STATIC_URL}}css/style.css" media="screen" rel="stylesheet" type="text/css" /> <script src="{{STATIC_URL}}js/application.js" type="text/javascript"></script> {% block extracss %} {% endblock %} </head> <body> <div class="container"> <h1>Hello</h1> </div> </body> </html> All the static files are being loaded as seen in terminal, but in browser its just loading bare html without any css or img: Please lemme know if i am missing something. Thnk You! -
Problem in deploying Django website on Cyber Panel
I have deployed the Django website on openlite server and cyberpanel. According to the documentation of the cyberpanel, there is no requirement to run the server manually. The default page of cyberpanel will be removed automatically once the Django website will be there. But in my case, that default page is still there. As this is not working, I tried it by executing the following command: python manage.py runserver example.com:8000 After this, the website is working only on port 8000 i.e. "https://example.com:8000", but not on "https://example.com". I have tried configuring all the settings in settings.py like setting the allowed host to ["*"] and also configuring the configurations of vhost in cyberpanel but still it is not working. Can anyone help please ? -
Not able to get current logged in user in django model
I am trying to get current logged in user through my model so that I can only see the current user in my order page dropdown: I have gone through a lot of documents which state that it is not that easy or feasible to get current logged in user in model. I have tried other method like getting AUTH_USER_MODEL but it is returning admin level users as well so not solving the problem. I am also sending the current logged in user from my views file but dont know how to access it inside form class, able to access it in init but dont know how it can be accessed in class. models.py : from django.db import models from django.contrib.auth.models import User from django.conf import settings from django.contrib.auth import get_user_model from django.http import HttpResponse,HttpRequest class Customer(models.Model): name = models.CharField(max_length=200,null=True) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Order(models.Model): product = models.ForeignKey(Product,null=True, on_delete=models.SET_NULL) #customer = models.ForeignKey(settings.AUTH_USER_MODEL,null=True, on_delete=models.SET_NULL) customer = models.ForeignKey(Customer,null=True, on_delete=models.SET_NULL) date_ordered = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=20,default= 'PENDING') def __str__(self): return str(self.customer.id) forms.py : class createorderform(ModelForm): def __init__(self,*args,**kwargs): self._instance=kwargs.pop('instance',None) super().__init__(*args,**kwargs) #def __init__(self,instance): # self.user = instance # super().__init__(instance) class Meta: model=Order fields="__all__" exclude=['status'] Views.py def … -
Set the value of a field in a model as the value of a field in another model in django
I have a two model field one which is the user model and one which is the landlord model. I want the first_name and last_name of the user model to be saved also in the landlord model. This is my model view pass class User(AbstractUser): is_customer = models.BooleanField(default=False) is_employee = models.BooleanField(default=False) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) nin = models.IntegerField(unique = True , null=True) avatar = models.ImageField(null= True, default="avatar.svg") objects = UserManager() class Landlord(models.Model): user = models.OneToOneField(User, null= True, on_delete=models.CASCADE) first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) email = models.EmailField(unique = True , null=True) bio = models.TextField(null=True) nin = models.IntegerField(unique = True , null=True) avatar = models.ImageField(null= True, default="avatar.svg") USERNAME_FIELD = 'email' REQUIRED_FIELDS= [] objects = User() def __str__(self): return str(self.user)``` -
How to run Django new project in the same VS code folder which already has a project that is running on every runserver Port?
I created two projects baseproject and web_project using django in vs code folder: smcode5 with virtual environment. I used web_project first to create an app and run on server port 8000. Now I want to use baseproject for an app, but only web_project runs. Any suggestions? -
populating foreign key in django
I'm creating a page that lets only admin add some assets. Each asset has a type. I have used a dropdown to select the asset_type. The selected value of asset_type gets passed into views.py but I can't get it written into the newly created asset object. Here is my models.py class assetType(models.Model): title = models.CharField(max_length=150) @property def get_type(self): return asset.objects.filter(asset_type=self.id) def __str__(self): return f"{self.title}" class Meta: verbose_name_plural = 'Asset Types' class asset(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, null=False) asset_type = models.ForeignKey('assetType', on_delete=models.CASCADE, null=True) asset_name = models.CharField(max_length=30, null=True) #unique=True location = models.CharField(max_length=30, null=True) brand = models.CharField(max_length=30, null=True) purchase_year = models.PositiveIntegerField(blank=True, null=True) isActive = models.BooleanField(default=True, null=True) currentOwner = models.ForeignKey(User, default='', null=True, on_delete=models.CASCADE) Here is createAssetView from views.py @user_passes_test(lambda u: u.is_superuser) def createAssetView(request): assetTypeList = assetType.objects.all() # use assetType.title assettype = request.POST.get('asset-type') assetname = request.POST.get('asset-name') locationn = request.POST.get('location') brandd = request.POST.get('brand') purchaseyear = request.POST.get('purchase-year') isActivve = request.POST.get('is-active','') == 'on' cuser=request.user context={ "cuser":request.user, "asset_type_list":assetTypeList, "asset_type":assettype, "asset_name":assetname, "location":locationn, "brand":brandd, "purchase_year":purchaseyear, "isActive":isActivve, 'iterator':range(2014,2050) } if request.method == 'POST': new_asset = asset() new_asset.asset_type_title=request.POST.get('asset-type') new_asset.asset_name=assetname new_asset.location=locationn new_asset.brand=brandd new_asset.purchase_year=purchaseyear new_asset.isActive=True if isActivve else False new_asset.currentOwner=cuser print(assettype) # PRINT assettype new_asset.save() return redirect('createAssets') return render(request, 'assets/createAsset.html', context) The PRINT assettype statement prints selected asset type from the form, so the … -
IntegrityError at /blog/5 NOT NULL constraint failed: blog_comment.post_id
I'm trying to implement a comment section in my blog that looks as follows: I don't have a user or post name input because it should take as input the request user and the post ID of the post where it's making the comment. My Comment model: class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) approved_comment = models.BooleanField(default=False) class Meta: ordering = ['-created_on'] def __str__(self): max_len = 75 if len(self.body) > max_len: string = self.body[:max_len] + "..." else: string = self.body return string Comment form: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) exclude = ['user', 'post', ] View function: def get_post_details(request, post_id): unique_post = Post.objects.get(id=post_id) all_comments = Comment.objects.filter(post=unique_post) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=True) new_comment.post = unique_post new_comment.user = request.user new_comment.save() return get_post_details(request, post_id) else: comment_form = CommentForm() context_dict = { 'post': unique_post, 'comments': all_comments, 'new_comment': new_comment, 'comment_form': comment_form } return render(request, 'blog/post_details.html', context=context_dict) I'm not sure what's missing, but when I try to add a comment I get the below error: IntegrityError at /blog/5 NOT NULL constraint failed: blog_comment.post_id I've searched all over stackoverflow and the issue … -
Does django supports frontend pagination?
In brief sight, to use django's Paginator class, we need to paginate from backend. But most of web pages are doing pagination at frontend. Is it possible doing frontend pagination with django's Paginator? Or should I just give it up and use datatables with giving all data to client? -
How to convert web URL data to JSON format
I am mobile application developer. I want to try to get web URL data in JSON format. I have try to build image aggregator application. https://yandex.com/images/search?rpt=imageview&url=https%3A%2F%2Favatars.mds.yandex.net%2Fget-images-cbir%2F1973508%2FEArWpseFrv-9jTLCuEUwTw5291%2Forig&cbir_id=1973508%2FEArWpseFrv-9jTLCuEUwTw5291 I am trying this URL data in JSON format like our REST API response. Is it possible to convert JSON data of this URL. I have also knowledge of Django framework. If it is not possible from front end using android studio then please share me possibility of Django. Thank you -
How to use Modal Foreign key
comment in a situation where my modal looks like this i want to display comments without having to go to different page class Posts(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post_name = models.CharField(max_length=150) desription = models.CharField(max_length=200) image = models.ImageField(upload_to="images/uploads") like = models.ManyToManyField(User, related_name="liked", blank=True, default=None) like_count = models.BigIntegerField(default=0) date_added = models.DateField(auto_now_add=True, blank=True) # @property # def like_count(self): # return self.like.count() def __str__(self): return self.desription class Meta: db_table = "Posts" ordering = ["date_added"] class Comments(models.Model): post = models.ForeignKey(Posts, on_delete=models.CASCADE) comment = models.CharField(max_length=500) user = models.ForeignKey(User, on_delete=models.CASCADE) date_added = models.DateField(auto_now=True, blank=True) class Meta: db_table = "Comments" ordering = ['date_added'] and in the index use {{post.comment}} ??? -
Anchor tag is changing the background color of other tags when click in Bootstrap 5
Whenever i try to click a anchor tag it always change the background of others tags for a split second even though i didn't click them, where do i get things wrong? Code Here: <nav class="navbar navbar-expand-lg navbar-light bg-warning"> <div class="container-fluid px-5"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-lg-0"> <li class="nav-item"> <a class="nav-link" href="/home/">Home</a> </li> <li class="nav-item me-auto"> <a class="nav-link" href="/rooms/">Rooms</a> </li> </ul> <ul class="navbar-nav ms-auto mb-2 mb-lg-0"> <li class="nav-item me-auto"> <a class="nav-link" href="#">Login</a> </li> <li class="nav-item me-auto"> <a class="nav-link" href="#">Sign-in</a> </li> </ul> </div> </div> -
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 …