Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to record a screen of client from server with python django
I want to create an application with django, where client's screen will be recorded from webapp server which will be in django framework (python). The pyautogui library giving me an error for not getting desktop after deployement, although there will be many clients who will requests to the django server. In that case, i want a solution which will serve all the clients simulteneously. -
How to analyze memory in gunicorn+django+gevent framework
I would like to know what memory analysis tools are available in python? We are now using gunicorn+django+gevent, is there a way to analyze the memory without invading the code? -
Django Self Reference Inlines is not working form me
I created a simple Self Reference model for a family tree and when added inlines to the model it is not working , code below: models.py class Person(models.Model): pname = models.CharField("Name",max_length=100) father = models.ForeignKey("familytree.Person", on_delete=models.CASCADE,null=True, blank=True, editable=False) def __str__(self): return self.pname admin.py class PersonInline(admin.TabularInline): model: Person fields = ['pname',] extra: 3 class PersonAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['pname']}), ] inlines: (PersonInline,) admin.site.register(Person, PersonAdmin) -
django-nextjs cause error HTTPConnectionPool
Now i'm doing migartion django to nextjs for frontend page by page. so I installed django-nextjs and set. But when visit the page for migrate at "localhost:8000", it cause error "HTTPConnectionPool(host='localhost', port=3000): Max retries exceeded with url: /en/projectname/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x12ce372b0>: Failed to establish a new connection: [Errno 61] Connection refused'))" Any help or guidance on this would be much appreciated! -
Unable to to access Generic Views with JWT authentcation
I'm at a loss - I have a django backend and react frontend. On the frontend, I have a login page that sets a JWT token, and I use that token to query data from the django backend. This all works perfectly. But I also have direct views to these APIs via something simple as http://localhost:8000/tables/data which will just show me a default django view of these tables (ie: a paginated "select * from data" call) ... and hooked in through a genericListAPIView. Now, as I said, everything works fine when feeding it via a curl command (or postman, or whatnot). I get the JWT token, set it the Authorization access in the subsequent call to the API, and get the data back and do something with in in React. What I can't seem to figure out is how to hoo that same JWT token when calling trying to access the generic view. When I browse to it, I get HTTP 401 Unauthorized Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: JWT realm="api" { "detail": "Authentication credentials were not provided." } Which I guess make sense since I'm not going through any React authentication. Yet, it's the same server. … -
Button doesn't work upon incorporating bootstrap table
After spending days agonizing over this error and looking for someone who might have had this same problem, I'm finally ready to just ask the question myself. I'm building an app on Django. My post button worked perfectly, but upon incorporating bootstrap-table, it doesn't work anymore. And by doesn't work anymore, it seems to have gone completely dormant -- no error logged in the console or terminal, it just looks like a button, but does absolutely nothing. Has anyone encountered a similar issue to this, and how did you fix it? If I take out data-toggle="table" in the table tag, the button works... but it completely messes up the styling, and I'd like to avoid that. Here is my template html: <table id="table" data-toggle="table" data-search="true" data-height="650" data-show-columns="true"> <thead> <tr> <th data-sortable="true">ID</th> </tr> </thead> <tbody> {% if df %} {% for i in df %} <tr> <form method="POST"> {%csrf_token%} <td value="{{i.ID}}"><input value="{{i.ID}}" name="dataId" type="text" class="form-control" aria-label="Large" aria-describedby="inputGroup-sizing-sm"></td> <td> <form method="POST"> <button type="submit" class="btn btn-secondary" name="updatePlacement">Save</button> </form> </td> </form> </tr> {% endfor %} {% endif %} </tbody> </table> and part of my view: def post(self, request): if "updatePlacement" in request.POST: print('hi') return render(request, "placement/index.html") -
OperationalError at ____ no such table: _____
I am making a Django application and I created a model. I ran the 'makemigrations' and 'migrate' with no problem. I also 'ranserver' with no problem. But when I tried to access it via the admin interface I got a "OperationalError at /api/profiles/ no such table: api_profile" here's my models.py: from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator from datetime import date from .countries import COUNTRIES class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) def username(self): usern = User.objects.get(id=self.user) usern = usern.username return usern setup = models.BooleanField(default=False) dob = models.DateField() def age(self): today = date.today() age = today.year - self.birthday.year - ((today.month, today.day) < (self.birthday.month, self.birthday.day)) return age orgin = models.CharField(max_length=300, choices=COUNTRIES) lives = models.CharField(max_length=300, choices=COUNTRIES) bio = models.CharField(max_length=150) email = models.CharField(max_length=255) hobbies = models.CharField(max_length=225) image = models.ImageField(upload_to='images') How can I solve this issue? -
Did the option 'Sign In with Twitter' had removed from twitter app settings?
There's no such option at my app's settings. Where can I find? I tried to log in with the app, but it just authenticate, not log in. I checked the user had added to the DB of my program, but everytime I try to log in, it redirects without log in. -
django login_redirect_url w/ urls.py containing userid
I'm trying to display all objects based on who is currently login In my setttings.py I have LOGIN_REDIRECT_URL = '/clearance/index/<str:userid>' In views.py def index(request, userid): context = {} context['items'] = ClearanceItem.objects.filter(resolve_by_userid=userid) return render(request, 'clearance/index.html', context) In urls.py path('clearance/index/<str:userid>', views.index) Its not showing error's just blank page. And in my browser's url http://127.0.0.1:8000/clearance/index/%3Cstr:userid%3E I want to get rid of str:userid but if I remove it on LOGIN_REDIRECT_URL it's throwing page not found -
submit select value from template to django form
I have a Group model: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=55) description = models.TextField() joined = models.ManyToManyField(User, blank=True) and a form to update the said group: class UpdateGroup(UpdateView): model = Group form_class = UpdateGroupForm template_name = 'update_group.html' def form_valid(self, form): group = form.save() return HttpResponseRedirect(reverse('user_detail', args=[str(group.pk)])) I want the leader of the Group to have the ability to give over their leadership to another member who has joined. In my UpdateUser template I have two buttons: <form method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit" name="update">UPDATE</button> <select> {% for member in group.joined.all %} {% if member != group.leader%} <option value={{ member }}>{{ member }}</option> {% endif %} {% endfor %} </select> <button type="submit" name="change_leader">CHANGE LEADER</button> </form> The frontend works here and it renders how I want, the only issue now is how do I submit an update to the Group with theUPDATE button and just the leader of the group with the CHANGE LEADER button? Do I need two different forms? I would like the CHANGE LEADER button to update the form and return to the GroupDetail view, but only if that button is clicked. Meaning, if by mistake the leader clicked one of the <option value={{ member … -
Determine which DRF auth class authenticated successfully first
Let's say I have the following Django Rest Framework authentication class order: REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.TokenAuthentication", "rest_framework.authentication.SessionAuthentication", "MyCustomAuthClass", ], ... } Per the docs: REST framework will attempt to authenticate with each class in the list, and will set request.user and request.auth using the return value of the first class that successfully authenticates. Within my view I want to know which class authenticated successfully. My use case is that I want to handle the third auth class differently for a specific endpoint. I'm currently re-authenticating which seems unnecessary and not performant: def get(self, request): if ( not TokenAuthentication().authenticate() and not SessionAuthentication().authenticate() and MyCustomAuthClass().authenticate(request): # do this else: # do something else Is there anyway to do that or is my approach the best option? -
Django prefetch_related fields with nested select_related fields
Im trying to fetch Team details with team members details also.So i prefetch_related team_member table which is linked to employee table and that is linked to User table. when i executed the code.It calls user table multiple times.Please help on this.Thanks in advance. #query queryset = Team.objects.prefetch_related("team_members__employee")\ .prefetch_related("team_members__employee__user").filter( team_members__employee__id=employee.id) #db call SELECT ••• FROM "leavetracker_team" INNER JOIN "leavetracker_teammember" ON ("leavetracker_team"."id" = "leavetracker_teammember"."team_id") WHERE ("leavetracker_teammember"."employee_id" = 7 AND "leavetracker_team"."id" = 16) LIMIT 21 8.00 Sel Expl + SELECT ••• FROM "leavetracker_teammember" WHERE "leavetracker_teammember"."team_id" IN (16) 0.00 Sel Expl + SELECT ••• FROM "leavetracker_employee" WHERE "leavetracker_employee"."id" IN (2, 6, 7, 10, 12) 0.00 Sel Expl + SELECT ••• FROM "core_user" WHERE "core_user"."email" IN ('mohammedismailfayeez@gmail.com', 'dhanush@gmail.com', 'fayeezmohammed@gmail.com', 'rajini@gmail.com', 'vijay@gmail.com') 8.00 Sel Expl + SELECT ••• FROM "leavetracker_employee" LIMIT 1000 2 similar queries. Duplicated 2 times. 7.99 Sel Expl + SELECT ••• FROM "core_user" WHERE "core_user"."email" = 'vjs@gmail.com' LIMIT 21 19 similar queries. Duplicated 2 times. 0.00 Sel Expl + SELECT ••• FROM "core_user" WHERE "core_user"."email" = 'maj@gmail.com' LIMIT 21 19 similar queries. Duplicated 2 times. 7.99 Sel Expl + SELECT ••• FROM "core_user" WHERE "core_user"."email" = 'vijay@gmail.com' LIMIT 21 19 similar queries. Duplicated 2 times. 0.00 Sel Expl + SELECT ••• FROM "core_user" … -
Using the navbar with the mouse scroll wheel
I'm currently making a website but I notice that I did not made a way to use the navbar with the mouse scroll wheel and I cant really find a way to make it with JavaScript. I'm using Django and bootstrap's navbar for information sake <nav class="navbar navbar-expand-lg bg-light"> <div class="container-fluid"> <a class="nav-link active" aria-current="page" href="{% url 'index' %}"><img src="../static/Images/Design_sem_nome-removebg-preview.png" alt="" width="38" height="28 " class="d-inline-block align-text-top"> Psicóloga Wilza Diane</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarScroll" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarScroll"> <ul class="navbar-nav me-auto my-2 my-lg-0 navbar-nav-scroll" style="--bs-scroll-height: 100px;"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="{% url 'sobre' %}">Sobre Mim </a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'formacao' %}">Formação</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'contato' %}">Contato</a> </li> </ul> </div> </div> </nav> thanks in advance for your replies! -
How to validade traverse attributes in DRF Serializer
So, trying to be as brief as possible and to put my problem into context, I will tell you here my doubt. The problem is that I don't know how to serialize the data in a correct way. How do I validadte traverse attributes inside serializer? My data model is structured as follows, an employee belongs to a company unit, and this unit belongs to a company, and there is also a super administrator who can access the data of all the other users. # models.py class User(AbstractUser): class Roles(models.IntegerChoices): SUPER = 0, _('SuperAdmins') COMPANY = 1, _('Company') UNITY = 2, _('Unity') STAFF = 3, _('Staff') role: Roles = models.PositiveSmallIntegerField(choices=Roles.choices, default=Roles.STAFF, verbose_name=_("Role")) objects = UserManager() class Company(TimeStampedModel): user: User = models.OneToOneField(User, null=True, on_delete=models.CASCADE, verbose_name=_("User")) cnpj: str = BRCNPJField(_("CNPJ"), unique=True) class Unity(TimeStampedModel): user: User = models.OneToOneField(User, null=True, on_delete=models.CASCADE, verbose_name=_("Usuário")) postal_code: str = BRPostalCodeField(verbose_name=_("CEP"), unique=False) company = models.ForeignKey(Company, related_name='units', on_delete=models.CASCADE, verbose_name=_("Compania")) class Staff(TimeStampedModel): user: User = models.OneToOneField(User, null=True, on_delete=models.CASCADE, verbose_name=_("User")) unity = models.ForeignKey(Unity, related_name="staffs", on_delete=models.CASCADE, verbose_name=_("Unity")) cpf = BRCPFField(_("CPF")) My serializer looks like: class RegisterStaffSerializerForModerators(serializers.ModelSerializer): """ The main goal of this """ username = serializers.CharField(source="user.username", max_length=150, allow_blank=True, validators=[username_validator], ) email = serializers.EmailField(source="user.email", allow_blank=True, max_length=150) first_name = serializers.CharField(source="user.first_name", allow_blank=True, max_length=150) last_name = serializers.CharField(source="user.last_name", … -
Update screen on button click Django
Say I have a screen that looks like this: Times clicked: 0 [button] And every time I click the button, the times clicked would increment by 1. How would I go about doing this? -
Django: Delete A form with javascript
So for more context, I'm making a biolink website which means the issue is adding and removing links for your profile. As of right now, I have a working add function, heres the code: <div class="links-section"> <div class='linkform-container'> {{ link_form.management_form }} <div id='form_set'> {% for form in link_form %} <div class='linkform'>{{ form }}</div> {% if formset.can_delete %} <li>{{ form.DELETE }}</li> {% endif %} {% endfor %} </div> <div id="empty_form" style="display:none"> <div class='linkform'>{{ link_form.empty_form }}</div> </div> <div class="add-remove-button-container"> <i class="fa-solid fa-plus add-link-button link-button" type="button" value="Add More" id="add_more"></i><i class="fa-solid fa-xmark remove-link-button link-button" type="button" value="Remove More" id="remove_more"></i> </div> <script> $('#add_more').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); </script> But I need a way to delete a formset. Preferably this can be javascript and removable with a click on a button. PS: I'm VERY sorry that this isn't explained well because im not very good at explaining, but i'm hoping its understandable and it means a lot because I can't find the solution anywhere else -
Django Mixin called twice and returns diferent responses
I've been strugglig with this bug for a week. I created a mixin BaseMixin to provide common data for two views EmailView and PanelView. class BaseMixin(ContenxtMixin): def get_context_data(self, hash, **kwargs): context = super().get_context_data(**kwargs) try: ficha = self.get_ficha(hash) print("TRY") except Exception as e: print("EXCEPT") # more code return context def get_ficha(self, hash): pass class EmailView(BaseMixin, TemplateView): template_name = "app/cotador/cotacao_email_produtividade.html" def get_context_data(self, hash, **kwargs): context = super().get_context_data(hash, **kwargs) # more code return context class PanelView(BaseMixin, TemplateView): login_url = '/login/' redirect_field_name = 'next' template_name = "panel/proposta.html" def get_context_data(self, hash, **kwargs): context = super().get_context_data(hash, **kwargs) # more code return context Whenever I call EmailView it calls the BaseMixin twice. First with the hash parameter, going into the try block and the second time lacking the hash and raising an exception. I noticed this behaviour by printing from within the try/except block: TRY INFO 2022-07-27 20:33:04,954 "GET /minhas-propostas/proposta/951c18b30ba2999860fa3324199d1272ae0275480b6453f54f90e348fe834bad HTTP/1.1" 200 92114 EXCEPT ERROR 2022-07-27 20:33:06,200 Internal Server Error: /minhas-propostas/proposta/Roboto-Regular.ttf And, I have no idea why, Roboto-Regular.ttf shows up in the url instead of the hash!!! Then, when PanelView is called it works well with no errors and is called only once: TRY INFO 2022-07-27 20:44:34,664 "GET /cotacao-produtividade/print/487af3b7bf8e2615702ca662fe8746889750d67264e4ed10a8ada1e67f6ac9ed I dont know how usefull it can be, … -
Django some static file are accessible while other new static files in same folder are not accessible
Some static files in Django are accessible but other new static files in the same folder are not accessible I renamed the previously working file and then named it same as it was before and then browser won't detect that file either. I am not sure what the issue is here. -
Django: how to get HTML input field value to django view?
i want to get a value in an input to a django views, this is not a form as i am not trying to submit any form, i just need the value that is in the input field this is the html template <input readonly name="ref_code" type="text" value="{{ request.user.profile.recommended_by.profile.code }}"> this is my django views code = str(request.GET.get('ref_code')) print("This is the code:" + code) It keep printing This is the code: None NOTE: i have also tried using request.POST.get("ref_code") it did not still work What might be the issue? -
Need Help to resolve error in running djangoQ Task
I am trying run a simple djangoQ task, but I get an error at the end from the djangoQ library. def welcome_mail(): body_to_sent = 'test' print(body_to_sent,"body_to_sent",settings.EMAIL_HOST_USER) EMAIL_HOST_USER = settings.EMAIL_HOST_USER print('about to email') from_email = EMAIL_HOST_USER to_email = [] to_email.append("xx@gmail.com") subject = 'New Fabric - Standalone Nexus 9k Leaf/s for ' email = EmailMessage(subject, body_to_sent, from_email, to_email) email.content_subtype = "html" email.send() Error: 13:59:56 [Q] ERROR Failed [spring-nineteen-muppet-artist] - 'NoneType' object is not callable : Traceback (most recent call last): File "/home/sgang31/.venvs3/netadc3/lib64/python3.6/site-packages/django_q/cluster.py", line 432, in worker res = f(*task["args"], **task["kwargs"]) TypeError: 'NoneType' object is not callable I don't have any arguments to pass to this function, so not sure about the error. -
How to match URL with ?code=string&state=string?
How can I match a url that looks like, for example, this: "login/?code=string&state=string". I'm very new to Python regex and regex in general, so I apologize if this is too simple for a Stack Overflow question. This is what I'm currently trying: re_path(r'^login/(?:code=(?P<code>\w+)/)(?:state=(?P<state>\w+)/)$', views.login, name='login'), -
One to many model POST using API View
I have this model I want to POST this to my location endpoint { "location": { "latitude": "1.23456789", "longitude": "1.23456789", "resources": [ { "url": "s3/locations/1/es.mp4", "name": "lorem_1" }, { "url": "s3/locations/1/en.mp4", "name": "lorem2" } ] } My goal is to add a location with many resources and to do it through a single locations endpoint using API Views This is my view: class LocationView(APIView, api_settings.DEFAULT_PAGINATION_CLASS): queryset = Location.objects.all() permission_classes = (permissions.AllowAny, ) serializer_class = LocationSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return response.Response(request.data) And this is my serializer: class LocationSerializer(serializers.ModelSerializer): resources = ResourceSerializer(source='resource_set', many=True, read_only=True) class Meta: model = Location fields = ('id', 'latitude', 'longitude', 'resources') -
Python - Space before and after operators like =, +, - etc
following the PEP 8 rules for python, you should use spaces before and after operators, for example "x = 1 + 2". I follow this convention and i don't like it without spaces. Currently im working on a Django Project and i want to include a .html document with a keyword. > {% include "pagination.html" with page = shares %} If i run it like written above i get a keyword error: "with" in 'include' tag needs at least one keyword argument. Without the spaces before and after the = it works without problems. Is that the only way or is there an other way? Thank you in advance. -
override mongoengine query mechanism
Let's say that I have 2 mongo collections, being handled using mongoengine at server. class UserA(Document): first_name = fields.StringField() last_name = fields.StringField() country = fields.StringField() class UserB(Document): # completely independent of UserA at storage layer full_name = fields.StringField() country = fields.StringField() UserA and UserB are 2 separate collections (stored separately in database) having separate entries and have nothing to do with each other at the storage layer. UserA can be converted to UserB with this formula at compute (server) layer. def convert_to_userb(user_a): user_b = UserB() user_b.full_name = user_a.first_name + " " + user_b.last_name user_b.country = user_a.country return user_b Now, for some reason I want to override the objects() call in mongoengine of UserB to also fetch data from UserA. Something like @queryset_manager def objects(doc_cls, queryset): actual_results = <Some form of UserA.objects(query_set)> # result that one would get normally without any override additional_results = convert_to_userb(<Some form of UserA.objects(query_set)>) return actual_results + additional_results What's the best way to achieve this? Any particular reason why you would recommend against it, if any? -
Whitelabel Django Application and connecting Google and Facebook accounts
We have a web application that runs on say domain.com. We then have whitelabel users that access the application from subdomain.theirdomain.com. Our application is able to connect Google, Facebook, Twitter accounts using our main domain (domain.com) and our integration with each platform. But when whitelabel users want to connect the process shows the name of our application and redirects to our domain (breaking whitelabel). We are looking at creating a generic application on each platform (google, facebook etc) for our whitelabel users on generic domain xyz-connector.com with a generic name and logo. However the users are not logged in on that domain so when the platform redirects to that domain after the user has successfully gone through the authorization\connection process we cannot associate the connection with the user. We need to know which account has just authenticated so we can update the database. What is the best practice for something like this? Using Django 3. Ideally we want our users to connect\authenticate their accounts directly from their white labeled subdomain or domain. Rather than having to login to xyz-connector.com. Can we share sessions? Or do these services (facebook, google) allow us to pass custom variables they will pass back to …