Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the IP address of incoming connection in custom PAM module
I am using PAM authentication to authenticate with my linux server. I have created a view on my website through Apache2 where I can use python to manually validate each login through a web shell with facial recognition and two factor authentication. This is working, but I can't seem to recover the IP address of the incoming connection. I need a way to find the IP address of my connection to the server before SSH is connected, in the PAM module which is running Python. I would like to use bash for this. I am trying to execute commands to recover the IP address, I tried using "who" and other commands to see incoming SSH connections to no avail. I also tried using "echo $PAM_RHOST" and "$SSH_CLIENT" and "$SSH_CONNECTION" with no success. -
Django - creating automatically database in postgresql for tests, and deleting it after it
I wonder if there is a possibility to trigger somehow automatic creation of database directly from application's code, only for tests purpose. In the perfect scenario, it should look like: Run the tests in Django Database being automatically created and fulfilled (postgresql) After tests pass, whole database should be deleted. For now what I have, is only fulfilling database with tables, and dropping it after tests, but I can't figure out if there is a possibility to trigger creation of database, so user won't be force to do it manually. I was looking for solution, but couldn't find any proper answer for it. I was trying to find a solution for it in documentation in Django, or postgresql but couldn't find any similar problem. -
Django: convert CharField primary key to IntegerField
I have a model (devices) with a CharField primary key containing integers that I would like to convert to an IntegerField. The problem is the devices are also used as a foreign key in another tables meaning when I change the field in my models.py and run the makemigrations/migrate I keep getting an error prompting me to drop the dependent objects first. How can I change the device primary key to an IntegerField without dropping the dependent objects? models.py class Device(models.Model): id = models.CharField(primary_key=True, unique=True, max_length=255) date_created = models.DateField() class Station(models.Model): id = models.AutoField(primary_key=True) device = models.ForeignKey('Device', on_delete=models.PROTECT) error when running the migration constraint api_station_device_id_117642ec_fk_api_device_id on table api_station depends on index api_device_pkey HINT: Use DROP ... CASCADE to drop the dependent objects too. -
How do I know if my Django project is ready to be deployed?
I already finished my project that I made with django, and I want to upload it. I already bought the domain, and they are about to host it for me.. once they give me the host, I just upload it and that's it? Or are there more steps to do within the code? What do I have to do?. that is, once everything is uploaded to the host, will everything be seen? And the Admin will continue to work, when in the search engine put /admin/ ???. that is, I wonder what are all the steps to follow so that once I host my page everything can be seen. that is, what things would have to be configured in the congif.py, and other things. I would appreciate a lot if you give me advice/tips/solutions.. What I know is that I have to change the debug to DEBUG=False ... And I don't know anything else, once they pass me the port and other host information, I simply upload the files of my project to the host and that's it, nothing more? Isn't it necessary to write more code to show it? Excuse me, I have never displayed a page -
How can I trigger function in django while reading it's output without impacting that functions execution time?
I've been trying to find a solution to my issue for some time now, but I haven't come across anything that seems intuitive enough that it seems like the "right" solution. I'm building an electron app that uses django as the backend. The backend is responsible for running some long processes that are time critical. For example, I have a loop that continuously takes data for about 5 seconds. When I run that function standalone, it takes a data point about every 10 ms, however, when I run it through django it takes a data point anywhere from 10 ms to 70 ms or even longer. This makes sense to me intuitively because django is sharing thread time to keep responding to the frontend. However, this is unacceptable for my application. The delays seem to be related to returning data to the frontend. Basically, there's a static variable in the view class that's a container for the result data, then the measurement is triggered from the front end and the measurement populates that static variable with data. When the measurement is running, the front end queries django once a second for updated data so it can plot it for the … -
How to display a specific color depending on the values of a variable in Django?
For example, if the application.status is "rejected", then background: gray; color: lightgrey. If "accepted" - green and lightgreen. If "in progress", then blue and light blue. <div> {% for application in object_list %} <div style="background: ???; color: ???;"> <span>{{ application.status }}</span> </div> </div> {% endfor %} </div> -
TypeError ... not JSON serializable in Django with no reference to my code in the traceback
Notice that my code is not listed. It is all libraries. Traceback (most recent call last): File "/root/env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/root/env/lib/python3.9/site-packages/django/utils/deprecation.py", line 138, in __call__ response = self.process_response(request, response) File "/root/env/lib/python3.9/site-packages/django/contrib/sessions/middleware.py", line 59, in process_response request.session.save() File "/root/env/lib/python3.9/site-packages/django/contrib/sessions/backends/db.py", line 82, in save obj = self.create_model_instance(data) File "/root/env/lib/python3.9/site-packages/django/contrib/sessions/backends/db.py", line 69, in create_model_instance session_data=self.encode(data), File "/root/env/lib/python3.9/site-packages/django/contrib/sessions/backends/base.py", line 94, in encode return signing.dumps( File "/root/env/lib/python3.9/site-packages/django/core/signing.py", line 150, in dumps return TimestampSigner(key, salt=salt).sign_object( File "/root/env/lib/python3.9/site-packages/django/core/signing.py", line 228, in sign_object data = serializer().dumps(obj) File "/root/env/lib/python3.9/site-packages/django/core/signing.py", line 125, in dumps return json.dumps(obj, separators=(",", ":")).encode("latin-1") File "/usr/lib/python3.9/json/__init__.py", line 234, in dumps return cls( File "/usr/lib/python3.9/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python3.9/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/usr/lib/python3.9/json/encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' Exception Type: TypeError at /financialreconciliation/ Exception Value: Object of type AllCompany is not JSON serializable I knew the offending view via the URL. I did a binary search in the view to try and find the line where it occurred using print statements but I did not find it. I got all the way to the return with print statements and they all showed. Then I did … -
How to I make this If statement work on my Django project?
The if statement looks correct to me but when i save and execute the server, the printed out information is incorrect. Its almost like the information is not being picked up. Am i missing something in my model or view? Or is there anything else that i have to add to the if statement to allow it to see the data i'm trying to have it post? Can someone point out what i'm missing here?? HTML code: {% if leads.lead_status == "Active Deal" %} {% for lead in leads %} <tr> <td data-href="{% url 'leads:lead-detail' lead.pk %}"><i class="far fa-paper-plane"></i> {{ lead.id }}</td> <td>{{ lead.first_name|title }} {{ lead.last_name|title }}</td> <td>{{ lead.city|title }}</td> <td>{{ lead.state|upper }}</td> <td data-href="tel:{{ lead.phone }}">{{ lead.phone }} <i class="fas fa-phone-square"></i> </td> <td>$34,567.89</td> <td> {% if lead.contract_out == "" %} --/--/---- {% else %} {{ lead.contract_out }} {% endif %} </td> <td> {% if lead.contract_back == "" %} --/--/---- {% else %} {{ lead.contract_back }} {% endif %} </td> <td> {% if lead.hearing_date == "" %} --/--/---- {% else %} {{ lead.hearing_date }} {% endif %} </td> </tr> {% endfor %} {% endif %} views.py class DashboardPageView(LoginRequiredMixin, ListView): template_name = 'dashboard.html' context_object_name = "leads" def get_queryset(self): user = … -
Set up DRF Browsable API Root with all api urls
In my urls.py I have many rest framework urls: path( "api/", include([ path("users/", api_views.users, name="users"), path("proposals/", api_views.Proposals.as_view(), name="proposals"), path("requests/", api_views.Requests.as_view(), name="requests"), #... ]) ) I can visit the individual endpoints in the browser and access the browsable API, but I want to set up a browsable API Root where I can see all the available endpoints. The DRF tutorial has an example in which they list the urls they want in the root, but I have a lot of urls and I want all of them to show up. Is there a way to include all the urls in my "api/" path? -
django cloud run custom domain redirecting to login
During development I an able to login and logout just fine. I have deployed the Django app to Google cloud run. I am also able to login with the Service URL which has the syntax https://example-service-xxxxxxx-ey.a.run.app. Furthermore, I have also connected a custom domain via Firebase to the cloud run service and everything works well apart when I signin in which case I am redirected back to the login page. -
Websocket connection to ws://localhost:8000/ws/jobs/<job_id> failed
I am trying to connect to the websocket using django and I'm still getting same connection error. I've checked the documents and using the same code from the tutorial. const jobSocket = new WebSocket( "ws{% if request.get_host != 'localhost:8000' %}s{% endif %}://" + window.location.host + "/ws/jobs/{{ job.id }}/" ); // Execute this function whenever this page receives an event from Job Consumer via WebSocket jobSocket.onmessage = function (e) { var data = JSON.parse(e.data); var job = data.job; console.log(job); l've tried using routing.py and asgi.py to access the path but the error is still the same "raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'ws/jobs/c5d1cc51-c2ad-458e-9cc7-f62520009112/'." I've tried different url patterns, different regrex esspresion and no luck. I tried this create a wair function to see if the websocket would open but it never does. function waitForSocketConnection(socket, callback){ setTimeout( function () { if (socket.readyState === 1) { console.log("Connection is made") if (callback != null){ callback(); } } else { console.log("wait for connection...") waitForSocketConnection(socket, callback); } }, 10); // wait 5 milisecond for the connection... } function updateCourierPosition(map) { let url = `ws://${window.location.host}/ws/jobs/{{ job.id }}/` const jobSocket = new WebSocket(url) waitForSocketConnection(jobSocket,function() { jobSocket.onopen = function(event){ jobSocket.send("connect") … -
Introspecting Django queryset field lookups
I'm building a querybuilder in Django for something similar to an issues dashboard, which allows users to query and save dashboards for custom subsets of the issues in our database (e.g., all issues assigned to team A, created by client X, and created or updated in the current quarter). The frontend would allow the user to interact with the issues API to generate the list of issues they're looking for, and to save the filter criteria so they can visit the page and see an updated list of issues that match the filter criteria. I'm thinking of saving the filter criteria as a dictionary in a JSONField, which I'd pass to the Model.objects.filter and the Q APIs. I'd like to provide the Frontend a list of all eligible Field lookups (e.g., exact, iexact, contains, icontains, in, gt, etc.). Is there a class I can introspect to programmatically get a list of these lookups? I read through the Field Lookup Docs tried looking through the Django source code, but couldn't find something similar to Model._meta.get_fields() for introspecting the fields on a model, as listed in the Model _meta API docs. -
HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'
Hello I had to rewrite my user model for add some filed, I used AbstractUser My models: It's on blog app: class Article(models.Model): author = models.ForeignKey(User , null=True, on_delete=models.SET_NULL , related_name='articles' , verbose_name='نویسنده')... it's on account app: `from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_authour = models.BooleanField(default=False, verbose_name="وضعیت نویسندگی") special_user = models.DateTimeField(default=timezone.now, verbose_name="کاربر ویژه تا") def is_special_user(self): if self.special_user > timezone.now(): return True else: return False is_special_user.boolean = True is_special_user.short_description = "وضغیت کاربر ویژه"` I imported my User view in this way: from account.models import User And I added this to my setting: AUTH_USER_MODEL = 'account.User' I seatched my error but I can't find my solution -
How can I create "profile" urls without explicit passing arguments in django?
I am kinda new at django. For example let's say I'd like to create a BrAnD nEw social network as a pet project. I want my urls to look something like example.com/my-profile but not as example.com/profile/slug_or_pk. I have a user and profile models in different apps for now. Is it actually possible somehow to hide the slug? Models.py class Profile(models.Model): user = models.OneToOneField(User, verbose_name='User', on_delete=models.CASCADE) slug = models.SlugField(null=True) about = models.TextField('About', null=True, blank=True) avatar = models.ImageField("Avatar", upload_to=f"profile/", blank=True, null=True) cover = models.ImageField("Cover", upload_to="profile/", blank=True, null=True) def __str__(self): return self.user def get_absolute_url(self): return reverse('profile_detail', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.user.username) return super().save(*args, **kwargs) class Meta: verbose_name = "Profile" verbose_name_plural = "Profiles" views.py class ProfileDetail(DetailView): model = Profile context_object_name = 'profile' template_name = 'user_detail.html' urls.py urlpatterns = [ path('<slug:slug>/', ProfileDetail.as_view(), name='profile_detail'), ] And the root URLconf: urlpatterns = [ path('', IndexView.as_view(), name='index'), path('register/', RegisterUserView.as_view(), name='register'), path('login/', LoginUserView.as_view(), name='login'), path('logout/', LogoutUserView.as_view(), name='logout'), path('users/', include('users.urls')), path('profile/', include('profiles.urls')), path('posts/', include('posts.urls')), ] I've looked over tutorials, articles and etc.but I didn't manage to find something really useful. Maybe I am wrong somewhere at the fundamentals. Please help! -
AttributeError: module 'django.db.models.signals' has no attribute 'post_syncdb'
I created two models in my Django db. Now, I want to make migrations, but it shows error like this: AttributeError: module 'django.db.models.signals' has no attribute 'post_syncdb' . I tried to google the answer and found that this signal was deprecated in new Django version. It is not my project and I can't change the current version, so my colleagues recommended me to find the solution. What am I supposed to do if I can't change the version of Django and working on dev branch in project? How do I make migrations? What packages I can update? -
Docker redis sync fell into error loop on remote server
I am running Django dev server in docker with celery and redis on my remote host machine. Everything works fine like 30 mins, and then redis starts falling into infinite loop while MASTER <-> REPLICA sync started Here's the console output: redis_1 | 1:S 16 Feb 2023 17:42:37.119 * Non blocking connect for SYNC fired the event. redis_1 | 1:S 16 Feb 2023 17:42:37.805 # Failed to read response from the server: No error information redis_1 | 1:S 16 Feb 2023 17:42:37.805 # Master did not respond to command during SYNC handshake redis_1 | 1:S 16 Feb 2023 17:42:38.057 * Connecting to MASTER 194.40.243.205:8886 redis_1 | 1:S 16 Feb 2023 17:42:38.058 * MASTER <-> REPLICA sync started redis_1 | 1:S 16 Feb 2023 17:42:38.111 * Non blocking connect for SYNC fired the event. redis_1 | 1:S 16 Feb 2023 17:42:39.194 * Master replied to PING, replication can continue... redis_1 | 1:S 16 Feb 2023 17:42:39.367 * Partial resynchronization not possible (no cached master) redis_1 | 1:S 16 Feb 2023 17:42:39.449 * Full resync from master: ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ:1 redis_1 | 1:S 16 Feb 2023 17:42:39.449 * MASTER <-> REPLICA sync: receiving 54992 bytes from master to disk redis_1 | 1:S 16 Feb … -
How to return a standard Django Rest Framework JSON from an enum?
I'm not very familiar with DRF and I haven't found a solution on google for this problem (most answers are about a model with a field as enum, my problem is different) You see, we have an Enum in a Django application. Let's call it SomeValuesEnum. class SomeValuesEnum(Enum): ONE_VALUE = "One value" ANOTHER_VALUE = "Another value" What I need to do is to create a GET endpoint that returns the following { "count": 2, "page_count": 1, "next": null, "previous": null, "results": [ { "value": "One value", "name": "ONE_VALUE" }, { "value": "Another value", "name": "ANOTHER_VALUE" } ] } I know I need to create a serializer, but I haven't been able to create one and "feed it". For example, I started with something like this: class SomeValueSerializer(serializers.Serializer): Meta: model = SomeValuesEnum, fields = '__all__' and on the view: class SomeValueListView(APIView): serializer_class = SomeValueSerializer def get(self, request): choices = [{"value": target.value, "name": target.value.capitalize()} for target in SomeValuesEnum] serializer = SomeValueSerializer(data=choices) return Response(status=status.HTTP_200_OK, data=serializer.data) I also tried this class IncidentSerializer(serializers.Serializer): name = serializers.CharField(required=False, allow_blank=True, max_length=100) value = serializers.CharField(required=False, allow_blank=True, max_length=100) I'm not sure if I'm failing on the creation of the serializer, or in how I invoke him on the view (or … -
Protect views from anonymus users in simpleJWT
so I'm getting this weird issue. I have my simpleJWT auth working on the server but for some reason, I can't get permission_classes=[permissions.IsAuthenticated] to block the view from an anonymous user. There are many similar posts but I can't figure out where the issue is. from rest_framework import permissions class UsersListView(ListView): http_method_names = ['get'] permission_classes=[permissions.IsAuthenticated] def get_queryset(self): return UserModel.objects.all().exclude(id=self.request.user.id) def render_to_response(self, context, **response_kwargs): users: List[AbstractBaseUser] = context['object_list'] data = [{ "username": user.user_name, "pk": str(user.pk) } for user in users] return JsonResponse(data, safe=False, **response_kwargs) I've tried the dumbest approach first and removed allow any from here but no luck REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } Can you spot the issue? -
Django Rest: User validation: Is it safe to access self.request in ViewSet for validation in methods like perform_destroy
I want to validate that the user owns the model (is specified in the special field in the model referenced by this model) when user tries to update or destroy a model. In perform_update and perform_create I can access request to get user (with serializer.context["request"]) and referenced model instance with (serializer.validated_data["another_model"]) But in perform_destroy request is not passed. Is it safe to access self.request (will it always return the same request as request passed to destroy)? Even if django rest becomes async once? Or should I validate user in some other way? -
(Django) Why would my code not execute in an .html template?
this is my first post. I'll try get things right first time. I am having a play around with django and slowly creating a dummy store website. I'm following along a Corey Schafer YouTube tutorial and I didn't have this issue on my first run, so scratching my head now! My problem is that my .html template is not displaying the listing item when I run the page. I still see the <h1>DaftPrices Store Homepage</h1>, but not the listings. This is my template (store_home.html): <!DOCTYPE html> <html lang="en"> <head> <title>DaftPrices - Home</title> </head> <body> <h1>DaftPrices Store Homepage</h1> {% for listing in listings %} <p>{{ listing.item }}</p> {% endfor %} </body> </html> This is saved in a store dir, inside a templates dir, inside the store app. Image of directories This is my app views.py: from django.shortcuts import render listings = [ { 'seller': 'Chazsharpe', 'title': 'Something to sell', 'date_posted': '28th August 3030' } ] def store_home(request): context = {'listing': listings} return render(request, 'store/store_home.html', context) def store_about(request): return render(request, 'store/store_about.html') To clarify, the page pulls the template, but the "code" isn't working I have tried re-writing the dummy listings and changing the variables. I wasn't expecting this to do anything (and … -
Django serializer data
I need to get value of basket in 'title' not in 'id'. How can I do this? How can I get a value of 'title' from 'Position' model in another 'Client' model using ManyToManyField. It automatically transmits ID and the 'title' is required I have tried many ways but... It must be easy, but i search info 2 days class Position(models.Model): title = models.CharField(max_length=150, verbose_name='Title') slug = models.SlugField(max_length=100, unique=True, db_index=True, verbose_name='URL') description = models.CharField(max_length=500, verbose_name='Describe') photo = models.ImageField(upload_to="photos/%Y/%m/", verbose_name='Photo', null=True) price = models.DecimalField(decimal_places=2, max_digits=10, verbose_name='Price') date_create = models.DateTimeField(auto_now_add=True, verbose_name='Date create') date_update = models.DateTimeField(auto_now=True, verbose_name='Date update') is_published = models.BooleanField(default=True, verbose_name='Is published') in_stock = models.BooleanField(default=True, verbose_name='In stock') class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) basket = models.ManyToManyField('Position', default=None, blank=True, related_name='basket') def __str__(self): return f'{self.user.username}, id-{self.user.id}' class ClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = "__all__" class ClientViewSet(viewsets.ModelViewSet): serializer_class = ClientSerializer permission_classes = (IsOwnerOrReadOnly,) def get_queryset(self): pk = self.kwargs.get('pk') # need a list of objects, not an one return Client.objects.filter(pk=pk) result: { "id": 1, "user": 1, "basket": [ 1 ] } need something like this - "basket":['monitor','keyboard'] -
Why would js function not trigger on button click?
I'm trying to follow this guide and I'm having a bit of an issue I can't figure out how to fix. Basically in PassKeys.html you have these 2 following bits of code: <button class="btn btn-success" onclick='start()'>Add Key</button> function start(){ $("#modal-title").html("Enter a token name") $("#modal-body").html(`<p>Please enter a name for your new token</p> <input type="text" placeholder="e.g Laptop, PC" id="key_name" class="form-control"/><br/> <div id="res"></div> `) $("#actionBtn").remove(); $("#modal-footer").prepend(`<button id='actionBtn' class='btn btn-success' onclick="begin_reg()">Start</button>`) $("#popUpModal").modal('show') } Now I'm no JavaScript expert but I would wager that when I click that button (which I can see in my webpage) a function should run that activates a modal. In the example provided by the guide things do work exactly that way, but in my application it doesn't seem to, and the code itself is exactly the same. What could be the cause of that? -
Correct use of pytest fixtures of ojects with Django
I am relatively new to pytest, so I understand the simple use of fixtures that looks like that: @pytest.fixture def example_data(): return "abc" and then using it in a way like this: def test_data(self, example_data): assert example_data == "abc" I am working on a django app and where it gets confusing is when I try to use fixtures to create django objects that will be used for the tests. The closest solution that I've found online looks like that: @pytest.fixture def test_data(self): users = get_user_model() client = users.objects.get_or_create(username="test_user", password="password") and then I am expecting to be able to access this user object in a test function: @pytest.mark.django_db @pytest.mark.usefixtures("test_data") async def test_get_users(self): # the user object should be included in this queryset all_users = await sync_to_async(User.objects.all)() .... (doing assertions) ... The issue is that when I try to list all the users I can't find the one that was created as part of the test_data fixture and therefore can't use it for testing. I noticed that if I create the objects inside the function then there is no problem, but this approach won't work for me because I need to parametrize the function and depending on the input add different groups … -
simpleJWT confirm password field
I'm creating a small app that uses simpleJWT. I want the user to retype their password when registering. Currently, I'm sending data like this { "email":"test", "user_name":"test3", "password":"b12@wsqp" } But what I want to validate is { "email":"test", "user_name":"test3", "password":"b12@wsqp", "password2":"b12@wsqp" } What i have now is class CustomUserCreate(APIView): permission_classes = (AllowAny,) def post(self, request): reg_serializer = RegisterUserSerializer(data=request.data) if reg_serializer.is_valid(): new_user = reg_serializer.save() if new_user: return Response(status=status.HTTP_201_CREATED) return Response(reg_serializer.errors, status=status.HTTP_400_BAD_REQUEST) class RegisterUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'user_name', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance So my guess is to do class RegisterUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'user_name', 'password1', 'password2') extra_kwargs = {'password': {'write_only': True}, 'password2':{'write_only': True}} def create(self, validated_data): password1 = validated_data.pop('password1', None) password2 = validated_data.pop('password2', None) instance = self.Meta.model(**validated_data) if password1 is not None and password2 is not None: if password1 == password2: instance.set_password(password) else: #return some error instance.save() return instance How can I validate if the password are matching? -
Chrome Extension Requesting django server
I am creating a chrome extension that requires a back end server for processing. I would like it to send data to the server, the server will process this data and send some other data back to the user. Preferably this back end server should be in python as there are libraries I would like to use. Any idea how to go about this? I was thinking to use a django server with rest API but I'm not sure what would be best. If anyone could provide a tutorial link or briefly explain the code behind this idea it would be brilliant.