Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dokku: Find IP of another app on same host
I have deployed 3 applications to a single host using Dokku (We call them A B and C). I need to connect to an API in application A from within application B. From the host machine for the three applications I am able to connect to the API with: curl 127.0.0.1:9011 If I run the same command inside container B I receive network error: connection refused Following the Dokku instructions here: https://dokku.com/docs/networking/network/ I created a network and added the network to each app using attach-post-create However running curl inside B still gives connection refused. Which IP must I curl from within B? Is there some other error I've made? Thank you. -
Django Rest Framework - Endpoint outside permission
Im using DRF to build my backend endpoint. I have a viewset protected by isAuthenticated permission_class. class SubnetViewSet(viewsets.ViewSet): permission_classes = [IsAuthenticated] Every endpoint requires autnetication and it works perfectly. Unfortunally, one endpoint of this viewset must be accessible without authentication. @action(detail=False, methods=['get']) def endpoint_free(self, request): [...] Is there a way to exclude only this endpoint without create a new ViewSet. I have found nothing on official Docs. Thanks. -
Why vscode's extension REST client can access my api?
I have a django application running in my server. In that application i use django-cors-headers to protect my api from other origins except the one i set by doing this: # settings.py CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000' ] When I tested it with other origins like http://127.0.0.1:5500 it gave cors error and that's what i want. BUT when i use vscode's extension called REST Client to access my api it worked without any errors. How can i protect my api from that? I'm new to all these things so maybe there are things i dont know about. Thanks you. -
Django Admin: How to add foreign key relational other integer field?
I want to create data from django admin. I have 3 model Employee, OverTime, Pay. Here my models: class OverTime(models.Model): employee = models.ForeignKey(Employee,on_delete=models.CASCADE) total_hour = models.IntegerField() overtime_amount = models.IntegerField() #per hour total_amount = models.IntegerField(editable=False) class Pay(models.Model): employee = models.ForeignKey(Employee,on_delete=models.CASCADE) month = models.CharField(max_length=15) salary = models.IntegerField() overtime = models.ForeignKey(OverTime,on_delete=models.CASCADE) total_amount = models.IntegerField(editable=False) When create payroll from django-admin I need to total_amount value in overtime ForeignKey relational field. How can I do that ? -
How to select latest object from each group using Django and MySQL?
I want to select latest Post of a User of each type. My model is like this: class UserPost(models.Model): POST_CHOICES = ( ('image', 'Image'), ('text', 'Text'), ('video', 'Video') ) user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) post_type = models.CharField(choices=POST_CHOICES, max_length=10) posted_at = models.DateTimeField(default=datetime.datetime.now) I know it can be done using this query: UserPost.objects.values('post_type').annotate(date=Max('posted_at')) But this only returns 2 columns (post_type, date), and I want more than 2 columns. I was able to achieve this in the MySQL with the following query: SELECT P1.post_type, P1.post_id, P1.posted_at FROM appname_userpost P1, (SELECT post_type, Max(posted_at) AS max_posted_at FROM appname_userpost GROUP BY post_type) AS P2 WHERE P1.posted_at = P2.max_posted_at AND P1.post_type = P2.post_type AND user_id = 97; How can I achieve these same results using Django? -
Need to add a new complaint to my site using django, but don't understand how to
I need to add new complaint to my complaint management site but I don't understand how to. I tried using the class Createview but the form is not rendering to the template. What should I do? WHat do I need to add to my code? models.py from django.db import models from django.contrib.auth.models import User from django.db.models.deletion import CASCADE class Complaints(models.Model): user = models.ForeignKey(User, on_delete= CASCADE, null = True, blank=True) title = models.CharField(max_length=300) description = models.TextField(null=True, blank= True) highpriority = models.BooleanField(default=False) document = models.FileField(upload_to='static/documents') def __str__(self): return self.title views.py: class ComplaintCreate(CreateView): model = Complaints field = '__all__' success_url = reverse_lazy('New') template_name = 'new.html' template: <!-- Middle Container --> <div class="col-lg middle middle-complaint-con"> <i class="fas fa-folder-open fa-4x comp-folder-icon"></i> <h1 class="all-comp">New Complaint</h1> <form class="" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-control col-lg-10 comp-title-field"> {{form.title}} </div> <p class="desc">Description</p> <button type="button" class="btn btn-secondary preview-btn">Preview</button> <textarea class="form-control comp-textarea" rows="7" placeholder="Enter text here"></textarea> <button type="file" name="myfile" class="btn btn-secondary attach-btn"><i class="fas fa-file-upload"></i> Attachment</button> <button type="submit" class="btn btn-secondary save-btn" value="submit"><i class="fas fa-save"></i> Save</button> </form> </div> this is my urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('Home/', landing_page.views.landing, name= 'Home'), path('Registration/', accounts.views.RegisterPage), path('Login/', accounts.views.LoginPage, name='Login'), path('Login/Profile/', accounts.views.profile, name='Profile'), path('Logout/', accounts.views.LogoutUser, name='Logout'), path('Login/Add-Complaint', accounts.views.newcomplaint, name = 'New') ] urlpatterns += static(settings.MEDIA_URL, … -
does cpanel requires external commands to run redis
i am using windows. and i have created a chat app with django channels which relies on redis channel layer. now the problem is everytime i want to send message i have to open a cmd for redis server as well to accept connections.. but i have seen on a video of justdjango channel that he installs channels_redis and he uses normal command manage.py runserver which also automatically runs the redis server..but in windows it does not work that way..now the thing is i am deploying it on Cpanel but how i will run redis on cpanel as i have to run it on windows.. ?? -
Autoplotter Python Library Integraton with Django Python Web framework
I have seen a tutorial here Which is demonstrating the data analysis in the jupyter notebook cell, I am looking for the solution that how can i show the output of autoplotter which is python library in the django templates. Below is the code snippet of autoplotter which i have taken from its official website: from autoplotter import run_app # Importing the autoplotter for GUI Based EDA import pandas as pd # Importing Pandas to read csv df = pd.read_csv("https://raw.githubusercontent.com/ersaurabhverma/autoplotter/master/Data/data.csv") # Reading data run_app(df,mode = "inline", host="127.0.0.1", port=5000) # Calling the autoplotter.run_app in inline mode run_app(df,mode = "external", host="127.0.0.1", port=5000) # Calling the autoplotter.run_app in external mode I am looking for that what is the output format of this command run_app (dataframe, host, port....) how can I display its output in my django templates? so that a person could interact with his data through my launched website? Looking for any smart solution. Thank you -
Get the current URL on connection in Django Channels
consumers.py async def connect(self): pk = self.scope["user"].pk self.room_group_name = await self.get_room(pk) print(self.room_group_name) # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() routing.py from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/chat/<int:pk>/', consumers.ChatConsumer.as_asgi()), ] How to get the current url on connection Any help is highly appreciated Thank you. -
Django: Is there a way to effienctly bulk get_or_create()
I need to import a database (given in JSON format) of papers and authors. The database is very large (194 million entries) so I am forced to use django's bulk_create() method. To load the authors for the first time I use the following script: def load_authors(paper_json_entries: List[Dict[str, any]]): authors: List[Author] = [] for paper_json in paper_json_entries: for author_json in paper_json['authors']: # len != 0 is needed as a few authors dont have a id if len(author_json['ids']) and not Author.objects.filter(author_id=author_json['ids'][0]).exists(): authors.append(Author(author_id=author_json['ids'][0], name=author_json['name'])) Author.objects.bulk_create(set(authors)) However, this is much too slow. The bottleneck is this query: and not Author.objects.filter(author_id=author_json['ids'][0]).exists(): Unfortunately I have to make this query, because of course one author can write multiple papers and otherwise there will be a key conflict. Is there a way to implement something like the normal get_or_create() efficiently with bulk_create? -
Setting up VolUtility - Django errors
Trying to set up VolUtility on Kali and when I run manage.py (python3 manage.py runserver) to start it up I get the following errors: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/usr/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/home/kali/.local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/kali/.local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/kali/.local/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/kali/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/home/kali/.local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/kali/.local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/kali/.local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/kali/.local/lib/python3.9/site-packages/django/apps/config.py", line 224, in create import_module(entry) File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/home/kali/Documents/tools/VolUtility/VolUtility/web/__init__.py", line 1, in <module> from . import checks File "/home/kali/Documents/tools/VolUtility/VolUtility/web/checks.py", line 3, in <module> import vol_interface ModuleNotFoundError: No module named 'vol_interface' I have run updates and everything is up to date as far as I can tell. … -
How do I use python for scripting?
So I want to develop a website which will mostly deal with text processing. It would have a 'file input', textbox for URLs. I would be using beautiful soup, ntlk library and some other for text processing. I would also be using some libraries for data visualisation. What would be the best option to achieve this? Would flask be helpful or should I go for django? or are there any better ways of doing this? -
How one can capture string that contain one or more forward slash in django urls
my code look like this urls.py: from django.urls import path from. import views app_name ='graduates' urlpatterns = [ . . path('status_detail/<str:id>/', views.status_detail, name='status_detail'), ] views.py: def status_detail(request, id): return HttpResponse(id) then I wanna use it like this somewhere in my code <a href=" {% url 'graduates:status_detail' graduate.id %}" class="btn text-secondary "></a> And it works fine for strings those don't contain forward slash. But I want to pass id of student to urls that look like this A/ur4040/09, A/ur5253/09 and etc Please help me how could I do this -
why is my Django hosted on Heroku is so slow?
Recently I have deployed my Django web app to Heroku. while testing and running the app on local, the performance is OK. but as soon as I deployed on Heroku, and even up scaling to 2x dynos, it is still slow. like, login in and loading each page takes up-to 10 seconds. also, loading of static pages are fast on Heroku. while interacting with DB and s3 becket, it get so slow. DB and storage is on AWS. Your feedback and comments are most welcomed as I am new to hosting and staff like cloud computing. here is the link to my app and it is not complete yet. https://dear-hr.herokuapp.com -
Can't import braces library
I use braces for my project. But when I import it to my views.py, it shows yellow error that there is no such a library. But it exists on libraries of the project. What should I do? -
get the value of a specific key from Django queryset json data and pass to javascript dictionary value
I have used Django2 to develop a web app. In the view function, I have rendered some json data to frontend. But in the frontend, I am not sure how to pass the value of a specific key in the Json data to a JavaScript dictionary value. I have tried to use query_results_book_json.XXX, but failed to get the data in my case. It shows undefined. View.py: def Browse_and_adopt(request): query_results_book = Title.objects.all() query_results_book_json = serializers.serialize('json', query_results_book) return render(request, 'main.html', {"query_results_book_json": query_results_book_json}) main.html: <script> var query_results_book = {{ query_results_book_json|safe}}; var book = {title: query_results_book_json.title, author: query_results_book_json.author}; </script> How could I get the the key of title and author in this json data in JS? -
How to convert this complex query to Django ORM equivalent
Models: Items(models.Model): name = models.CharField(max_length=250, verbose_name="Item Name") created_date = models.DateTimeField(auto_now_add=True) Accounts(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) url_tag = models.CharField(max_length=200) item = models.ForeignKey(Items, on_delete=models.CASCADE) Comments(models.Model): item = models.ForeignKey(Items, on_delete=models.CASCADE, null=True) comment = models.TextField(null=True) url_tag = models.URLField(null=True) is_flagged = models.BooleanField(default=False, null=True) response_required = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) Responses(models.Model): response = models.TextField() comment = models.ForeignKey(Comments, on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) Sql Query: select c.id as comment_id, c.created_date, c.is_flagged, c.response_required from comments as c left join responses as r on c.id = r.comment_id inner join items as i on i.id = c.item_id and r.comment_id is null left join accounts as a on (a.item_id = c.item_id and lower(a.url_tag) = lower(c.url_tag) where c.id in (12, 32, 42, 54) ORDER BY c.created_date desc, comment_id desc; What I tried: filters = { 'id__in': [12, 32, 42, 54] } Comment.objects.filter(**filters) .select_related('responses', 'item') .order_by('-created_date', '-id') I want to get list of comment objects after joining and applying filters. Maybe we can use serializers here i don't know since I don't have much experience with django -
Django Middleware: Creating Middleware for a Specific Case
I just want to provide access to my website when an api http://www.example.com/api/token=exampletoken (any link) returns a success message. The above link returns two type of json type: {"error":"invalid_token","error_description":"The access token provided has expired"} OR {"success":true,"message":"You accessed my APIs!"} if the first part is "success":true , I want the user to access my website. How to design a middleware for this to give access in this case? What I've tried: import requests class NeedtoLoginMiddleware(MiddlewareMixin): def process_request(self,request): exampletoken = some_token # token is generated somewheree r = requests.get("http://www.example.com/api/token="+exampletoken) -
Why webSocket is connecting with "BACKEND": "channels.layers.InMemoryChannelLayer", But not connecting with Redis
I am working on my django chat app, using websocket and channels. for production purpose I tried to change channel_layers to redis. for that, I changed my channel layers in settings.py to CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } terminal shows the following error. Exception inside application: [Errno 111] Connect call failed ('127.0.0.1', 6379) File "/usr/lib/python3.8/asyncio/selector_events.py", line 528, in _sock_connect_cb raise OSError(err, f'Connect call failed {address}') ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 6379) WebSocket DISCONNECT /ws/chat/2febff41-3dd8-4344-a072-b7a0a36f1f6f/ [127.0.0.1:37950] the program was working when I used following channel layer CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer", }, } -
Effective way to return a list of ManyToMany related items from a queryset of another model class related to same items
I have the following two model classes: class Property(models.Model): """Represents property class model""" serial_no = models.CharField(unique=True,max_length=255,blank=True,null=True) map_no = models.CharField(max_length=255,blank=True,null=True) lr_no = models.CharField(max_length=255,blank=True,null=True) locality = models.CharField(max_length=255,blank=True,null=True) class PropertyObjection(models.Model): """Represents property objection class. This has properties that have been objected""" objector_name = models.CharField(max_length=255,null=True, blank=True) objection_no = models.CharField(max_length=255,null=True, blank=True) properties = models.ManyToManyField(Property,blank=True) ratable_owner = models.BooleanField(null=True,blank=True) ratable_relation = models.CharField(max_length=50,null=True, blank=True) Which is the most effective way to get all properties that have been objected using the PropertyObjection class. One other thing to note is that each property should have values for objection_no, ratable_owner and ratable_relation values. The expected result should look something like this: [ { 'objector_name': "Angela Rudolf", 'serial_no': "5603883", 'map_no': "238", 'lr_no': "234/R", 'locality': "Nairobi", 'objection_no': "pv876646", 'ratable_owner': True, 'ratable_relation': "N/A" } ] I attempted this implementation but its not the most effective way to do so considering when data eventually grows (I tried this when I have more than 5000 records and the request takes long to return a response. I'd like to use the ORM methods to effectively populate the required queryset. class ObjectUsvAPIView(generics.ListAPIView): permission_classes = (permissions.IsAuthenticated,) queryset = PropertyObjection.objects.all() pagination_class = PageNumberPagination def get_queryset(self): """ This view should return a list of all the properties objected. """ qs = … -
Safely patch additional attributes to Django HttpRequest
Background In certain middleware, I want to add some additional attributes to it, like so: def process_request(self, request: HttpRequest): request._additional_info = {} and then I can access it in the view function: def update_information(request: HttpRequest) -> HttpResponse: if hasattr(request, "_additional_info"): request._additional_info["updated"] = True It works just fine. However, since _additional_info only presents in runtime, there is no way for mypy to know that it exists, and thus making the hasattr check necessary. Question My question is: is it possible to create a class called CustomHttpRequest that behaves exactly the same as HttpRequest except that it explicitly has additional attributes like _additional_info? Expected Result With that, I should able to convert HttpRequest to CustomHttpRequest in the middleware, and change the type hints for request in the view functions to CustomHttpRequest. class ConvertRequests(MiddlewareMixin): def __call__(self, request: HttpRequest) -> HttpResponse: converted_request = CustomHttpRequest(request) return self.get_response(converted_request) No more hasattr will be needed, and now mypy and autocomplete should know that request may have the attribute _additional_info. def update_information(request: CustomHttpRequest) -> HttpResponse: assert request._additional_info is not None: request._additional_info["updated"] = True -
Django, What does it mean to cache an endpoint?
with DRF or with plain view, I use something like this. @method_decorator(cache_page(60)) def list(self, request, *args, **kwargs): How does cache works? When a user-a requests it, it caches for 60 seconds. When a user-b requests the same endpoint, it returns the cached response After 60 seconds, cache expires purely because time has passed. (it doesn't matter what happened during the 60 seconds) And the 60-seconds cycle begins when another user requests the same end point? -
Django form save every dynamic inputs / rows into database
I am beginner at Django. I am developing a project where a model is FileAccess and there has a field named files_link. I have created multiple dynamic inputs/added rows (of this field) using jquery at the Django form. When we submit the form, only the last dynamic input is saved into the database (using PostgreSQL database for saving data). Example: Suppose for input 1, input 2, input 3 if there values are link1, link2, link3 and there only last value link3 has been saved into the database. But expected output for files_link is all the input data link1, link2, link3 dynamic inputs image of files_link Now I want to save every input value/ rows data (of files_link) into the database. I need help to solve this out. Thank You in advance. Django 3.1.7 PostgreSQL models.py class FileAccess(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) files_link = models.CharField(max_length=230) revoke_access_name = models.TextField(null=True, blank=True) date_posted = models.DateTimeField(auto_now_add=timezone.now) forms.py class FileAccessForm(forms.ModelForm): class Meta: model = FileAccess fields = ['files_link', 'revoke_access_name'] fileaccess_form.html {% extends "blog/basep.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">File Server Access Activation Form</legend> <div class="input-wrapper"> <div>Files link : <br/> <input type="text" … -
Define searchFilter URL in django rest framework
Currently I am working on a shop management project. The project is building with django, django-rest-framework and react. I want to filter the models data. So I have installed django-filter. I need to define the url like "http://localhost:8000/api/search-products/?category=oil&product=mustard oil". How can I do this? My product search views is- class SearchProduct(generics.ListAPIView): serializer_class = ProductSerializer filter_backends = [filters.SearchFilter] search_fields = ["category", "name"] My url is- path("api/search-product/?<str:category>&<str:name>", SearchProduct.as_view()) Its showing page not found error. How can I define the appropriate url path? -
No module named 'six.moves.urllib'; 'six.moves' is not a package
I am trying to run a Django server for a project, and I'm getting the following error. No module named 'six.moves.urllib'; 'six.moves' is not a package I've pip installed six, also I've verified it in python by importing six.moves.urllib. I've also tried reinstalling six. Nothing seems to work; kindly help.