Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to connect Docker database container to any database GUI application?
When I view my tables from container bash on terminal its shows like this So is there any way to connect my database container to any database GUI? -
How to learn Django Framework efficiently?
I've been learning the Django framework for the last 6 months I saw a bunch of video tutorials, read the documentation, and practiced some small projects but still, I do not understand the basics of Django. Please help me to clear the concepts of the Django Web Framework. -
How to deploy Django + React project to hosting platform?
I used Django as backend and React as frontend. I want to know how to deploy this project to hosting platform such as heroku, netlify, etc. Can I deploy this project to one domain? Or should I have to use two doamins - one for Django and one for React? -
Django app via heroku is returning 500 error when only on mobile
I have just deployed an ecommerce site via heroku. I have a product review form which works fine on desktop devices however when i test this on my mobile phone - iphone i get a 500 error. These are the only logs i can see from heroku 2022-07-28T05:56:07.424841+00:00 heroku[router]: at=info method=POST path="/products/2" host=thecoffeeco.herokuapp.com request_id=37ea67d2-0989-41a5-9e34-25166c2649be fwd="151.224.165.76" dyno=web.1 connect=0ms service=584ms status=500 bytes=403 protocol=https 2022-07-28T05:56:07.425962+00:00 app[web.1]: 10.1.16.25 [28/Jul/2022:05:56:07 +0000] "POST /products/2 HTTP/1.1" 500 145 "https://thecoffeeco.herokuapp.com/products/2" "Mozilla/5.0 (iPhone; CPU iPhone OS 14_8_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1" -
git push heroku main
Processing /D:/bld/astroid_1640971040574/work remote: ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: '/D:/bld/astroid_1640971040574/work' I am having the error above when trying to upload to heroku using git push heroku main. Please what's the way forward? -
How can we integrate ory kratos with django+react website
I am having a project to integrate ory kratos for auth. I don't find much of documentation on the implementation of ory with django+react website. I have worked with jwt previously. Does anyone know the complete working process of integrating ory with django+react application. -
I am creating a shopping todo list, it contains multiple shops and each shop have items in it. I want to share a shop with another user (DJANGO)
Like on clicking a share button that specific shop and its items should be transferred to another user and a receiver user can add that shop in its shopping list. I tried Django channels but I failed. I was unable to understand how to send object from a model using channel. Every YouTube Video is sending a text using Django channel. -
Inserting a new instance to a foreign key model in django
Im new at django and new at posting so pardon my mistakes, anyways What I have is a QR login system that will creates a new instance or record of a person scanning their qr code the problem is that Field 'id' expected a number but got Field 'id' expected a number but got "(insert name here) here is the relevant code models.py name = models.CharField(verbose_name='Name', max_length=30,) Truck_Assigned= models.ForeignKey(Truck, on_delete=models.CASCADE) def str(self): return self.name class Attendance(models.Model): name=models.ForeignKey(Helper, on_delete=models.CASCADE) attendace_time=models.DateTimeField(auto_now_add=True)```` views.py ````def qrcodelogin(request): attendance=Attendance.objects.all() attendacecounter=attendanceCounter.objects.all() if not request.user.is_staff: messages.error(request, 'You are not allowed to view this page') return redirect('userProfile') if request.method == 'POST': try: with transaction.atomic(): name = request.POST.get('decodedText') helper=Helper.objects.get(name=name) attendance_log = Attendance(name=helper) attendance_log.save() if attendanceCounter.objects.filter(name=name).exists(): attendanceCounter.objects.filter(name=name).update(counter=F('counter')+1) else: counter_log=attendanceCounter(name=name) counter_log.save() attendanceCounter.objects.filter(name=name).update(counter=F('counter')+1) except Exception as e: print(e) messages.success(request, 'something went wrong')```` -
TestCase for Loginview using ModelViewSet or GenericViewset
I am trying to write a testcase for my login in django rest framework. I tried browsing through net where I tried with APIClient, django-Client, Factory but didn't get the result. I getting the following response: {'non_field_errors': [ErrorDetail(string='Unable to log in with provided credentials.', code='authorization')]} even after supply the correct credentials Here is my test case file: """ Test cases for Login """ import json from django.urls import reverse from django.test import TestCase from rest_framework.test import APIClient class LoginTest(TestCase): """ Login test cases """ def setUp(self): """ Setup data for the login test cases """ self.valid_payload = json.dumps( {"username": "admin@ksbsgroup.com", "password": "dell@123"} ) self.url = reverse("users:login-list") def test_valid_login(self): """ Test login with a valid login """ client = APIClient() response = client.post( self.url, data=self.valid_payload, content_type="application/json" ) print(response.data) self.assertEqual(response.status_code, 200) My Login view is as follows: """ Login view """ import logging from rest_framework import viewsets, status from rest_framework.response import Response from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.authtoken.models import Token from common import messages log = logging.getLogger(__name__) class LoginViewSet(ObtainAuthToken, viewsets.GenericViewSet): """ Login view set for login """ def create(self, request): """ Login the user with the specified email and password. parameters: -------------------- email(str): Email address to login password(str): Password of the user … -
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