Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Set different session expiry time for different users in Django
How can I set different session expiry time for different logged-in users? The scenario can be, admin can permit certain users some time(like 4 hrs in a day) to use the application. After that time limit is over the user is logged out of the system and cannot log in again until the admin permits again. Is there any way I can implement this in Django? -
Check if password matches to the current user's password in Django
I have to check if the inputted password matches the password of the current user. class UserPasswordMatchAPIView(APIView): """ Check password """ serializer_class = UserPasswordSerializer permission_classes = [IsAuthenticated] queryset = User.objects.all() def get(self, request, *args, **kwargs): user = self.request.user password = self.request.data.get("password") if user.check_password(password): return Response(data={"message": True}) else: return Response(data={"message": False}) class UserPasswordSerializer(serializers.ModelSerializer): class Meta: model = User fields = ("password",) When I try to run this in swagger, it shows that it has no parameters required. I have to input the password. Is there any way I can execute this? -
How do I display the date on the top of chat messages in django?
I am working on a chat application but I am struggling to figure out how to display the calendar date on the top of chat messag. As example, the first image in this post is exactly what I mean link of image The date is displayed on top of a fresh new batch of text messages. I would like to do the same, just for a batch of messages related to a specific date. Say if I have messages for October 19, it shows October 19 on top followed by messages for October 20 and so on... -
Filter the Staff name and display the staff list in frontend
I am trying to filter only staff users and show the list of staff into the frontend where normal users can choose the staff name and input the price. My views file for this function is quite big, so I am sharing the gist file here https://gist.github.com/TaufiqurRahman45/104b571873531d3d119295bb3c24b4fb[View.py][1] Can anyone help me to sort out this? Thank you model.py class DailyFood(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(default=now) total = models.PositiveIntegerField() class PurchaseHistory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='histories') date = models.DateTimeField(default=now) balance = models.PositiveIntegerField() hand_cash = models.PositiveIntegerField() HTML <form action="" method="post"> {% csrf_token %} <div class="modal-body"> <div class="modal-body"> <div class="form-group"> <label>Total price</label> <input type="number" name="price" class="form-control" placeholder="Enter price"> <label>Staff</label> <!-- #show staff list here--> </div> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-success">Submit</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </form> -
How to filter for an object that has a foreign key field that is part of a query set in Django?
I have a chat application using Django API and one operation requires that it return a list of chats associated with the person requesting the chats. The chats are of two kinds - Individual chats and group chats. Both require different approaches to determine whether that chat belongs to the person or not. These are the models:- class Group(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=250) institution = models.ForeignKey(Institution, on_delete=models.PROTECT) avatar = models.CharField( max_length=250, blank=True, null=True, default="https://i.imgur.com/hNdMk4c.png") searchField = models.CharField(max_length=400, blank=True, null=True) # Type Choices class TypeChoices(models.TextChoices): CLASS = "CL", _('Class') TEAM = "TE", _('Team') COORDINATiON = "CO", _('Coordination') # End of Type Choices group_type = models.CharField( max_length=2, choices=TypeChoices.choices, default=TypeChoices.TEAM) admins = models.ManyToManyField(User, related_name="adminInGroups", through="GroupAdmin", through_fields=( 'group', 'admin'), blank=True) members = models.ManyToManyField( User, related_name="memberInGroups", through='GroupMember', through_fields=('group', 'member'), blank=True) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Chat(models.Model): group = models.OneToOneField( Group, on_delete=models.CASCADE, blank=True, null=True) individual_member_one = models.ForeignKey( User, related_name="chat_member_one", on_delete=models.CASCADE, blank=True, null=True) individual_member_two = models.ForeignKey( User, related_name="chat_member_two", on_delete=models.CASCADE, blank=True, null=True) # Type Choices class TypeChoices(models.TextChoices): INDIVIDUAL = "IL", _('Individual') GROUP = "GP", _('Group') # End of Type Choices chat_type = models.CharField( max_length=2, choices=TypeChoices.choices, default=TypeChoices.INDIVIDUAL) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): … -
Seperate djnago model field to another fields
I have a field called fullname that the data in it, is something like this first_name:Gholi;last_name:Sezavar Poor Asl Esfahani I want to seperate it first_name and last_name to seperated fields name first_name & last_name my models.py now is this: from django.db import models class Person(models.Model): fullname = models.CharField(max_length=250, null=True) information = models.CharField(max_length=350, null=True) first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=50, null=True) id_code = models.CharField(max_length=10, null=True) born_in = models.CharField(max_length=30, null=True) birth_year = models.PositiveIntegerField(null=True) and I want to make custom migration for it and using annotate method or something else. How can I do this ??? -
Cron jobs show but are not executed in dockerized Django app
I have "django_crontab" in my installed apps. I have a cron job configured CRONJOBS = [ ('* * * * *', 'django.core.management.call_command',['dbbackup']), ] my YAML looks like this: web: build: . command: - /bin/bash - -c - | python manage.py migrate python manage.py crontab add python manage.py runserver 0.0.0.0:8000 build + up then I open the CLI: $ python manage.py crontab show Currently active jobs in crontab: efa8dfc6d4b0cf6963932a5dc3726b23 -> ('* * * * *', 'django.core.management.call_command', ['dbbackup']) Then I try that: $ python manage.py crontab run efa8dfc6d4b0cf6963932a5dc3726b23 Backing Up Database: postgres Writing file to default-858b61d9ccb6-2021-07-05-084119.psql All good, but the cronjob never gets executed. I don't new database dumps every minute as expected. -
Copy of a Slice from a DataFrame issue while running the script in Django
I am trying to apply multiple user-defined functions to a column of a dataframe one by one. This is the error it is giving me when I ran it in Django env. (.py3env) [root@---------]# python report_feedback_attribute.py runserver feedback_attribute.py:89: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy data1['feedback_text'] = data1['feedback_text'].apply(clean_text) # the feedback_text column has been cleaned feedback_attribute.py:93: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy data1['feedback_text'] = data1['feedback_text'].astype(str) feedback_attribute.py:103: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy data1['feedback_text'] = data1['feedback_text'].apply(lambda x: tokenizer.tokenize(x.lower())) It is returning an empty dictionary. {'count': []} I have already tried creating a copy of my dataframe and then working on it. Still no result. I have also tried applying .loc in this way: data1.loc[:, 'feedback_text'] = data1['feedback_text'].apply(clean_text) (I did this change for every function that I defined and applied on … -
Django - query an existing database with no keys
New to Django. I have a database that I am connecting to using the multiple database configurations. There are no keys on the tables and I cannot change them. Lets say the tables are Orders and Customers and data can be returned by SQL: SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID; What is the best approach in Django to query tables where I need to specify a join? -
Django admin can add data but not user from site
hello friends i am not able to add user data in my database but i am able to do it in admin panel and there is no error plz help.there is no error can someone help view.py from django.shortcuts import render from keshavapp.models import Register # Create your views here. def index(request): return render(request,"index.html") def register(request): return render(request,"register.html") def connect(request): if request.method =="POST": fname=request.POST.get('fname') lname=request.POST.get('lname') email=request.POST.get('email') password=request.POST.get('password') address=request.POST.get('address') city=request.POST.get('city') state=request.POST.get('state') zip=request.POST.get('zip') connect=Register(fname=fname,lname=lname,email=email ,password=password,address=address ,city=city,state=state,zip=zip) connect.save() model.py- from django.db import models Create your models here. class Register(models.Model): fname = models.CharField(max_length=120) lname = models.CharField(max_length=120) email = models.CharField(max_length=120) password = models.CharField(max_length=20) address = models.CharField(max_length=120) city = models.CharField(max_length=120) state = models.CharField(max_length=120) zip = models.CharField(max_length=12) it display name in data base self.name def __str__(self): return self.fname -
NoReverseMatch at /home/ Reverse for 'detail' with arguments '(1, '')' not found. 1 pattern(s) tried: ['(?P<id>[0-9]+)/(?P<slug>[^/]+)/$']
I'm a newcomer in Django. I'm unable to point out exactly what's wrong. I get this error views.py class DetailPost(DetailView): model = Post template_name = 'blog/PostDetail.html' slug_field = 'slug' slug_url_kwarg = 'MySlug' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['post'] = Post.objects.filter(id=kwargs['id'], slug=kwargs['MySlug']) post = context['post'] context['comments'] = Comment.objects.filter(post=post).order_by('create_date__hour') return context urls.py urlpatterns = [ . . path('home/', Home.as_view(), name='Home'), path('<int:id>/<str:slug>/', DetailPost.as_view(), name='detail'), ] home.html <div id="latestp"> {% for item in newposts %} <article> <h1>{{ item.title }}</h1> {% if item.images.image1.url %} <img src="{{ item.images.image1.url }}" class="responsive-image" alt="Smiley face" title={{ item.description }}/> {% else %} <img src="{% static 'img/noimage.png' %}" class="responsive-image" alt="Null" title={{ item.description }}/> {% endif %} <p>{{ item.description|truncatewords:50 }}</p> <a href="{% url 'blog:detail' item.id item.slug %}" class="rm">Read More</a> </article> {% endfor %} </div> what's the matter? is my wrong in HTML code in a tag? -
Inlines for indirectly related models
I'd like to add an inline in the admin for two indirectly related models, more precisely, I wish to generate inlines for foreign keys to the same model. class Order(model.Model): ... class OrderAddress(models.Model): order = models.ForeignKey(Order, on_delete=models.PROTECT) class VendorOrder(models.Model): order = models.ForeignKey(Order, on_delete=models.PROTECT) What i want @admin.register(VendorOrder) class VendorOrderAdmin(admin.ModelAdmin): ... inlines = (OrderAddressInline, ) ... The closest I've come is django-nested-admin but that is used for nesting inline within inlines and not for sibling FKs. Can you point in the right direction on how to solve this? -
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