Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Join tables which doesnot have any relation but common field
I have two tables clinicalvariable and adherencemeasure. I need to get all records which satisfies condition clinicalvariable.id = adherencemeasure.id. Both tables donot have any foreign key relation so i couldn't use select_related. I need to use Subquery in django.Similar postgres query select * from clinicalvariable as a, adherencemeasure as b where a.id = b.id I tried below code but no luck with it cvar = Clinicalvariable.objects.filter(pmdclinicalvariablerefid=OuterRef('pk')).values('pmdclinicalvariablerefid') Adherencemeasure.objects.filter(crefadherencemeasureid=Subquery(cvar)) I am getting more than one row returned by subquery. -
Django template inheritance doesn't seem to work properly
So I'm trying to use Django inheritance in a program but it doesn't really work, and I'm sure it's something trivial that I'm messing up. It's a simple webpage that saves the birthdays of people and stores them into a database. I'll only be showing the HTML files because I already know that the Python files work. Take a look. That's the default layout template. <!DOCTYPE html> <html lang="en"> <head> {% block head %}{% endblock %} </head> <body> {% block body %}{% endblock %} </body> That's the other template called "index.html". {% extends "layout.html" %} {% block head%} <meta name="viewport" content="initial-scale=1, width=device-width" <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet"> <link href="/static/styles.css" rel="stylesheet"> <title>Birthdays</title> {% endblock %} {% block body %} <div class="jumbotron"> <h1>Birthdays</h1> </div> <div class="container"> <div class="section"> <h2>Add a Birthday</h2> <form action="/" method="post"> <input name="name" autocomplete="off" autofocus type="text" placeholder="Name"> <input name="month" autocomplete="off" autofocus type="text" placeholder="Month"> <input name="day" autocomplete="off" autofocus type="text" placeholder="Day"> <input type="submit" value="Add Birthday"> </form> </div> <div class="section"> <h2>All Birthdays</h2> <table> <thead> <th>Name</th> <th>Birthday {% for name in name %} </thead> <tbody> <tr> <td> {{ name.name }} </td> <td> {{ name.month }}/{{ name.day }}</td> </tr> {% endfor %} </tbody> </table> </div> </div> {% endblock %} I get a 500 Internal error and … -
WebRTC: ICE failed error in browser with Mesibo Video/Audio chat
I am working on a video/audio chat application in React and Django using Mesibo Javascript SDK. It is working locally on the same network but when trying to connect through different networks, Firefox browser gives me this error WebRTC: ICE failed, add a TURN server and see about:webrtc for more details. In Chrome, this error doesn't show up but still the video/audio chat is not working and gives me Mesibo_OnCallStatus: 50. I noticed that Mesibo uses stun:stun.l.google.com:19302 as the STUN server and tried changing it to stun:stun.l.google.com:19305 but of no use. I even created a numb.viagenie.ca account to add a TURN server which worked for a few minutes and then gave this error webrtc: ice failed, your turn server appears to be broken. When checked on https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/, chrome is giving error code:701 for all the above turn/stun servers whereas firefox doesn't. As suggested by Mesibo Documentation, my website is fully secure with https and the Rest APIs are called from Django backend. I'm invoking https://api.mesibo.com/mesibo.js as a script tag in the index.html file in react. I'm also able to successfully get Mesibo_OnConnectionStatus=1 and the incoming call notification is also working. Upon answering the call, the call status changes from 3 … -
Anyone out there have advice for deploying a Django/React app to heroku?
I wanted to open a thread to see how people have had success in doing so. I have viewed a couple articles, like this, but I was hoping to hear more perspectives. Also, as I am running a docker container in development, I was wondering if people had any example dockerfiles for deploying a react/django app to heroku. -
Update ImageField using Django Rest Framework
I am using REST framework for creating APIs. I have ImageField to store Images. class GeneralInfo(models.Model): logo = models.ImageField(upload_to="logo/") school_name = models.CharField(max_length=50) address = models.CharField(max_length=50) Now using PUT request, I want to update the logo which is ImageField. Serializer class looks like this: class GeneralInfoSerializer(serializers.ModelSerializer): class Meta: model = GeneralInfo fields = ["id", "school_name", "address"] def create(self, validated_data): return GeneralInfo.objects.create(**validated_data) def update(self, instance, validated_data): instance.logo = validated_data.get("logo", instance.logo) instance.school_name = validated_data.get("school_name", instance.school_name) instance.address = validated_data.get("address", instance.address) What am I missing? -
How to filter a field by its belonging to the model defined in the original model in Django?
For example I have such models: class Person(models.Model): ... class Group(models.Model): persons = models.ManyToManyField(Person, through='Membership') ... class Membership(models.Model): group = models.ForeignKey(Group) person = models.ForeignKey(Person) class Team(models.Model): group = models.ForeignKey(Group) ... class TeamPerson(models.Model): team = models.ForeignKey(Team) person = # Question about this # So Membership links the Person with the Group and we have Team that relates to a Group. The thing what I need to do is to use in TeamPerson the persons related through the Team -> Group -> Membership -> Person so Django knows that I can choice only the persons that are in the group choose for the team that was choose in the TeamPerson. Actually what I expected is automatic filtering the persons in the TeamPerson admin page when I choice the team. Is there a (right) way to do that? -
Is there any way to add html file dynamically from django admin?
I am very new to django. I want to include html file from django admin dashboard. Let me explain a little. Let, My model is like below class myModel(models.Model): fileName= models.CharField(max_length=100) my views.py file def calcView(request): template_name = 'index.html' filename = Adsense.objects.first() context = {} context['filename'] = filename return render(request, template_name, context) Now i enter filename in as 'anyfile.html'. It already available in template folder. Now in index.html file how can i it from dashboard. Pseudo code {% include "{{ filename.fileInclude}}" %} Is it possible ?? if yes, how can I do this ? Thanks in advance -
Refactoring part of template into own file breaks django
I have something weird: I got a base.html that acts as a skeleton with blocks for the website. It contains this part: <main class="main"> {% block main %} <div class="content"> {% block content %} content {% endblock %} </div> {% endblock %} </main> I also got a base_with_sidebar.html that looks like this: {% extends "core/base.html" %} {% block main %} {{ block.super }} <div class="sidebar"> {% block sidebar %} {% include "polls/recent_polls.html" %} {% endblock %} </div> {% endblock %} and index.html which fills the content: {% extends "app/base_with_sidebar.html" %} {% block content %} somecontent {% endblock %} This all works so far. The problem arises if I want to refactor base.html: from this: <main class="main"> {% block main %} <div class="content"> {% block content %} content {% endblock %} </div> {% endblock %} </main> to this: base.html <main class="main"> {% block main %} {% include './main.html' %} {% endblock %} </main> main.html <div class="content"> {% block content %} content {% endblock %} </div> This results in my index.html always displaying 'content' - instead of the block content specified in index.html -
Using prefetch_related() in Django in combination with raw_id_fields
I'm trying to eliminate queries by prefetch_related(). In the admin with TabularInline this works in all cases, except the ForeignKeyRawIdWidget created by raw_id_fields = ('article',). This is due to the Queryset.get() it does, and filter actions are not supposed to work when prefetching. So for every row in the inline I'll get a seperate query. This blogpost illustrates a workaround: https://blog.mounirmesselmeni.de/2017/02/06/accessing-prefetched-objects-inside-your-models-methods/ The workaround looks quite messy to me, and won't work in this case since the widget does the get. Is there some proper way to do prefetching here or is this a Django prefetching limitation? Not using raw_id_fields is not an option since the default widget does even more queries. Also, I don't understand why filter actions do not check the prefetching cache before actually querying the database. This small step could potentially save multitudes of queries, right? -
You're accessing the development server over HTTPS, but it only supports HTTP. in django
I am building a django app to bookmark images from other sites. But, when I go to any website and click on the "Bookmark" button, I get this error in my terminal: [19/Jan/2021 21:15:00] code 400, message Bad request version ('÷b%2Eí\x10Ð\x80ðB\x90\x00"\x8a\x8a\x13\x01\x13\x02\x13\x03À+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x00') [19/Jan/2021 21:15:00] You're accessing the development server over HTTPS, but it only supports HTTP. I don't get any error in my website though. Is this a problem in my code? -
Is there a way in django to update the same page with the response without totally rendering it?
Is there a way in django to update the same page with the response without totally rendering it. I am trying to create a code editor to test. But when I am returning the results my contents are removed. I understand it is because I am rendering the page . I need the contents to retain. How can I do it using redirect? I am including the render statement I used and a screenshot of how it looks here: Steps: Handle post request Program execution code Save the result in a variable called "message". Then I used return render(request, 'editor.html', {'message': message}) I want to redirect the message to the same page without rendering a new page. [Before submission][1] [After submission][2] [1]: https://i.stack.imgur.com/BxoLU.png [2]: https://i.stack.imgur.com/uiEOU.png Any help will be appreciated. Thank you. -
Can a contains search be made in ElasticSearch in the search query?
I created a django project to learn ElasticSearch and when I search for users in this project, when I enter the username of the user exactly, the result is returned. Can I set this to contains as in django ORM? i use "match" because i just know it. q = request.GET.get('q') users = UserDocument.search().query("match",username=q) -
Posted data doesnt appear on DRF serializer attrs
im having an issue here and cant find out whats happening. I have and DRF REST API which must receive a POST to create an AlertRule object and a couple of EmailAddress objects related to it. The problem is that when debugging the validator method, the email data should come on the attr param on the validator mathod, but its just not there when i send the data obver http post. Example of what im sending: {'alert_event_max_count': 2, 'alert_time_window': 2, 'company': 'Q29tcGFueToxNw==', 'company_id': 17, 'comparison_rule': 4, 'comparison_value': '0', 'daily_start_time': '07:00:00', 'daily_stop_time': '17:59:59', 'emails': [{'email':'bruno.carli@smartgreen.net'}], 'end_date': '2022-01-01', 'installation_ids': [], 'monitored_property_id': 30, 'name': 'kk', 'start_date': '2019-01-01', 'week_day_bitmask':17} The attr only shows: OrderedDict([('alert_time_window', 2), ('alert_event_max_count', 2), ('company', <Company: Company object (17)>), ('comparison_rule', 4), ('comparison_value', '0'), ('daily_start_time', datetime.time(7, 0)), ('daily_stop_time', datetime.time(17, 59, 59)), ('end_date', datetime.date(2022, 1, 1)), ('installations', []), ('monitored_property', <Property: None - None>), ('name', 'loli'), ('start_date', datetime.date(2019, 1, 1)), ('week_day_bitmask', 17)]) Where is the 'emails': [{'email':'bruno.carli@smartgreen.net'}], data i have sent? Here the code: serializers class EmailSerializer(serializers.ModelSerializer): class Meta: fields = ['id', 'email'] model = EmailAddress class AlertRuleSerializer(serializers.ModelSerializer): emails = EmailSerializer(many=True, required=False) ... # other fields class Meta: model = AlertRule fields = [ ... # other fields 'emails' ] depth = 2 def … -
TimeoutError Error while sending email using Django and SMTP protocol
I have a Django project and an app inside the project. Now I am trying to send email using SMTP. But when I am trying send email it's showing this error: TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond The configuration for sending email in settings.py is : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = "MyEmailId" EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_PASSWORD = "MyPass" The code for sending email in views.py is : from django.core.mail import send_mail send_mail( 'email_subject', 'email_body', 'MyEmailId', ['ReceiverEmailId'], fail_silently=False, ) Thanks a lot for help. -
Error while getting database values into form
I am trying to get values from database and import them in checklist inside a form. I am getting values with CustomStudent.objects.all().values_list('sname') but values are retrieved as list which gives error when submitting. This is my forms.py class WeeklyForm(forms.Form): sname = forms.ModelMultipleChoiceField(queryset=CustomStudent.objects.all().values_list('sname'), required = False, widget =forms.CheckboxSelectMultiple( attrs ={'class':' form-check-input' ' form-check-inline'})) class_name = forms.CharField(widget= forms.Select(choices= [('1', 'UKG'), ('2', 'Class 1'), ('3', 'LKG'), ('4', 'Montessori') ] ,attrs={'class': 'form-control', 'placeholder' : 'Select Class'})) fdate = forms.DateField(initial = datetime.date.today() , required=False, widget =forms.DateInput( attrs ={'class': 'form-control' , 'placeholder' : ' Date ', 'name' : 'date'})) tdate = forms.DateField(initial = datetime.date.today() , required=False, widget =forms.DateInput( attrs ={'class': 'form-control' , 'placeholder' : ' Date ', 'name' : 'date'})) objective = forms.CharField(widget = forms.Textarea(attrs={'class': 'form-control', 'placeholder' : 'objective'})) target = forms.CharField(widget = forms.Textarea(attrs={'class': 'form-control', 'placeholder' : 'target'})) how = forms.CharField(widget = forms.Textarea(attrs={'class': 'form-control', 'placeholder' : 'how?'})) material = forms.CharField(widget = forms.Textarea(attrs={'class': 'form-control', 'placeholder' : 'material required'})) support = forms.CharField(widget = forms.Textarea(attrs={'class': 'form-control', 'placeholder' : 'Any Support Required?'})) This is my model class CustomStudent(models.Model): _id = models.AutoField sname = models.CharField(max_length = 50) slname = models.CharField(max_length = 50) password = models.CharField(max_length = 255, default = '') I have tried adding CustomStudent.objects.all().values_list('sname', flat=True) which returns proper name instead … -
Python PIP version
I`m writing a django project, every time When I installed django: pip install "Django==3.0.*" I was encountering a WARNING: WARNING: You are using pip version 19.2.3, however version 20.3.3 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. But the strange thing is when I go to the PIP installations directory on Windows and Check for the pip version, I always got the version upgraded: ...Programs\Python\Python38\Scripts> pip --version pip 20.3.3 from c:\users\... This is very annoying, cause each time I pip install Django I have to upgrade it while it has been already upgraded. Somebody tell me how is this happen? -
how to add a link in django admin app that redirects to a html file
i have an application django admin based, in a specific admin page i have a fieldsets as below: def report(self, obj): return mark_safe(json2html.convert(json=obj.report, table_attributes="class=\"results\" style=\"overflow-x:auto;\"")) fieldsets = ( (None, { 'fields': ('complete',), }), ('Transaction Details', { 'fields': ('chp_reference', 'income_period', 'property_market_rent', 'rent_effective_date', 'number_of_family_group',), }), ('Report', { 'classes': ('collapse',), 'fields': ('report',), }), and in the models.py class Transaction(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) income_period_choices = (('Weekly', 'Weekly'), ('Fortnightly', 'Fortnightly')) chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11, choices=income_period_choices, null=True, blank=True, default='Weekly') property_market_rent = models.DecimalField(help_text='Weekly', max_digits=7, @property def report(self): family_groups = [] for f in self.familygroup_set.all(): family_members = [] for m in f.familymember_set.all(): family_members.append({ 'name': str(m), 'rent_percentage': m.effective_rent_percentage, 'weekly_income': "%.2f" % float(m.weekly_income or 0), 'rent_component': "%.2f" % float(m.income_component or 0) }) report = [ family_groups, 'Household Rent: ' + "%.2f" % float(self.household_rent or 0) ] import json return json.dumps(report, indent=4) what im trying to do is to add a clickable link to the report function, and this link redirect the user to a html file that i will create, instead of the function i made in the models.py. what is the best approach to accomplish this ? -
Django max_length where there should not be a max_length
I do not have a deep understanding of Django, anyway not deep enough to overcome a problem that turns up in my application. In models.py I have a.o. the following definitions: class Relatiedata(models.Model): ... getuigen = models.TextField(blank=True, null=True) ... class Meta: db_table = 'relatiedata' Relatiedata.objects = Relatiedata.objects.using('genealogie') So in the database genealogie, which is not the default database, I have a table relatiedata with a column getuigen that has to contain a text string without a limitation on the length. Further, I have a user form for mutating records of this table. As usual, the form is populated from a Relatiedata.object and the returned form results in another Relatiedata.object which is saved, thereby updating the database. This works (almost) perfect. The problem is that in my form it turns out to be impossible to enter a string of length above 600 in the textarea for getuigen. Longer strings are simply cut off. There seems to be sort of a form validation for the length of that field, despite the fact that there is no such limit in the models, nor in the database, nor in the migration files. This value of 600 comes from earlier, abandoned, implementations of the model, … -
django fieldsets IndentationError: unindent does not match any outer indentation level
from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from authentication.forms import UserForm, CustomUserChangeForm # Register your models here. User = get_user_model() class CustomUserAdmin(UserAdmin): add_form = UserForm form = CustomUserChangeForm model = User add_fieldsets = ( ('Personal Details', {'fields': ('email', 'full_name', 'username', 'picture', 'password1', 'password2')}), ('Permissions', {'fields': ('is_staff', 'is_active')}) ) fieldsets = ( ('Personal Details', {'fields': ('email', 'full_name', 'username', 'picture')}), ('Permissions', {'fields': ('is_staff', 'is_active')}) ) admin.site.register(User, CustomUserAdmin) I am working on web application for this i want to do some customization on my admin panel but it giving Indentation error. I also try it in list but it still showing me same error. What I did wrong! Traceback (most recent call last): File "C:\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "G:\Python\publish\env\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "G:\Python\publish\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "G:\Python\publish\env\lib\site-packages\django\apps\registry.py", line 122, in populate app_config.ready() File "G:\Python\publish\env\lib\site-packages\django\contrib\admin\apps.py", line 24, in ready self.module.autodiscover() File "G:\Python\publish\env\lib\site-packages\django\contrib\admin\__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "G:\Python\publish\env\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 786, in exec_module File "<frozen importlib._bootstrap_external>", line 923, in get_code File "<frozen importlib._bootstrap_external>", line 853, in … -
How to add a custom input field into some Model Create form in django Admin
The question is How to add some custom form fields into django model create form and handle their values before create new Model into DB. I'm using django for my site, and there is a simple model Specialist { name, diploma, email, phone } also there is a model Topics { title, description } Each specialist can be experienced in different set of topics. There is a many to many relation via an extra Model TopicsSpecialists { specId, topicId } Standard Django admin allows me to create specialists and topics. Aslo to make it convenient i've provided Inline class TopicsInline(admin.TabularInline): extra = 1 model = Topics and passed it as in admin registration class SpecialistAdmin(admin.ModelAdmin): inlines = [TopicsInline,] Now list of extra fields were added to my Specialist creation form. It works well, but to make it more sense I would like to have a chance to have a set of checkboxes for each user to select topics instead of drop downs (as i have now). But would not add a bunch of bool fields into DB, just convert checkboxes to set of references before save specialist into DB There should be the way to customize model creation form. If … -
ManagementForm data is missing or has been tampered with for nested forms
I have the following Forms defined in my forms.py class MachineryGroupForm(ModelForm): class Meta: model = MachineryGroup fields = '__all__' class MachineryPartForm(ModelForm): class Meta: model = MachineryPart fields= '__all__' The following is the corresponding UpdateView: class MachineryGroupUpdate(UpdateView): model = MachineryGroup template_name = 'procman/machinerygroup_form.html' form_class = MachineryGroupForm success_url = 'machinery_group_list' MachineryPartFormSet = inlineformset_factory(MachineryGroup, MachineryPart, fields='__all__') def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data['parts'] = self.MachineryPartFormSet(self.request.POST, instance = self.object) else: data['parts'] = self.MachineryPartFormSet(instance = self.object) return data And Below is the template used to render the form: <h1>Machine Group</h1> <form method="post"> {% with named_formsets.MachineryPartFormFormSet as formset %} {{ formset.management_form }} {% csrf_token %} <table> {{ form.as_table }} {% if parts %} <table style="border-collapse: collapse; width: 100%;" border="1"> <br><br> <tbody> <thead> <td style="width: 14.2857%;">Group Code</td> <td style="width: 14.2857%;">Group Name</td> <td style="width: 14.2857%;"></td> <td style="width: 14.2857%;"></td> </thead> {% for part in parts %} <tr> <td style="">{{part.part_name}}</td> <td style="">{{part.part_number}}</td> <td style="width: 14.2857%;"><a href="#"> Edit</a></td> <td style="width: 14.2857%;"><a href="#"> Delete </a></td> </tr> {% endfor %} </tbody> </table> {% endif %}<br><br> </table> <br><br><input type="submit" value="Save"> {% endwith %} </form> I have tried every permutaion using {{formset}}, {{MachineryPartFormSet}} and also the last one using the with tags, but I am still getting the error: ['ManagementForm data is missing … -
Want to share backup file in Django web container with Postgres database container: How to?
I have a Django app on Docker with web container where automatics backups are stored and another postgresql database container. I want to be able to restore postgresql database using \i 'path\to\backup.psql' in a psql shell but it failed because file is not found db_preprod=# \i '/usr/src/app/backup/backup_2021-01-19_1336.psql' /usr/src/app/backup/backup_2021-01-19_1336.psql: No such file or directory I also tryed to copy with docker cp but not works: docker cp web:/usr/src/ap/backup/backup_2021-01-19_1336.psql db:/. copying between containers is not supported docker-compose version: '3.7' services: web: restart: always container_name: web build: context: ./app dockerfile: Dockerfile.preprod restart: always command: gunicorn core.wsgi:application --bind 0.0.0.0:8000 volumes: - ./app:/usr/src/app - static_volume:/usr/src/app/static - media_volume:/usr/src/app/media expose: - 8000 env_file: - ./.env.preprod depends_on: - db - redis healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8000/"] interval: 30s timeout: 10s retries: 50 db: container_name: db image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.preprod.db nginx: container_name: nginx build: ./nginx restart: always volumes: - static_volume:/usr/src/app/static - media_volume:/usr/src/app/media ports: - 1340:80 depends_on: web: condition: service_healthy volumes: postgres_data: static_volume: media_volume: -
Djano recursive SubQuery
I'm tring to implement a query including a recursive function. I have in one hierarchical structure, i.e. every organisation has a head organisation which has also a head organisation and now I want to get the (head) organisation with level 3 of a given (sub) organisation. The corresponding model looks like this: class OrganisationHierarchy(TimeStampMixin): id = models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID') level = models.ForeignKey(OrgaLevel, on_delete=models.PROTECT, null=True, blank=True) name = models.CharField(max_length=60, blank=True) zip_code = models.ForeignKey(ZipCode, on_delete=models.PROTECT, null=True, blank=True) parent = models.ForeignKey('self', null=True, on_delete=models.PROTECT, related_name='organisationhierarchy', blank=True) The query below works except getting the head organisation. I have written a separate method for this, but I don't know how to get the current organisation into this value, i.e when doing head_organisation=get_head_organisation_name(F('organisation')) then the method receives F('organisation') and not the value of organisation class EventGeneralSerializer(serializers.ModelSerializer): locations = serializers.SerializerMethodField('get_locations') class Meta: model = Event fields = ( 'locations', ) def get_head_organisation_name(self, organisation): if organisation.level_id > 3: return self.get_head_organisation_name(organisation.parent) elif organisation.level_id < 3: raise Exception("To low value") else: return organisation.name def get_locations(self, obj): result = obj.registration_set.values('organisation__name').annotate( participants=Coalesce(Sum('participantgroup__number_of_persons'), 0) + Coalesce(Count('participantpersonal'), 0), head_organisation=F('organisation__parent__parent__name')) \ <-- Insert recursive method here .values('organisation__name', 'participants', 'head_organisation', lon=F('organisation__zip_code__lon'), lat=F('organisation__zip_code__lat'), ) return result So thanks for your help in advance! -
Django REST API followers system
I'm trying to make a rest API for a blog app using Django-rest-framework. I'm a beginner and it's hard for me to understand how to implement that system. I made an intermediary model for making connections between followers and followings and serializers for users. But my API showing absolutely wrong following and followers for each user and endpoints for following and unfollowing not working also. Models.py: class UserFollowing(models.Model): class Meta: constraints= [ models.UniqueConstraint(fields=['user_id', 'following_user_id'], name='unique_following') ] ordering = ['-created'] user_id = models.ForeignKey('auth.User', related_name='following', on_delete=models.SET_NULL, null=True,blank=True) following_user_id = models.ForeignKey('auth.User', related_name='followers', on_delete=models.SET_NULL, null=True,blank=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user_id} is following {self.following_user_id}' serializers.py: class UserSerializer(serializers.HyperlinkedModelSerializer): following = serializers.HyperlinkedRelatedField(many=True, view_name='user-detail', read_only=True) followers = serializers.HyperlinkedRelatedField(many=True, view_name='user-detail', read_only=True) posts = serializers.HyperlinkedRelatedField(many=True, view_name='post-detail', read_only=True) class Meta: model = User fields = ['url', 'id', 'username', 'posts', 'following', 'followers'] def get_following(self, obj): return FollowingSerializer(obj.following.all(), many=True).data def get_followers(self, obj): return FollowersSerializer(obj.followers.all(), many=True).data class UserFollowingSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UserFollowing fields = '__all__' class FollowingSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UserFollowing fields = ['id', 'following_user_id', 'created'] class FollowersSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UserFollowing fields = ['id', 'user_id', 'created'] views.py: class UserViewSet(viewsets.ReadOnlyModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class UserFollowingViewSet(viewsets.ModelViewSet): queryset = UserFollowing.objects.all() serializer_class = UserFollowingSerializer class UserFollow(APIView): """ Retrieve, update … -
Django nested regroup
I use Django 2.2.12 I have three models: RiskRating is pointing to RiskType which is pointing to RiskCategory with ForeignKeys. class RiskCategory(models.Model): name = models.CharField(max_length=400, blank=True) class RiskType(models.Model): riskcategory = models.ForeignKey(RiskCategory, on_delete=models.CASCADE, related_name="risksforcategory") class RiskRating(models.Model): risktype = models.ForeignKey(RiskType, on_delete=models.CASCADE, related_name="ratingsforrisk") In my view: riskratings = Riskrating.objects.all() I would like to display RiskRating grouped by RiskCategories, i.e. I would like to do a nested regroup as following: {% regroup riskratings by risktype.riskcategory as ratingsbycategory %} How can I do that ? Thanks a lot