Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: Take table name as input from user and show the content of the table from database
I am trying to implement form in django, where I will take input from user, e.g, its table name and then I want to show all the content on the webpage. So, far I tried below code. views.py from django.shortcuts import render # Create your views here. from django.shortcuts import HttpResponse from .models import my_custom_sql from django.core.exceptions import * def index(request): return render(request, 'forms_spy/form.html') def search(request): if request.method == 'POST': search_id = request.POST.get('textfield', None) try: user = my_custom_sql.objects.get(name = search_id) #do something with user html = ("<H1>%s</H1>", user) return HttpResponse(html) except Person.DoesNotExist: return HttpResponse("no such user") else: return render(request, 'forms_spy/form.html') forms_spy/models.py from django.db import models # Create your models here. def my_custom_sql(TABLE): with connections["my_oracle"].cursor() as cursor: cursor.execute("SELECT * FROM {};".format(TABLE)) row = cursor.fetchall() return row templates/forms_spy/form.html <form method="POST" action="/search"> {% csrf_token %} <input type="text" name="textfield"> <button type="submit">Upload text</button> </form> urls.py under project folder: from django.contrib import admin from django.urls import path from django.conf.urls import url,include from forms_spy.views import * urlpatterns = [ # url(r'^$', views.index, name='index'), #url(r'^', include('livefleet.urls', namespace='livefleet')), path('admin/', admin.site.urls), url(r'^search/', search), url(r'^index/', index), ] I referred to this link. When I entered the value getting below error. RuntimeError at /search You called this URL via POST, but the … -
Loop over related model's children in Django template
I have a model for a company. Then I have a base model for company posts. It contains common posts attributes. An attribute is the company that publishes the posts. It refers to the Company model with a ForeignKey. Finally I have a child model (based on the CompanyPost base model) for posts of type A: class Company(models.Model): name = models.CharField(...) ... class CompanyPost(models.Model): company = models.ForeignKey(Company,...) ... class PostA(CompanyPost): name = ... In a template I want to loop over posts of type A published by a specific company. I tried these variants: 1) {% for postA in company.companyposts_set.all.postA_set.all %} ... 2) {% for companyposts in company.companypost_set.all %} {% for postA in companyposts.postA_set.all %} ... {% endfor %}{% endfor %} I tried other sub-variants of the above. None seems to work. I know that I can easily prepare the set in the view, like: postsA = PostA.objects.filter(company__pk=pk) And pass postsA to the template context, but I'm wondering whether there is a way to loop over related models' children in the template. (note: looping over companyposts works. But I get of course all types of posts, like postB etc.: {% for post in company.companypost_set.all %} That is why I tried … -
In django how to model an invoice which can have multiple items?
I am using Django Rest Framework in the backend and Angular for frontend. If the customer order multiple items, it should be be in a single invoice. For example, if the customer order apple, orange and banana, all these should be in a single invoice. When the customer order again and it will be a new invoice. class InvoiceItem(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name='invoiceitems') customer = models.ForeignKey( Customer, on_delete=models.CASCADE, related_name='invoiceitems') quantity = models.PositiveIntegerField() date = models.DateTimeField(auto_now_add=True) class Invoice(models.Model): invoice_item = models.OneToOneField( InvoiceItem, on_delete=models.CASCADE, related_name='invoice') Now I have to link the InvoiceItem with Invoice. I thought about using post_save signals with InvoiceItem as a sender to create Invoice object and link it with the InvoiceItem. @receiver(signals.post_save, sender=InvoiceItem) def create_account(sender, instance, created, **kwargs): Invoice.objects.update_or_create(invoice_item=instance) How can I do it for multiple items? Or there is a better way to implement my requirements? -
Make sqlite query to update to inner join table after a new entry
I have a backend API in DJRF with three tables in the database where one of them is a mix of the other two. How do I have the inner join table update after there is a new entry in one of the other two tables? EX: I have a HTTP request to the API which then creates a new entry, which then should update the joined table and then a final request will be made to retrieve the new data from it for the frontend. -
HTTP status code 400 while trying to send data from angular to REST API
Can any one help me with this 400 bad request? I wanted to send a form data to rest api from angular and I'm getting the http 400 response due to which my data is not sent to the back end. HTML and JS code using angular CDN {% load staticfiles %} <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script> <!-- using angular with CDN --> <script> var app = angular.module('kanbanForm', []); /* creating a new angular module*/ app.controller('CardsController', ['$scope', '$http', CardsController]); function CardsController($scope, $http) { $scope.submit=true; $scope.JiraNum = null; $scope.Reporter = null; $scope.Assignee = null; $scope.Summary = null; $scope.Description = null; $scope.StoryPoints = null; //create new user... $scope.createJira = function(jnumber, jreporter, jassignee, jsummary, jdescription, jstoryPoints) { var data = { JiraNum: jnumber, Reporter: jreporter, Assignee: jassignee, Summary: jsummary, Description: jdescription, StoryPoints: jstoryPoints }; //posting data to server... $http({ method: 'POST', url: '/kanban/cards/', data: data, }).then(function successCallback(response) { $scope.users.push(response.data); alert("User has created Successfully") }, function errorCallback(response) { alert("Error. while creating user, Try Again!" + JSON.stringify(response)); }); }; } </script> </head> <body ng-app="kanbanForm" ng-cloak> {% verbatim %} <div ng-controller="CardsController"> <form ng-submit="createJira(number, reporter, assignee, summary, description, storyPoints)"> <h4>Enter the details to create a new JIRA</h4><br> <label>JIRA number: </label> <input type="text" ng-model="number"/><br> <label>Reporter: </label> <input type="text" ng-model="reporter"/><br> … -
Django Formset non_form_errors not appearing into template
on Shell its working fine >> formset.non_field_errors() ['Some error.'] but in below case its not working in Django Template. {% if formset.non_field_errors %} <div class="alert alert-danger" role="alert"> {% for error in formset.non_field_errors %} {{ error }} {% endfor %} </div> {% endif %} this below code is also not displaying any error in Django Template. {{formset.non_field_errors}} Can someone please help me out. is there anything I am missing on template to display error message related to non_field_errors -
local variable 'form' referenced before assignment in python
this code always show me error local variable 'form' referenced before assignment https://i.stack.imgur.com/KlYRu.jpg -
i get the first result only of the for loop in my views
i have a PositiveIntegerField in a model, in which i need to loop through that model to check all the values of this field and get its results to use it in my views.. The Problem is when i did that i just get the value of the first row in the database only! models.py class RoomType(models.Model): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE) room_type = models.ForeignKey(RoomTypesNames, on_delete=models.CASCADE) room_capacity = models.PositiveIntegerField() ## Thats the field i wanna check its value views.py def SearchHotels(request): x = None z = None t = None if request.method == 'GET': destination = request.GET.get('cityHotels') numAdultStr = request.GET.get('numAdult') numChild = request.GET.get('numChild') numAdult = int(numAdultStr) if destination: q_city2 = Q(hotel__city__name__icontains = destination) rooms2 = RoomType.objects.filter(q_city2) ################################ ### next is my question: if rooms2: for r in rooms2: if r.room_capacity < numAdult and numAdult % r.room_capacity == 0: x = numAdult / r.room_capacity ### i want to loop through this query and check the values of 'room_capacity' in all models, but i only get the result of only the first row in my database -
How to dynamically specify fields for nested serialization
When working with Django rest-framework, and object relationships, i often encounter situations in which i want to return different fields from a serializer depending on the context in which i'm calling that serializier. To provide an example, lets say i have some models representing artiste and album class Artiste(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=30) songs = models.ManyToManyField(Song, related_name='artiste') albums = models.ManyToManyField(Album, related_name='artiste') class Album(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=30) description = models.TextField(blank=True, null=True) These models being serialized by these serializers, which include field from the many to many relationship class AlbumSerializer(serializers.ModelSerializer): artiste = ArtisteSerializer(many=True) class Meta: model = Album fields = ('id','title','description','artiste') class ArtisteSerializer(serializers.ModelSerializer): class Meta: model = Artiste fields = ('id', 'name', 'albums') A request to my album endpoint might produce an object like this "id": "5807bd12-254f-4508-b76f-02dc0740e809", "title": "Test", "description": "", "artiste": [ { "id": "31f09ef0-50ce-48b1-96a6-a6c234930ce5", "name": "Alec Benjamin", "albums": [ "5807bd12-254f-4508-b76f-02dc0740e809" ] } ] As you can see, using nested serialization ends up giving me more information that i actually want in this context. Given that i had more data for example, when looking at the information for an artiste, i'd love to have the information regarding all the albums that the … -
How to make my navigation bar work in Django?
I am working on a school project, I have to submit it in next two days. I have created a simple website using django, html, css and python. Everything is working fine but my navigation bar is not working. I am getting this error: The error I am getting. This is my code below: prodj/urls.py: from django.contrib import admin from django.urls import path , include urlpatterns = [ path('',include('app1.urls')), path('morse',include('morse.urls')), path('binary',include('binary.urls')), path('ascii',include('ascii_con.urls')), path('admin/', admin.site.urls), ] This is my homepage : My homepage pic Only problem is that my navigation bar is not working, it shows the error mentioned in above image. Please help me as I need submit my project in next two days !! Thank you very much in advance. -
How can I maintain Django database entries after making migrations and pushing changes to Git?
I have constructed essentially a blog in Django, where various users can input Articles to the blog I host on a remote server. However, if I change any of the model 'Article' field attributes (and therefore update migrations) and push them to Git with "git commit -m" and "git push -u origin master" I notice that any of the blog posts made prior to this commit vanish from the webpage. I would like it to be, that when I make changes in the Python code that constitutes my Django project, pushing through these changes doesn't delete blog posts each time. My Article model looks as follows: class Article(models.Model): title = models.CharField(max_length=255) #Body is the "body" of our entry - self explanatory. body = models.TextField() #date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) entry_date_time = models.DateTimeField(default=timezone.now) Whenever I update through Git though, all the old 'articles' published on my blog disappear. How can I either a) prevent that, or b) circumvent that? I appreciate any and all help / solutions, thank you. -
Amcharts to group Pie chart data by range
I have a set of data, marks obtained by students. My aim is to diplay a pie/bar chart with range category, like marks between 90-100, 80-90, 70-80, 60-70, 50-60, and <50. I am passing Data from python Django to html, which will display the data as a pie chart/ bar chart with those ranges. One way to do is to populate the data range wise in python using if conditions. etc and then feed the charts which is straight forward. Is there any way to automatically create range in python/in amcharts using pie/column/bar? Like I just have to pass the marks and number of students in each mark and then the am chart plugin will automatically group it with the interval we specify? -
django rest api doest not retrive data from my database
i am trying to retrieve data from my django database using django rest framework but my api view showa no data. models.py class shop(models.Model): spname = models.CharField(max_length=150, default=" ") spownm = models.CharField(max_length=100, default=" ") mob = models.BigIntegerField(blank=False, null=False, unique=True) city = models.CharField(max_length=255) location = models.PointField(srid=4326) objects = GeoManager() views.py class shoplist(viewsets.ModelViewSet): queryset = shop.objects.all() serializer_class = shopSerializers serializers.py class shopSerializers(serializers.ModelSerializer): class Meta: model = shop fields = ('spname', 'spownm', 'mob', 'location') urls.py router = routers.DefaultRouter() router.register(r'^', views.shoplist) urlpatterns = [ url(r'^categories/(?P<Catg_id>[0-9])/(?P<Type_id>[0-9]+)/shops/', include(router.urls)), ] my result with above api is HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept {} it shows no data while i expect it to list the items in database. -
Firebase python admin sdk isNewUser ()
Hi i'm currently using firebase admin sdk on my django server to handle my app. I would like to check if user a user first time login on the server side.I would like to use firebase isNewUser() on the django server but in the firebase admin sdk docs i don't see any information related to that. My server side to get user from token(send from app): from utils.firebase_utils import auth class FirebaseAuthentication(authentication.BaseAuthentication): def authenticate(self, request): token = request.META['HTTP_AUTHORIZATION'] if not token: return None try: decoded_token = auth.verify_id_token(token) uid = decoded_token['uid'] user = auth.get_user(uid, app=None) # need to check if user first time log in too except Exception as e: raise exceptions.AuthenticationFailed('No such user') return (user, None) # authentication successful How can i check if a user first time login? -
Getting an Unable to get repr for <class 'notifications.models.NotificationQuerySet'> for Django-notifications connected with an Postgres database
I am stuck with this problem for quite some time now without any idea what's causing it. I have implemented a realtime notification system for my Django application. I used Django-notifications library to implement it. It shows the unread count and and unread notifications as a dropdown list from the navbar. Previously I was using sqlite3 database but now I have moved on to PostgreSQL. The migration was smooth. I can see all the tables and data's being saved in database. Even the Notification Model is the database.But Recently I am facing a problem which is the following, [18/Dec/2019 09:54:22] "GET /api/unread_list/?max=20 HTTP/1.1" 500 64565 Internal Server Error: /api/unread_list/ Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/site-packages/notifications/views.py", line 173, in live_unread_notification_list struct['actor'] = str(notification.actor) TypeError: str returned non-string (type NoneType) [ Now when I started to debug the notifications view.py method for live_unread_notification list function I found that its facing a 'Getting an Unable to get repr for ' problem whenever its trying to fetch some data from the database. Also … -
The included URLconf 'simplesocial.urls' does not appear to have any patterns in it. ...circular import
Unable to locate the source of the above error: I've review the below link and the provided solutions have not resolved my issue: Django - Circular model import issue The following urls seems to cause the circular import error to appear. When commented out, the error does not appear. simplesocial/urls.py urlpatterns = [ url(r"^$", views.HomePage.as_view(), name="home"), url(r"^test/$", views.TestPage.as_view(), name="test"), url(r"^thanks/$", views.ThanksPage.as_view(), name="thanks"), url(r"^admin/", admin.site.urls), url(r"^accounts/", include("accounts.urls", namespace="accounts")), #causes circular reference url(r"^accounts/", include("django.contrib.auth.urls")), # causes circular reference url(r"^posts/", include("posts.urls", namespace="posts")), # causes circular reference url(r"^groups/",include("groups.urls",namespace="groups")), accounts/urls.py from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ url(r"^$", views.LoginView.as_view(), name="login"), #works, review #url(r"^login/$",accounts.views.LoginView,name="login"),#additional url pattern. test. #url(r"^$", views.LoginView.as_view(template_name="accounts/login.html"), name="login"),#test. does this work?? url(r"login/$", auth_views.LoginView.as_view(template_name="accounts/login.html")), url(r"logout/$", auth_views.LogoutView.as_view(), name="logout"), url(r"signup/$", views.SignUp.as_view(), name="signup"), ] groups/urls.py from django.conf.urls import url from . import views app_name = 'groups' urlpatterns = [ url(r"^$", views.ListGroups.as_view(), name="all"), url(r"^new/$", views.CreateGroup.as_view(), name="create"), url(r"^posts/in/(?P<slug>[-\w]+)/$",views.SingleGroup.as_view(),name="single"), url(r"join/(?P<slug>[-\w]+)/$",views.JoinGroup.as_view(),name="join"), url(r"leave/(?P<slug>[-\w]+)/$",views.LeaveGroup.as_view(),name="leave"), ] posts/urls.py from django.conf.urls import url from . import views app_name='posts' urlpatterns = [ url(r"^$", views.PostList.as_view(), name="all"), url(r"new/$", views.CreatePost.as_view(), name="create"), url(r"by/(?P<username>[-\w]+)/$",views.UserPosts.as_view(),name="for_user"), url(r"by/(?P<username>[-\w]+)/(?P<pk>\d+)/$",views.PostDetail.as_view(),name="single"), url(r"delete/(?P<pk>\d+)/$",views.DeletePost.as_view(),name="delete"), ] However, when commenting out the following 3lines from the simplesocial/urls.py file. The following error is returned: "NoReverseMatch at / 'accounts' is not a … -
how to save the sortable div in html
so i have a html page called campaign prioritation , that use a sortableJS to sort what campaign is important first .. it really works that i can sort the sortableJS but i cant save it to the page , so when i refresh it , it will back to normal(not the one with the campaign that already sorted how to do it? html <style> .sortable-ghost { opacity: .6; } section, a, a:visited { color: #005FAF; text-decoration: none; display: block; margin: 10px 0; } a:hover { text-decoration: none; } #loadMore { padding: 10px; text-align: center; background-color: #005FAF; color: #fff; border-width: 0 1px 1px 0; border-style: solid; border-color: #fff; box-shadow: 0 1px 1px #ccc; transition: all 600ms ease-in-out; -webkit-transition: all 600ms ease-in-out; -moz-transition: all 600ms ease-in-out; -o-transition: all 600ms ease-in-out; } #loadMore:hover { background-color: #fff; color: #005FAF; } </style> <section id="main-content"> <section class="wrapper"> <h3><i class="fa fa-angle-right"></i> Campaign Prioritation</h3> <!-- page start--> <ul id="campaignPrio" style="list-style: none;padding: 0;"> {% for table in obj2 %} <li style="background: white;margin: 10px 5px;padding: 5px 10px; color: #005FAF">{{table}}</li> {% endfor %} </ul> <a href="#" id="loadMore">Load More</a> <!-- page end--> </section> <!-- /wrapper --> </section> <!-- /MAIN CONTENT --> <!--main content end--> <!--footer start--> <footer class="site-footer"> <div class="text-center"> <p> … -
Django - Generate Edit form based on selected drop down option
I have recently starting learning Django and trying to built a simple edit form based on the value selected from the dropdown list. This dropdown list is populated from the backend database column 'student_first_name' from the Students Model. When a particular student_first_name is selected and submitted, an edit form with all the details of the student should be generated in the same template for editing purpose. In that, only the student_id field should be read only. I am able to generate the dropdown list and get the 'student_id' value in the selected_item variable. But I am not able to understand on how to use this to generate an edit form. Also is there any other better way to achieve this? This is my first draft of the code so any suggestions would be really appreciated. models.py class Students(models.Model): student_id = models.IntegerField(primary_key=True) student_first_name = models.CharField(max_length=100, null=True) student_last_name = models.CharField(max_length=100, null=True) student_address = models.CharField(max_length=255, null=True) student_dob = models.DateTimeField(null=True) student_doa = models.DateTimeField(null=True) views.py def student_edit(request): details = Students.objects.all() form = request.POST if request.method == 'POST': selected_item = get_object_or_404(Students, pk=request.POST.get('student_id')).student_id return render(request, 'student_edit.html', {'details': details}) student_edit.html <form method="POST" novalidate> {% csrf_token %} <select name="student_id" class="form-control"> <option value="">Select Student Name</option> {% for detail in details … -
How can I build a Django-webapp using Jenkins?
I want to know how to build a django webapp using jenkins. What should be done while configuring a new job in jenkins. Can the django webapp be built into a .war file which can be deployed in a container. How can I build a CI pipeline for the django app using jenkins. A step by step guide would be appreciated. -
Sending events using django-eventstream from external scripts
I recently started looking at django_eventstream to push data to a webpage instead of the client polling for updates. I ran django_eventstream's time example, that was ok. I then configured my project to use events (asgi.py, routing.py, etc) and got one of my app's view.py to push an event to the web page. That worked, at least in testserver mode, so all seems configured ok. Now what I'd like to do is run a script external to the Django project and send events from there, for example, import os import django from django_eventstream import send_event os.environ['DJANGO_SETTINGS_MODULE'] = 'my_project.settings django.setup() # ...some script logic send_event('my_channel', 'message', 'my_message_content') This results in the event being stored in the project's django_eventstream_event database table, but I never see it get pushed to the webpage. Wireshark shows the other web traffic but not the externally generated send_event messages. My question is what is different about using send_event() within view.py versus in another script that may not be integral to the Django project? The external script does go through the django_setup() configuration process. Using Python 3.7.3, Django 2.2.5, django_eventstream 2.6.0 -
Django - why cant i retrieve user name?
When i log in an user, and attempt to retrieve the username or any details i get the below error. Not sure what it really does mean? def loginview(request): message=[] if request.method=='POST': if Loginform(request.POST).is_valid(): login_form=Loginform(request.POST) loginuser=authenticate(username=request.POST['email'],password=request.POST['password']) if loginuser is not None: login(request,loginuser) print("attempted log in") uname=User.username print(User.get_full_name) return render(request,'payrequest/templates/landing.html',{'landing_content':'Well done, you are loged in as'+ str(User.get_username)}) else: return render(request,'payrequest/templates/landing.html',{'landing_content':'Incorrect details, try again.','okurl':'login'}) else: message.append("We had some difficulties processing your request, please try again. If the issue persists please contact the systems team.") return render(request,'payrequest/templates/landing.html',{'landing_content':'invalid data','okurl':'login'}) else: login_form=Loginform() return render(request,'payrequest/templates/login.html',{'form':login_form}) Console prints: <function AbstractUser.get_full_name at 0x04560BB0> -
How to resolve value error in my views file
Can anyone please help me solve this problem in my view. I have been stuck for quite a time now. Any help will be highly appreciated. My Error System check identified no issues (0 silenced). December 18, 2019 - 09:28:36 Django version 2.2.8, using settings 'Timesheet.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [18/Dec/2019 09:28:42] "GET / HTTP/1.1" 200 6027 Internal Server Error: / Traceback (most recent call last): File "D:\Django\TimeSheetProject\morabu\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\Django\TimeSheetProject\morabu\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response "returned None instead." % (callback.__module__, view_name) ValueError: The view morabu_timesheet.views.create_timesheet_view didn't return an HttpResponse object. It returned None instead. [18/Dec/2019 09:29:02] "POST / HTTP/1.1" 500 65059 My views.py And I don't know whether my method is correct or not but I want to save the data from the raw HTML form only since I have to do some front end validation using java script. from django.shortcuts import render from .models import TimesheetDetails # Create your views here. def create_timesheet_view(request): if request.method=="POST": if(request.POST.get('dateToday') and request.POST.get('dayToday') and request.POST.get('startTime') and request.POST.get('endTime')and request.POST.get('breakTime')and request.POST.get('normalTime') and request.POST.get('overTime')and request.POST.get('holidayTime')and request.POST.get('weekType') and request.POST.get('attendance')and request.POST.get('content')): post = TimesheetDetails() post.date = request.POST.get('dateToday') post.day = request.POST.get('day_today') post.startTime = request.POST.get('startTime') post.endTime = request.POST.get('endTime') post.breakTime … -
Annotate with a static date - Django
I'm trying to annotate a queryset with a static date in Django. With an integer (instead of a date) it works: from django.db.models import Value, IntegerField cars= Car.objects.all().annotate(sales=Value(0, IntegerField())) How can I make it works with date?? from django.db.models import Value, DateField cars= Car.objects.all().annotate(mydate=Value('2019-01-01', DateField())) -
Django: Can we enforce POST request in DRF without requiring csrftoken?
I am implementing a post commenting mechanism in DRF using ListCreateAPIView. Using ReactJS, I wanna allow anonymous visitors to comment on a post. I am able to do so only when the csrftoken is available (which means a user must be logged in for the csrftoken to be available). But I wanna enforce commenting for unauthenticated users/anonymous site visitors. Do you guys know any way to do this, maybe without requiring csrftoken. Or if the token is really needed, is there any way to generate it without relying on Django's authentication process? I'm knew to Django I badly need direction for this feature I'm developing. Thanks a heap! -
How to resolve an m-to-n relationship with additional data in django with graphene
Greeting! I'm new to Django an Graphene. I have the following m-to-n relationship between Course and User through a Participation that holds additional information: class Course(models.Model): participants = models.ManyToManyField(get_user_model(), through='Participation') class Participation(models.Model): COURSE_ROLE = [(0, "student"),(1, "mentor"),(2, "tutor"),(3, "owner")] course = models.ForeignKey('exquizit.Course', on_delete=models.CASCADE) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) course_role = models.SmallIntegerField(choices=COURSE_ROLE) class User(AbstractBaseUser): first_name = models.CharField(max_length=100, blank=False) last_name = models.CharField(max_length=100, blank=False) I want to write a query to load the participants of the of a given course (by id). I want to write it in a manner that essentially the user is returned but extended by the course_role property of Participation. I know that I can get a result close to this by class ParticipantType(DjangoObjectType): course_role = graphene.Int() user = graphene.Field(User) but this will result into { user: {firstName: "Alice", lastName: "Anderson"}, course_role: 1 } when i really want { participant: {firstName: "Alice", lastName: "Anderson", course_role: 1} } If possible, please provide ParticipantType and the query-resolver! Thanks in regard for any answers or tips!