Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Queryset Many to many 'ManyRelatedManager' object is not iterable
I'm using Forms to filter the choices of a many to many relationship to only show the ones following a queryset. This is how my Form looks like class ContractAdminForm(forms.ModelForm): class Meta: model = Contract fields = '__all__' def __init__(self, *args, **kwargs): super(ContractAdminForm, self).__init__(*args, **kwargs) self.fields['client_year_periods'].queryset =ClientYearPeriod.objects.filter( Q(contract_id__isnull=True) | Q(contract_id=self.instance.id) & Q(client__in=self.instance.client_entity)) Error: 'ManyRelatedManager' object is not iterable The issue is being caused by Q(client__in=self.instance.client_entity)) I need to filter the model years using the client legal model that is connected to Client Ops. See here how is it built [ Models class ClientLegal(models.Model): name = models.CharField(max_length=350, verbose_name='Client Name') countries = models.ManyToManyField(Country, blank=True) operations_code = models.ManyToManyField(Client) class ClientYearPeriod(models.Model): client = models.ForeignKey(Client, on_delete=models.PROTECT, null=True) [...] class Contract (models.Model): legal_client= models.ManyToManyField(ClientLegal) client_year_periods = models.ManyToManyField(ClientYearPeriod, blank=True) [...] class Client(models.Model): code = models.CharField(max_length=3, verbose_name='Client Code') name = models.CharField(max_length=250, unique=True) -
"Page undefined of undefined" in the pdf using the wkhtmltopdf library
i have used the wkhtml2pdf library, I want to set the numbering of page on my pdf But i didn't reach my goal yet, it always show me "Page undefined of undefined", Here is the code i have go to tag head and make this properties for the div contain the number of pages: <style> div.footer { display: block; text-align: center; position: running(footer); @page { @bottom-center { content: element(footer) } } } </style> then in the body, I have go and add the div with javascript code: <body style="border:0; margin: 0; min-height: 1123px"> <div id="div-body"> #code </div> <div class='footer'> Page <span id='page'></span> of <span id='topage'></span> <script> var vars={}; var x=window.location.search.substring(1).split('&'); for (var i in x) { var z=x[i].split('=',2); vars[z[0]] = unescape(z[1]); } document.getElementById('page').innerHTML = vars.page; document.getElementById('topage').innerHTML = vars.topage; </script> </div> </body> How i can resolve that, thanks in advance. -
How to convert django.utils.timezone.now() into iso 8601 format string?
2022-02-20T06:07:00-0700 What type of date format is it and how to convert django.utils.timezone.now() to this format? -
there a way to use count on single forloop in django template
Hi I want to know how many elements there are numerically within each cycle I do. I tried {{forloop.counter}} but the problem is that they are not in order but scattered. is there a way to use count on single forloop ie dayone? {% if integratori %} {% for dayone in integratori %} {% if giorno >= dayone.inizio and giorno <= dayone.fine %} <h4 class="text-danger">{{ dayone.count }}</h4> <!-- {% if forloop.counter > 3 %} <p>si</p> {% endif %} --> <div class="integrazione"> <div> <img src="{% static 'img/integratori.svg' %}" class="img-fluid"> <h6 class="m-0">{{ dayone.integratore }}</h6> </div> </div> {% endif %} {% endfor %} {% endif %} -
Django ordering by random when using union
I have one Django app when I'm doing random ordering it's working using order_by('?') But not working when I apply random ordering on union queryset. queryset = (queryset.filter(town__istartswith=location).order_by('?')). union(queryset.filter(Q(town__icontains=location) | Q(post_code__icontains=location) | Q(post_area__icontains=location) | Q(street__icontains=location) | Q(country__icontains=location) | Q(agency__operating_areas__icontains=location)).order_by('?')) In my case, if I search with city Helsinki then if it comes in city field then its record display first but in a random order, another record also comes from other fields it is also set random order. For example*: Searching with "Helsinki" city. Then there are four records in which agency city is "Helsinki" then it will come always first but in random order all time and for other record come in random order. [{ "id": 1, "city": "Helsinki", "Name": "Abhishek", }, { "id": 2, "city": "Helsinki", "Name": "Urvesh", }, { "id": 3, "city": "Helsinki", "Name": "Dhruvil", }, { "id": 4, "city": "Helsinki", "Name": "Akshat", }, { "id": 5, "town": "Helsinki", "Name": "Akshat", }, { "id": 6, "country": "Helsinki", "Name": "Akshat", }, { "id": 7, "street": "Helsinki", "Name": "Akshat", }, { "id": 8, "town": "Helsinki", "Name": "Akshat", }] Please help me in this how can I do a random search in the union, Please give me the best solutions … -
Checking if a field in model is modified and creating instance of another model
I have two models Project Model class Project(models.Model): name = models.CharField(max_length=200) workflow = models.ForeignKey("WorkflowType", null=True, blank=True, on_delete=models.SET_NULL) created_on = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) def __str__(self): return self.name Workflow Instance Model class WorkflowInstance(models.Model): workflow_step = models.ForeignKey('WorkflowStep', null=True, blank=True, on_delete=models.CASCADE) project = models.ForeignKey('Project', null=True, blank=True, on_delete=models.SET_NULL) I want to check if the value of workflow field in "Project" models is added or changed for a particular project. I am approaching the problem in following manner: Checking if the previous and the new value of the "workflow" field in a project are different. If yes (modifies), then create the new instance of a project. @receiver(pre_save, sender=Project) def projectToBeUpdated(sender, instance, **kwargs): if instance.id is None: pass else: previous = Project.objects.get(id=instance.id) if previous.workflow != instance.workflow: print("workflow value modified. Please create a WorkflowInstance") Problem: The comparison for previous and new value of the "workflow" field are happening in "pre_save" signal. But my new instance creation for workflowInstance is to be created in "post_save" signal. How can I do this? Also, ideally I would like to store the previous value of workflow field in "pre_save" and get the new value of the field in "post_save". Reason being, save() method might fail for any reason, … -
File "C:\django\2proj\authentication\utils.py", line 2, in <module> from six import text_type ModuleNotFoundError: No module named 'six'
Am trying to import module six in my utils.py but its not working from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type from django_six import text_type class AppTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (text_type(user.is_active) + text_type(user.pk) + text_type(timestamp)) account_activation_token = AppTokenGenerator() but i get this error " File "C:\django\2proj\authentication\utils.py", line 2, in from six import text_type ModuleNotFoundError: No module named 'six'" Am using django 4.0.2 -
Adding new fields to the Object Change History model (Django)
I'm writing my todo in django. I want to add not just the entry "task changed" to the "history" tab, but also two additional fields: "was" - "became". How can I do this? -
How to create range slider filter in django
I want to create a range slider filter in Django where If I change the price from the slider by increasing the range, it should show the servers that have the same price in order. but I tried to create that slider also I researched on google, StackOverflow I couldn't find the answer between I'm using the API instead of models stuff Here's the website sample: https://www.hetzner.com/sb?price_from=30&price_to=380 my code: def index(request): headers = { "User-Agent": "...", "Accept-Encoding": "*", "Connection": "keep-alive" } url = "https://www.hetzner.com/a_hz_serverboerse/live_data.json" response = requests.get(url, headers=headers) data = response.json()['server'] p = Paginator(data, 20) pn = request.GET.get('page') page_obj = p.get_page(pn) context = { 'data': data, 'page_obj': page_obj, } return render(request, 'index.html', context) -
ImportError: Could not import 'authentication.backends.JWTAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'
I am following the example given here : https://www.django-rest-framework.org/api-guide/settings/#accessing-settings. Once I open the django shell using python manage.py shell and run the following command from rest_framework.settings import api_settings print(api_settings.DEFAULT_AUTHENTICATION_CLASSES) I am getting the following error Traceback (most recent call last): File "C:\django_project\.venv\lib\site-packages\rest_framework\settings.py", line 177, in import_from_string return import_string(val) File "C:\django_project\.venv\lib\site-packages\django\utils\module_loading.py", line 30, in import_string return cached_import(module_path, class_name) Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\django_project\.venv\lib\site-packages\rest_framework\settings.py", line 225, in __getattr__ val = perform_import(val, attr) File "C:\django_project\.venv\lib\site-packages\rest_framework\settings.py", line 168, in perform_import return [import_from_string(item, setting_name) for item in val] File "C:\django_project\.venv\lib\site-packages\rest_framework\settings.py", line 168, in <listcomp> return [import_from_string(item, setting_name) for item in val] File "C:\django_project\.venv\lib\site-packages\rest_framework\settings.py", line 180, in import_from_string raise ImportError(msg) ImportError: Could not import 'authentication.backends.JWTAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ModuleNotFoundError: No module named 'authentication.backends' Does someone know what's going on? P.S: I have a very big django project which is failing with the same error, hence I am pinpointing to only the main setting which is failing in this example. -
Django OneToOneField Structure
I have been researching and looking through all the docs but I am still a bit confused, I think maybe because there are multiple ways to use the OnToOneField. I have 4 models, Pregame, Ingame, Postgame and Game. And I want 'Game' to contain the other three models. As of right now it looks like this... class Pregame(models.Model): game_id = models.CharField(max_length=10) other fields... def __str__(self): return str(self.game_id) class Ingame(models.Model): game_id = models.CharField(max_length=10) other fields... def __str__(self): return str(self.game_id) class Postgame(models.Model): game_id = models.CharField(max_length=10) other fields... def __str__(self): return str(self.game_id) class Game(models.Model): game_id = models.CharField(max_length=10) pregame = models.OneToOneField( Pregame, on_delete=models.CASCADE, null=True) ingame = models.OneToOneField( Ingame, on_delete=models.CASCADE, null=True) postgame = models.OneToOneField( Postgame, on_delete=models.CASCADE, null=True) def __str__(self): return str(self.game_id) I am using OnToOne because each Game will only have one Pregame, Ingame and Postgame and the other three models will only belong to one Game. I have a couple questions I am confused about. Will I be able to have a Game object if one of the other model objects doesn't exist yet? Like if there is a Pregame but no Ingame or Postgame, will Game still exist with just Pregame inside of it? I seen a couple videos where they did a … -
django app pytest Key error while testing
I have a problem regarding testing one of views in my django app. I use pytest. Here is the view i'm gonna test: class IngredientDetailsView(View): def get(self, request, id): ingredient = Ingredient.objects.get(id=id) return render(request, 'diet_app/ingredient_details.html', {'ingredient': ingredient}) and it's model: class Ingredient(models.Model): name = models.CharField(max_length=50, unique=True) nutrient = models.IntegerField(choices=NUTRIENTS) glycemic_index = models.IntegerField(choices=GLYCEMIC_INDEX) Here is my fixture and test: @pytest.fixture def example_ingredient(): return Ingredient.objects.create( name='apple', nutrient=2, glycemic_index=2 ) @pytest.mark.django_db def test_ingredient_view(client, example_ingredient): response = client.get(f'/ingredient_details/{example_ingredient.id}/') assert response.status_code == 200 assert response.context['name'] == 'apple' assert response.context['nutrient'] == 2 assert response.context['glycemic_index'] == 2 I still face KeyErrors: FAILED diet_app/tests.py::test_ingredient_view - KeyError: 'name' and don't know why. I'm a fresher using pytest and still learning. I suppose the problem are asserts fields in my test because when i removed field 'name' key error changed to 'nutrient' -
Paginator won't paginate
I use Paginator for paginate my posts, i have no error, and i have the list of page in the bottom of the posts, but: 1.Post doesn't paginate correctly, i have set 5 i have more. 2. When i click on the 2 second page and 3 and etc, i have the same results of posts, i have no the next page with nexts posts. This is my view code: def post_all(request): posts = Post.objects.filter().order_by('-published_date') paginator = Paginator(posts, 5) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) categories = PostCategory.objects.all().annotate(posts_count=Count('post')) return render(request, 'front/blog/post_all.html', {"posts":posts, "categories":categories,"page_obj":page_obj}) Thank u. -
How to limit number of requests user can make in a month using Django rest framework throttling?
I was successfully able to throttle user requests on basis of day, minute, second. But I am not sure what would be the best way to throttle requests on monthly basis i.e. lets say I want 1000 request/month for a user I can use day for achieving the goal like this 34/day, It will limit the requests per day so the user will have to make 34 requests per day to reach the limit, but what I want to give the user liberty to utilize their requests even in a single day or at once. I am using ScopeRateThrottle 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.ScopedRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'subscription_monthly': '2/monthly', } I'll be really thankful for quick response -
How to create and handle a related field in django with react?
I have created 2 models - Tags and Startups. Startups has a tags field with a ManytoMany relationship with Tag. Models.py file - from django.db import models from django_extensions.db.fields import AutoSlugField from django.db.models import CharField, TextField, DateField, EmailField, ManyToManyField class Tag(models.Model): name = CharField(max_length=31, unique=True, default="tag-django") slug = AutoSlugField(max_length=31, unique=True, populate_from=["name"]) def __str__(self): return self.name class Startup(models.Model): name = CharField(max_length=31, db_index=True) slug = AutoSlugField(max_length=31, unique=True, populate_from=["name"]) description = TextField() date_founded = DateField(auto_now_add=True) contact = EmailField() tags = ManyToManyField(Tag, related_name="tags") class Meta: get_latest_by = ["date_founded"] def __str__(self): return self.name My serializers.py file - from rest_framework.serializers import HyperlinkedModelSerializer, PrimaryKeyRelatedField, ModelSerializer from .models import Startup, Tag class TagSerializer(HyperlinkedModelSerializer): class Meta: model = Tag fields = "__all__" extra_kwargs = { "url": { "lookup_field": "slug", "view_name": "tag-api-detail" } } class StartupSerializer(HyperlinkedModelSerializer): tags = TagSerializer(many=True, read_only=True) class Meta: model = Startup fields = "__all__" extra_kwargs = { "url": { "lookup_field": "slug", "view_name": "startup-api-detail" } } My viewsets.py file - from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from .serializers import TagSerializer, StartupSerializer from .models import Tag, Startup from rest_framework.decorators import action from rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_200_OK, HTTP_204_NO_CONTENT from django.shortcuts import get_object_or_404 class TagViewSet(ModelViewSet): queryset = Tag.objects.all() serializer_class = TagSerializer lookup_field = "slug" class StartupViewSet(ModelViewSet): serializer_class = … -
why my django app is not formatted using AWS S3 Bucket?
I have configured AWS S3 to handle the static files and I can see the static folder in my bucket and also its sub-folders such as admin. I don't know what is wrong and why it is not formatting the site with css, images and videos i have in my static file. the static folder was added so why I can't see any effect in the site? -
Need to fetch the column names(field names) along with the values in raw sql query
views.py def view(request): cursor = connection.cursor() with open('D:\Project-Management-Tools\Project-Management-Tools\query.sql','r') as inserts: query = inserts.read() cursor.execute(query) row = cursor.fetchall() return Response(row) I have tried a raw query by inserting a sql file in cursor function. However I am getting the values alone as a response and I need to get the fields name along with the values in the response. Kindly help me to solve this issue. -
update key of specific dict in dict of dicts
I'm creating a dictionary of dictionaries and then trying to update a specific key using for loop. however, all keys are getting updated. code is as follows: transactions = Transaction.objects.all() unique_sellers = ['A002638841D', 'A09876543456'] seller_summary={} summary = { 'total_loan_amount': 0, 'gross_incentive': 0, } for each in unique_sellers: seller_summary[each] = summary seller_summary[each]['total_loan_amount'] = transactions.filter(channel_seller__pin_no = each).aggregate(total_loan_amount=Sum('loan_amount'))['total_loan_amount'] print(seller_summary) total_loan_amount for A002638841D is 1500 total_loan_amount for A09876543456 is 2000 my expectations is output of print(seller_summary) should be {'A002638841D': {'total_loan_amount': 1500, 'gross_incentive': 0,}, 'A09876543456': { 'total_loan_amount': 2000, 'gross_incentive': 0,}} However, I'm getting output as follows my expectations is output of {'A002638841D': {'total_loan_amount': 2000, 'gross_incentive': 0,}, 'A09876543456': { 'total_loan_amount': 2000, 'gross_incentive': 0,}} total_loan_amount is both the dict is getting updated as 2000 instead of 1500 and 2000 respectively -
Failed to import a model into a view DJANGO
Newbie to Django here. I am trying to import a model into views to use it. However I am facing problems doing so. First of all, here is the structure of my folder : project structure webpage folder structure When I try to import one of my models into views with: from .models import model_i_want I get : ImportError: attempted relative import with no known parent package if I try from webpage.models import model_i_want I get : ModuleNotFoundError: No module named 'webpage' if I try to import models like this import .models I get this error setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. My webapp is added in the settings, and everything was running smoothly while following the Django official tutorial. I know I should be reading the documentation and figure it out but I can't seem to understand all of it yet and I am still trying to get used to Django. Thank you and have a nice day! -
how to convert date format in __range look up - django
I'm trying to search between two dates using __range but it expects to write hours during the search and raise this error : ['“2022-02-22data” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] here is my models field created_at = models.DateTimeField(auto_now_add=True) and here is my views.py def my_views(request): start = request.GET.get('from') end = request.GET.get('to') if start and end: total_price = MyModel.objects.filter(created_at__range=(start,end)) else: total_price = MyModel.objects.all() <form action="" method="GET"> <div class="col-12 p-1 mt-1 mx-auto text-center text-light pInside row"> <p class="col-12 col-sm-6 mx-auto text-left row"> from <input type="date" class="form-control col-9 mr-1" name="from" id="from"> </p> <p class="col-12 col-sm-6 mx-auto text-right row"> to <input type="date" name="to" class="form-control col-9 mr-1" id="to"> </p> <button class="btn btn-success col-8 col-sm-5 col-md-3 mx-auto">search</button> </div> </form> i dont want to force the database to only get year, month and day, i have to change the created_at to strftime("%Y-%m-%d") in the filter, but i dont know how to achieve that?! thank you in advance .. -
while creating pdf for repaortlab layout error
raise LayoutError(ident) reportlab.platypus.doctemplate.LayoutError: Flowable <Table@0x7FA13491B898 1 rows x 1 cols(tallest row 900)> with cell(0,0) containing '<Table@0x7FA1349110B8 1 rows x 1 cols(tallest row 894)> with cell(0,0) containing\n'<Table@0x7FA1349894E0 1 rows x 1 cols(tallest row 24)> with cell(0,0) containing\n"<Table@0x7FA134989438 1 rows x 1 cols(tallest row 18)> with cell(0,0) containing\\n\'Vulnerability ( Virustotal Domain Report )\'"''(583.2755905511812 x 900), tallest cell 900.0 points, too large on page 6 in frame 'normal'(583.2755905511812 x 794.8897637795277*) of template 'Later' I make a PDF(A4) size for it and got the error, while Ienter code here make A3 for it the problem is solved, i want the solution for A4 size. if type(data) == dict: all_table = [] for key, value in data.items() : temp = [] temp_table = [] temp.append(key) tool_table_header = Table([temp],colWidths='*') tool_table_header.setStyle(tools_table_header_Style) temp_table.append(tool_table_header) if key != 'Builtwith': t_h = [] t_b = [] for k,v in value.items(): t_h.append(k) t_b.append(v) t_body = [] for index, item in enumerate(t_h): if item != 'status': arr1 = [] arr2 = [] if type(t_b[index]) is list: temp_txt = '' for txt in t_b[index]: temp_txt += txt + ', ' arr1.append(item + ':') text = t_b[index] wraped_text = "\n".join(wrap(str(temp_txt[:-3]), 60)) # 60 is line width arr1.append(wraped_text) else: **arr2.append(arr1) n_table =Table(arr2,[200,370]) n_table.setStyle(Style4) t_body.append(n_table)** tool_header = … -
Django: How to apply Count on the results of a `distinct` QuerySet?
I have the following models: class Exercise(models.Model): name = models.CharField(max_length=300) class UserWorkout(models.Model): user = models.ForeignKey(User) class WorkoutSet(models.Model): exercise = models.ForeignKey(Exercise) user_workout = models.ForeignKey(UserWorkout, related_name="sets") date_time = models.DateTimeField(default=timezone.now) These are simplified models for a workout app, where a user starts a UserWorkout with a set of Exercise objects, then for each exercise they create a few WorkoutSet objects to record how much weight/time etc. What I want to answer: Given a particular user, how many times each exercise has been performed by the user? I want to count all related WorkoutSet objects in 1 UserWorkout as 1. This is what I have now: # 1. Get all Exercise objects performed by the user using WorkoutSet: qs = Exercise.objects.filter(workoutset__user_workout__user=user) # 2. Select the ID and Name only and annotate with the workout ID qs = qs.values('id', 'name').annotate(workout_id=F('workoutset__user_workout__id')) # 3. Get the distinct of both exercise ID and Workout ID qs = qs.distinct('id', 'workout_id') The query set now has the following (correct) data, which is very close to what I want: In [44]: for x in qs: ...: print(x) ...: {'id': 3, 'workout_id': UUID('755925da-9a43-490c-9ffa-3222acd1dcfa'), 'name': 'Ab Rollout'} {'id': 3, 'workout_id': UUID('bc59c55b-9adc-47c7-9790-2e5d8b21f956'), 'name': 'Ab Rollout'} {'id': 3, 'workout_id': UUID('c23c80ea-4408-45d8-bf05-b2d699bee11f'), 'name': 'Ab Rollout'} {'id': 3, … -
Django queryset querying with OR function
I want to make a query (qs) and then another query on the queryset (qs2). In the second query, I want to put an or function, but it can't seem to work (maybe because I don't perform it on 'objects'?) If I only put one filter (membership) on the second query, it works fine. qs = ExpFiles.objects.filter((Q(member_id=id_input) & Q(card_type=card_input))).values(*filter_list).order_by('date_of_measurement') qs2 = qs.filter(Q(membership= membership_input) | Q(note=note_input)).values(*filter_list).order_by('date_of_measurement') -
bypassing the related field manager / referring alternate manager
My model (Lets say class "A") has two managers - the default one (objects), which hides some objects (applies a filter, let's say by a field hidden = models.BooleanField) and the second one, which shows only objects filtered by the default one (so applies opposite filter). So they are mutually exclusive. I did this on purpose, because i don't want to involve these filtered objects anyhow in the admin interface. So far, so good, it works. The problem i have is with related fields. I have a second model where i refer the first one (with these two managers) as ManyToMany field. class B(models.Model): object_a = models.ManyToMany() Now, in the logic i create some objects of the instance A with hidden = True (thus, invisible for the default objects manager of the class A). And i assign these objects to the instance of class B. instance_b.object_a.add(instance_a.hidden_object_a) Now, i thought it does not work, because instance_b.object_a.all() returns empty query result. But then i realised, that the default manager is also applied, so the query is filtered. And in fact, there are hidden objects assigned to the instance_b.object_a, they just cannot be returned by such a reference. How can i refer them … -
Employee model Linked to Django User
I have the Django User model and I created Employee model as below class Employee(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='employees') title = models.CharField(_('Title'), max_length=6, default='Mr', choices=TITLE, blank=False, null=True) firstname = models.CharField(_('Firstname'), max_length=125, null=False, blank=False) In my sidebar.html I can access the username as {{ request.user }} but I want to show the title and firstname from the Employee model on the sidebar.html