Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to reflect changes that applied directly though database shell to django model?
We had to change the datatype of a table primary key from int to bigint but we did it manually through PSQL for many reasons and now we want that to be reflected in Django. changing the id type like that id = models.BigAutoField(primary_key=True) will create a migration and it will be applied is there any way to mark migration as applied or edit Django tables to avoid migrations here? As we have a really restricted pipeline and changing it to run migration with --fake is a really big hassle so I prefer code changes or database changes over running --fake -
Django- error in if condition of django template language while cheking != condition
here the request.user = timon and user.username = timon so the if couldn't should not run for user timon but it does???? in the list of send message to the timon should not be included -
In Wagtail, I want to expose the API but only to internal/authorized services
I followed the Wagtail instructions to set up the API v2 in my Wagtail CMS. The CMS will be used in headed mode, but I still want to enable the API so that another service can query for the raw information directly. However, I don't want to enable the API to just be publicly accessible, since that would allow malicious actors to completely scrap the contents of my website. How could I add authentication to the API url paths, so that only certain services can access it (probably by sharing a secret)? I've seen that, on a view, I could add something like @login_required, but 1) I'm not sure if I really want other services to be logged in, I just need them to be identified with some secret value and 2) ideally I'd do this at the url rather than the view level, which could change with updates. Even so, I tried extending the PagesAPIViewSet to have a CustomAPIViewSet(PagesAPIViewSet) that included the @login_required tag, but I wasn't able to make that work either (it complained about the get_urlpatterns, for which I could find no workaround trying to extend the method of the BaseAPIViewSet) -
Hot reload in Django app inside docker containers not working
So today is my first day ever to use docker, I tried use it many times but I noticed that hot reload does not work I opened the container using vscode and navigate through the files and tried changing files and nothing happens here's Dockerfile FROM python:3.8-slim-buster WORKDIR /usr/project ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 COPY . . RUN pip install -r requirements.txt and here's docker-compose.yml version: '3.7' services: web: restart : always build: context: . dockerfile: Dockerfile command: sh -c "python manage.py runserver 0.0.0.0:8000" ports: - "8000:8000" env_file: - .env volumes: - .:/user/project even unchecked docker-compose 2 from desktop docker and restarted the app and the containers, still nothing happens, so what am I doing wrong? -
Django - Form-Select field set as not required not working
I have a form and want to make some fields not required. It's working for most, but pairing_rum field (and a few others) are causing some difficulties. For this question I removed the other fields as they are in the same format as rum_pairing. Here is what I tried so far: using the same format as venue ie forms.ModelChoiceField(queryset = Venue.objects.all() - but how can I filter to only get the choices contained within the field of the model? I also tried to modify the forms __init__, but no luck (example below - sorry for the formatting, stack is not letting me putting it in a code format) def init(self, *args, **kwargs): super(ReviewRating, self).init(*args, **kwargs) self.fields['pairing_rum'].required = False Which renders the following error: super(type, obj): obj must be an instance or subtype of type What would be the best way to make pairing_rum field not requried? My current code is as follows: models class ReviewRating(models.Model): user = models.ForeignKey(User,blank=True,null=True, on_delete=models.SET_NULL, related_name="usercomments") product=models.ForeignKey(Product,related_name="comments",null=True, on_delete=models.SET_NULL) pairing_rum = models.IntegerField(choices=RUM_PAIRING, default=0, blank=True) review =models.TextField(max_length=250, blank=True) rating =models.IntegerField(choices=RATING, default=0) venue = models.ForeignKey(Venue, blank=True, null=True, related_name="venues", on_delete=models.SET_NULL) forms class ReviewForm(forms.ModelForm): venue = forms.ModelChoiceField(queryset = Venue.objects.all(),required=False) class Meta: model = ReviewRating fields = ['review', 'rating','venue','pairing_rum'] widgets = { … -
How to see what data is passed to the class?
I have a product model with a json field as product attributes. I want to make filters on all keys of this field. I am using Djnago-filter. enter image description here When I declare a field and process this request in the method, everything works. Example: tip = django_filters.CharFilter(method = 'filter_attrs') "api/v1/product/?tip=Городской" name = tip in the "filter_attrs" method I get the name argument which is equal to the key in the filter. Its work. But if I make such a "api/v1/product/?ves=30" request, the method is not even called. So I want this method to process requests regardless of what is in the name argument. I wanted to see inside the class what request comes in and in what case the method is called, and override this rule. But I don't understand how to do it. Please help me how to learn how to do this so that in the future I can cope with such tasks on my own I tried to call the "init" method inside which to call print(request,queryset), but this method was apparently not called, I did not see anything in the terminal. I tore off the files filterset.py(djang0_filters/rest_framework/filterset.py) and tried to find methods in which … -
Tell me how to transfer this code from Html to models
There is a code in html {{post.author.posts.count}} that counts the number of posts by the author. I have such a question, how to transfer it to views.py The code looks like this. enter image description hereenter image description here I need to find an existing post, find its author and sort all posts by this author and calculate the total number of posts -
psycopg2.errors.ActiveSqlTransaction: CREATE DATABASE cannot run inside a transaction block
I am trying to create a Django app that creates a new database for every user when he/she signs up. I am going with this approach due to some reason. I have tried many ways using management commands and even Celery. But I am still getting the same error. 2022-12-23 07:16:07.410 UTC [49] STATEMENT: CREATE DATABASE tenant_asdadsad [2022-12-23 07:16:07,415: ERROR/ForkPoolWorker-4] Task user.utils.create_database[089b0bc0-0b5f-4199-8cf3-bc336acc7624] raised unexpected: ActiveSqlTransaction('CREATE DATABASE cannot run inside a transaction block\n') Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/celery/app/trace.py", line 451, in trace_task R = retval = fun(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/celery/app/trace.py", line 734, in __protected_call__ return self.run(*args, **kwargs) File "/app/user/utils.py", line 45, in create_database cursor.execute(f'CREATE DATABASE tenant_{tenant_id}') psycopg2.errors.ActiveSqlTransaction: CREATE DATABASE cannot run inside a transaction block This is my task @shared_task def create_database(tenant_id): conn = psycopg2.connect(database="mydb", user="dbuser", password="mypass", host="db") cursor = conn.cursor() transaction.set_autocommit(True) cursor.execute(f'CREATE DATABASE tenant_{tenant_id}') cursor.execute(f'GRANT ALL PRIVILEGES ON DATABASE tenant_{tenant_id} TO dbuser') cursor.close() conn.close() I have tried several ways but I always get the same error This is my API call def create(self, request, *args, **kwargs): serializer_class = mySerializer(data=request.data) if serializer_class.is_valid(): validated_data = serializer_class.validated_data or = validated_data["org"] or = Org.objects.create(**org) create_database.delay(str(or.id)) return Response(create_user(validated_data)) -
Why does Django app through an error when run in a Docker container
Am building a Django microfrontend App using in docker. When i run the dev server with python manage.py runserver ```, the app spins up at http://127.0.0.1:8000/ but after configuration with Dockerfile and docker-compose.yml, as **Dockerfile** FROM python:3.9 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app CMD python manage.py runserver 8.8.0.0:8000 **docker-compose.yml** version: '3.8' services: backend: build: context: . dockerfile: Dockerfile ports: - 8000:8000 volumes: - .:/app depends_on: - db db: image: mysql:5.7.22 restart: always environment: MYSQL_DATABASE: admin MYSQL_USER: root MYSQL_ROOT_PASSWORD: root volumes: - .dbdata:/var/lib/mysql ports: - 33066:3306 docker-compose up throughs the error; Django version 3.1.3, using settings 'admin.settings' backend_1 | Starting development server at http://8.8.0.0:8000/ backend_1 | Quit the server with CONTROL-C. backend_1 | Error: That IP address can't be assigned to. admin_backend_1 exited with code 1 what am I doing wrong, thanks tried to change the server port at CMD python manage.py runserver 8.8.0.0:8000 to CMD python manage.py runserver 0.0.0.0:8000 expecting to host using my host machine IP address, but all in vain -
Complete the code below to create a query that returns all products with a price greater than 50 that have the word "red" in their name:
`from myapp.models import Product products = Product.objects. #Complete here` I tried to do it but I didn't understand, because I'm a beginner -
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.