Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add permissions on the User instance in Django post_save signal?
I would like to add permissions after my object is saved but the permissions don't persist. They are correctly displayed with user_permissions.all() after the refresh_from_db but when I update the model again the queryset is empty. What could be the reason ? @receiver(post_save, sender=Manager) def assign_manager_permissions(sender, instance, created, raw, using, **kwargs): content_type = ContentType.objects.get_for_model(Manager) print('Current permissions:') print(instance.user_permissions.all()) for codename in ['view_manager', 'change_manager', 'add_manager', 'delete_manager']: permission = Permission.objects.get(content_type=content_type, codename=codename) instance.user_permissions.add(permission) instance.refresh_from_db() print('After refresh permissions:') print(instance.user_permissions.all()) -
Data gets lost when being passed to serializer
I am trying to update the information field on my Profile model. The endpoint is receiving the data correctly, but it seems like the serializer does not get the data. I don't understand why and none of my attempts to fix it have worked. Model: class Profile(models.Model): id = models.UUIDField(uuid.uuid4, primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") information = models.JSONField(null=True) def __str__(self): return f'{self.user} Profile' Endpoint: class ProfileView(viewsets.ModelViewSet): serializer_class = ProfileSerializer queryset = Profile.objects.all() def update(self, request, *args, **kwargs): # Retrieve the user's profile profile = Profile.objects.get(user=request.user) # Update the information field with the data from the request data = request.data print(data) # This prints the data correctly serializer = self.get_serializer(profile, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) Serializer: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ["user", "information"] def validate(self, attrs): print(attrs) # this prints an empty OrderedDict return super().validate(attrs) def update(self, instance, validated_data): print(validated_data) # This prints an empty dictionary # Update the information field with the data from the request instance.information = validated_data["information"] instance.save() return instance The data i'm passing through: {"information": {"name": "xxx", "birthday": "xxx}} How is it possible that the data just vanishes? Any help is very appreciated -
Django default migration giving an "make_aware expects a datetime" error
I set a new Django project with version 4.1 and tried migrate default migration tables via python manage.py migrate command. but process fails in the middle i create admin related and auth related table then giving an error make_aware expects a datetime, got 2022-12-23 11:30.50.81.... it's Django's default migration actually, what could trigger datetime related problem? are django's default migrations file corrupted maybe? -
Difference between form validation and data cleaning in DJango
I have got the concept of form validations in DJango at basic level but I am struggling to get grip over what actually cleaning data in DJango means? What's difference between cleaning and validation ? -
Can I change the display order of readonly_fields that use the @admin.display decorator in Django Admin?
Ok, so here's my problem. I'll try not to go round the houses too much. I have a django model which I want to expose with an admin interface. It foreign keys to a user model. Something like (note ordering of other fields): class SomeModel(models.Model): user = models.ForeignKey(...) other_field2 = models.IntegerField(...) other_field1 = models.IntegerField(...) other_field3 = models.IntegerField(...) ... I also have an admin interface for this model which looks like this: class SomeModelAdmin(admin.ModelAdmin): @admin.display(description="User id") def get_user_id(self, obj): return obj.user.id list_display = ( "get_user_id", "other_field1", "other_field2", "other_field3", ) readonly_fields = ( "get_user_id", "other_field1", "other_field2", ) As far as I can see from the docs I can only use the @admin.display decorator for list_display and read_only_fields. But what if I want to change the order that the fields are displayed in? In the above code they'll default to the order defined in the model (read only User id comes first, followed by other_field2 and other_field1 then finally an editable other_field3). I was hoping I could do this by defining a fields tuple or overriding the get_fields method, but this won't work for fields that use @admin.display. Any ideas? -
Django dropdown menu with nested classes not showing form-field in template
Django (4.1.4): I´m trying to display a dropdown-menu for changing the status of "MyModel" in a table using a form, bot the fields are not shown in the template. I also tried to use javascript to enable the change of the status dynamically. Both approaches failed. Changing the status trough the admin page is working properly, as well as displaying the current status in the template. The project is based on the Visual Studio Django Webapp template. The following stylesheets and scripts are included: bootstrap 3.0.0, jquery-1.10.2 jquery-2.2.4 ajax/libs/bootstrap-fileinput/4.4.7 Is MyModel correctly structured and are choices properly used? Where are the mistakes? I assume, they might be in the forms.py-file, but I cannot find them. Following many tutorials, none of them worked for me. Also checking other posts did not help me further, like this one: Django form not showing up in template models.py: import uuid class MyModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=100, unique=True, verbose_name='Name') class Status(models.Choices): IN_ARBEIT = 'Modell in Arbeit' BEREIT = 'Bereit' DOKUMENTATION = 'Dokumentation' FERTIGGESTELLT = 'Fertiggestellt' ZU_AKTUALISIEREN = 'Zu aktualisieren' REVISION = 'In Revision' status = models.CharField( max_length=30, choices=Status.choices, default=Status.IN_ARBEIT, verbose_name ='Bearbeitungsstatus' ) I would apprappreciate your help! 1ST approach without javascript: … -
Add severity in JIRA json dump api
I'm creating a JIRA ticket from the python api, i'm able to create the ticket with the same detials i'm providing on the dump except the severity. payload = json.dumps( { "fields": { "project": { "key": "xyz" }, "summary": summary", "assignee": { "id": account_id }, "description": "description", "issuetype": { "name": "Bug", "severity": 'S2' } } } ) This is the data payload i've written. Here even after providing severity as S2 or even S1, I'm still having my JIRA ticket generated as S3. please help me out on this pushed severity inside the issue type as S2/S1 -
Django: how to write a conditional statement to check if a post status was changes from live to cancel in django?
i want to write a condition that would show a warning message when a user try to change the status of a an object to cancel that already have a participant in the object. The conditional statement seems not to be working. class PredictionUpdate(ProductInline, UpdateView): ### SOME OTHER CODE def dispatch(self, request ,*args, **kwargs): obj = self.get_object() if obj.user != self.request.user: messages.warning(self.request, "You are not allowed to edit this bet!") return redirect("core:dashboard") if obj.status == "finished": messages.warning(self.request, "You cannot edit this bet again, send an update request to continue.") return redirect("core:dashboard") ###### This is the section that is not working if obj.participants and obj.status == "cancelled": messages.warning(self.request, "You cannot cancel a bet that already have participants") return redirect("core:dashboard") return super(PredictionUpdate, self).dispatch(request, *args, **kwargs) models.py class Predictions(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) title = models.CharField(max_length=1000) participants = models.ManyToManyField(User, related_name="participants", blank=True) It sets the post to cancel even if there is already a participant. what i want is this, provided there is already at least 1 participant in the object, i want to show a warning message that they cannot cancel the post and redirect them back to the dashboard. -
Django session variables not saving when back button clicked
On my page i am trying to implement a recently viewed section on my home page. The problem is when I append a new item to request.session["recently-viewed"], the item i just viewed gets deleted from the list when i load a new page. There is a similar question that has been asked but the only answer was a solution using javascript. If possible could solutions stay away from javascript. views.py def item(request, item_id): if "recently-viewed" not in request.session: request.session["recently-viewed"] = [item_id] else: request.session["recently-viewed"].append(item_id) -
clickable nodes with post request with django and pygraphviz
As a beginner in the use of Django and pyGrphViz, I will probably not present my problem in the most rigorous way. My final goal is to be able, when I hover a node of my graph, to highlight another element of the page, and to be able to make a post request to my server by clicking a node. Not seeing how to do this, I tried to highlight the elements when clicking. I managed to get a clickable svg image of my graph on my server, thanks to the tag and the URL attributes of pyGraphViz. However it doesn't do what I want because when I click on a node, if I filled in a URL outside localhost, for example wikipedia, it displays in a small scrollable window instead of redirecting me to the page. Moreover, it's impossible to redirect me to a window of my own site for the moment in localhost, even when no post parameter is required. I think I need to use the "target" attribute of the nodes to explain that I want to make a new post request in the current window but I didn't really find an example. I think I may … -
Django: if statement not working in django class based view?
i want to write a condition that would show a warning message when a user try to change the status of a an object to cancel if there is already a participant in the object. The conditional statement seems not to be working. class PredictionUpdate(ProductInline, UpdateView): ### SOME OTHER CODE def dispatch(self, request ,*args, **kwargs): obj = self.get_object() if obj.user != self.request.user: messages.warning(self.request, "You are not allowed to edit this bet!") return redirect("core:dashboard") if obj.status == "finished": messages.warning(self.request, "You cannot edit this bet again, send an update request to continue.") return redirect("core:dashboard") ###### This is the section that is not working if obj.participants and obj.status == "cancelled": messages.warning(self.request, "You cannot cancel a bet that already have participants") return redirect("core:dashboard") return super(PredictionUpdate, self).dispatch(request, *args, **kwargs) models.py class Predictions(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) title = models.CharField(max_length=1000) participants = models.ManyToManyField(User, related_name="participants", blank=True) It sets the post to cancel even if there is already a participant. what i want is this, provided there is already at least 1 participant in the object, i want to show a warning message that they cannot cancel the post and redirect them back to the dashboard. -
Django - Annotate field
I have 3 models: class Calendar(models.Model): ... supplier = models.CharField(...) subassort = models.CharField(..., null=True) class SupplierProductAssortments(models.Model): subassort = models.CharField(...) supplier = models.CharField(...) ui2_code = models.CharField(...) class UI2(models.Model): code = models.CharField(...) name = models.CharField(...) I need to annotate ui2 field to queryset of Calendar. For better understanding below I wrote a function that demonstrates it: def get_calendars_with_ui2s(): calendars = Calendar.objects.all() # need to annotate ui2 names for calendar in calendars: if subassort := calendar.subassort: ui2_codes = SupplierProductAssortments.objects\ .filter(supplier=calendar.supplier, subassort=subassort)\ .values_list('ui2_code', flat=True) ui2 = UI2.objects.filter(code__in=ui2_codes).values_list('name', flat=True) calendar.ui2 = ui2 return calendars If when filtering ui2_codes was by one field I guess it could be solved by OuterRef. But there are filtering by two fields. How can I annotate field ui2? -
Running multiple Django apps under same domain with Gunicorn & Nginx?
I have a static website that works domain.com and a Django project that works domain.com/djangoproject1, now I'm trying to add another Django project as domain.com/djangoproject2, this is my sites-avaliable server { listen 80; listen [::]:80; server_name domain.com www.domain.com; return 301 https://$host$request_uri; } #upstream djangoapp1 { # This did not work # server 127.0.0.1:9000 fail_timeout=0; #} #upstream djangoapp2 { # This did not work # server 127.0.0.1:7000 fail_timeout=0; #} server { listen 443 ssl; server_name ...; ssl_certificate ... ssl_certificate_key ...; root /var/www/portfolio; #Serves static portfolio and works index index.html; #Serves static portfolio and works location / { try_files $uri $uri/ =404; } location /djangoapp1static/ { #Works for app 1 and matches settings alias /home/djangoapp1... } location /djangoapp2static/ { alias /home/djangoapp2... } location /djangoapp1{ alias /home/djangoapp1/src/; include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; #WORKS #proxy_pass http://djangoapp1; #Does not work even without the second app #proxy_pass http://127.0.0.1:9000; #Does not work even without the second app } location /djangoapp2{ alias /home/djangoapp2/src/; include proxy_params; proxy_pass http://unix:/run/djangoapp2.sock; #This works for djangoapp1 but not for this one #proxy_pass http://djangoapp2; #Tried did not work #proxy_pass http://127.0.0.1:7000; #Tried did not work } } Currently the djangoapp1 works normally while the djangoapp2 works only when I manually run it with gunicorn --bind 127.0.0.1:7000 … -
Disable foreign key link in django admin
I've got a Django admin site with two models : Client and User (Users are member of a Company working with Clients). Each client has a user referent, so Client has a field 'sales_contact' which is a Foreign Key to User. class Client(models.Model): first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=25) email = models.EmailField(max_length=100) phone = models.CharField(max_length=20) mobile = models.CharField(max_length=20) company_name = models.CharField(max_length=250) date_created = models.DateTimeField() date_updated = models.DateTimeField() sales_contact = models.ForeignKey( to=User, on_delete=models.PROTECT, limit_choices_to={'role':2} ) def __str__(self): return f"{self.first_name}, {self.last_name}" class ClientAdmin(admin.ModelAdmin): fields = ['last_name', 'sales_contact'] A user only having 'view client permission' can however click on the name of the 'sales_contact' (corresponding to a link to the user change view) and will be directed to the 403 Forbidden page. enter image description here According to me, it would be preferably to disable this link when user has no change permission. I tried to use list_display_links but it only works with list view, not detailed views. How to do this, please ? Livior -
Correct way to make a "back/cancel" button in django
I wanna know what the correct way of a back button is. These are the options i found. <a href="{{request.META.HTTP_REFERER}}">Cancel</a> And <button onclick="history.go(-1)">Cancel</button> I'm curious if there is any other/better way. -
Django 3.2 post_save signal invoked for all model instances even if 1 instance is used in the code to save
Is post_save signal called for all the mailbox model instances when we click save button in django model admin? Does the post_save signal work continuously in Apache server?When it is executed behind Apache, just when we refresh the page it again saving the same password in next password column as the previous password column.I need to check password history for 5 passwords to not repeat.The post_save code: def check_oldest_password_instance(mbox): passwd_list = [] oldest_password = None oldest_password_datetime = datetime.now() pfield = '1' n = 0 mphistory = Phistory.objects.filter(mbox=mbox) if mphistory: print('======phistory exists====', mphistory) for p in mphistory: if p.password1: passwd_list.append(p.password1) oldest_password_datetime = p.datetime1 oldest_password = p.password1 pfield = '1' if p.password2: passwd_list.append(p.password2) if oldest_password_datetime > p.datetime2: oldest_password_datetime = p.datetime2 oldest_password = p.password2 pfield = '2' if p.password3: passwd_list.append(p.password3) if oldest_password_datetime > p.datetime3: oldest_password_datetime = p.datetime3 oldest_password = p.password3 pfield = '3' if p.password4: passwd_list.append(p.password4) if oldest_password_datetime > p.datetime4: oldest_password_datetime = p.datetime4 oldest_password = p.password4 pfield = '4' if p.password5: passwd_list.append(p.password5) if oldest_password_datetime > p.datetime5: oldest_password_datetime = p.datetime5 oldest_password = p.password5 pfield = '5' print(len(passwd_list),pfield,'passwd_list_len,pfield_oldest') n = len(passwd_list) # For new mailbox, check if all 5 values are populated # if n == 0: # pfield = '1' if n == 1: … -
want to remove the extra space from the values while searching in the django admin
I have a list and as the text is too long i have applied the line breaks in it using the code as below: and also showing an example for the text TESTTRACK00000000000 000000008 def track(self, obj): if obj.tracking_no: line_length = 20 # used to break the text when it reaches 20 characters lines = [obj.tracking_no[i:i+line_length] + '\n' for i in range(0, len(obj.tracking_no), line_length)] return ''.join(lines) return obj.tracking_no but when copying the text for applying search in it there is a space coming in between like TESTTRACK00000000000 000000008 when copying the text for searching i want it as TESTTRACK00000000000000000008 . need to remove the extra space in it. I tried using strip() but its not working -
Create Django admin panel where project is created using another language
I have created a project using Golang. I have used PostgreSQL as the database. Now I want to make an admin panel for this project using Django. I want directly reflect the database tables in the Django admin panel. As I am not running the project under the Django server and I don't have any apps and models, how can I show them in the admin panel? -
How to set different permissions for GET and POST methods with ListCreateAPIView?
I would like to set IsAuthenticated permission for GET and IsTeamLeader permission for POST with ListCreateAPIView and ModelSerializer, but without having a unique permission that check the request method in has_permission, as suggested in these questions here and here. How could I do that ? @permission_classes([IsAuthenticated]) class ManagerListView(ListCreateAPIView): queryset = Manager.objects.all() serializer_class = ManagerSerializer class IsTeamLeader(permissions.BasePermission): def has_permission(self, request, view): if Manager.objects.filter(pk=request.user.pk).exists(): return Manager.objects.get(pk=request.user.pk).is_team_leader class ManagerSerializer(serializers.ModelSerializer): password1 = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) fields = serializers.JSONField(write_only=True) def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError('Passwords must match.') return data def create(self, validated_data): data = { key: value for key, value in validated_data.items() if key not in ('password1', 'password2') } data['password'] = validated_data['password1'] user = self.Meta.model.objects.create_user(**data) return user class Meta: model = Manager fields = ('id', 'email', 'first_name', 'last_name', 'username', 'role', 'is_team_leader', 'password1', 'password2', 'fields') read_only_fields = ('id', 'first_name', 'last_name', 'role', 'is_team_leader', 'address', 'contact') -
How do I run a function in the background of my Django server and send the output to the correct view?
I have a queue of users defined as: class QueueItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) In addition, I have the following functions to interact with the queue: def should_pair(user1, user2): # Add user preferences later # compare the attributes of the two users and return True if they should be paired, False otherwise if user1.school == user2.school: return True return False def pair_users(): # get all users in the queue users = QueueItem.objects.all() # pair users two at a time for i in range(0, len(users), 2): user1 = users[i] try: user2 = users[i + 1] except IndexError: return None if should_pair(user1, user2): return [user1, user2] return None My question is, is there a way that I can run the pair users function constantly in the background, and when it finds a match, send a common url for the 2 users to a view that can redirect the users to the common link? This is for a video chat app that connects random users (similiar to Omegle). -
how can i override django-rest-auth registration serializer?
I'm using dj-rest-auth (https://dj-rest-auth.readthedocs.io/en/latest/) and trying to implement a custom registration form. in login, i want: username password email(i want to remove it) in signup username email ( i want to remove it) password password2 When I am trying to register a new user I get this error: enter image description here My registration Serializerenter image description here My User model enter image description here -
Docker Container Running But it thorgh the error Teplate does not Exist
Hi I'm New In Docker I Have Created A Django Application Its Running in Local machine Good But When I try To run In docker Container its Run Properly But When I sent Request The Found The Error Template Does Not Exist Dockerfile #syntax=docker/dockerfile:1 #FROM ubuntu:latest FROM ubuntu:latest FROM python:3.8-slim-buster WORKDIR /app #COPY requirements.txt requirements.txt #RUN pip3 install -r requirements.txt # #CMD python . /manage.py runserver 0.0.0.0:8000""" # pull the official base image # set work directory # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN apt-get update&& \ apt-get -y install sudo RUN apt-get install -y tesseract-ocr RUN apt-get install -y build-essential libpoppler-cpp-dev pkg-config python-dev mupdf RUN apt-get install ffmpeg libsm6 libxext6 -y RUN apt-get install -y default-jre RUN apt-get install -y default-jdk RUN apt-get update RUN apt-get install -y python3-pip RUN pip3 install --upgrade pip #RUN pip3 install virtualenv #RUN python3 -m virtualenv env #RUN source env/bin/activate COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt # copy project COPY . /app EXPOSE 8000 CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] # My Docker File Look Like that docker-cpmpose.yml version: "3" services: web: build: . command: python3 manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 Folder Structure Directory: … -
Can't Manually Assign Django ModelForm Variables for some reason
I'm can't figure out why it won't set my author field. I'm calling form.author = request.user but it won't set for some reason. It keeps setting to Null Does anybody happen to know what I'm doing wrong? .models class PoopMascot(models.Model): name = models.CharField(max_length=128) image = models.ImageField(upload_to='upload/mascots/') votes = models.ManyToManyField(User, related_name='votes', blank=True) author = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True ) .forms class PoopMascotForm(forms.ModelForm): class Meta: model = PoopMascot fields = ['name', 'image', 'author'] field_classes = { 'class': 'form-control'} widgets = {'author': forms.HiddenInput()} helper = FormHelper() .views def mascot(request): form = PoopMascotForm() user = request.user anonymous_pooper = User.objects.get(username="Anonymous_Pooper") if request.method == 'POST': form = PoopMascotForm(request.POST, request.FILES) form.author = request.user if user.is_authenticated: form.author = user else: form.author = anonymous_pooper if form.is_valid(): print('entering form is valid') form.save() -
Django Query which join two models and find the average of scores
In my model there is some Tests in Tests model, each test have some questions in it which are in Question model , and some types are relate to each test which are in TestTypes model , and there is a QuestionResult model which save the scores of each test: These are the models : Test : class Test(BaseModel): class DifficultyLevel(models.IntegerChoices): EASY = 1 MEDIUM = 2 HARD = 3 types = models.ManyToManyField( 'TestType', related_name='tests', ) questions = models.ManyToManyField( 'question.Question', related_name='tests', blank=True, help_text='Standard tests could have multiple questions.', ) level = models.IntegerField(default=1, choices=DifficultyLevel.choices) title = models.CharField(max_length=255) def __str__(self): return self.title Question: class Question(BaseModel): question_text = models.TextField() def __str__(self): return truncatewords(self.question_text, 7) TestResult : class TestResult(BaseModel): candidate = models.ForeignKey( 'Candidate', on_delete=models.CASCADE, related_name='test_results', ) test = models.ForeignKey( 'exam.Test', on_delete=models.CASCADE, ) test_score = models.DecimalField(default=0.00, max_digits=5, decimal_places=2) def __str__(self): return f'{self.candidate.user.email} - {self.test.title}' TestType : class TestType(BaseModel): title = models.CharField(max_length=255) def __str__(self): return self.title now i want to get the score which each type earned for example test1 got score =90 and test1 has two types : HTML and C++ . Test2 got score = 50 and test2 has two types : HTML and Python now i want to find the score which HTML … -
Log out via GET requests is deprecated and will be removed in Django 5.0
I get this warning while running tests with selenium and pytest. Here's the test method: def test_registration( self, driver, live_server, valid_user_data, django_user_model ): selenium_signup(driver, live_server, valid_user_data, django_user_model) selenium_sign_in(driver, live_server, valid_user_data) page_source = driver.page_source.lower() assert 'sign in' not in page_source assert 'sign up' not in page_source assert 'sign out' in page_source driver.find_element(By.ID, 'btnGroupDrop1').click() driver.find_element(By.XPATH, '//*[contains(text(), "Sign out")]').click() assert 'sign in' in page_source assert 'sign up' in page_source This is where the warning is generated: driver.find_element(By.XPATH, '//*[contains(text(), "Sign out")]').click() Here's the button: <li><a class="dropdown-item" href={% url 'signout' %}>Sign out</a></li> The view uses django LogoutView and here's how it's defined from django.contrib.auth.views import LogoutView urlpatterns = [ path('signout/', LogoutView.as_view(), name='signout'), ... ] What would be a clean way to fix this?