Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
best way to integrate 2checkout with django
I know(maybe) it's silly question, but just sucked in to it. I'm building an eCommerce website using django, where i need to use 2checkout payment gateway, i'm wondering if there is a package, tutorials or anything that helps me(almost 3days searching about.. I've no idea if it's possible) :| -
How to determine the type of a querset in django
How can I check to know the 'TYPE' of my database queryset. I want to use an 'IF' statement to do something when a certain condition is met but I don't know how to go about it. def tot_query(request): fb = Fblink.objects.all() tw = Twlink.objects.all() yt = Ytlink.objects.all() th = Thlink.objects.all() ig = Iglink.objects.all() sc = Sclink.objects.all() tk = Tklink.objects.all() query = chain(fb, tw, yt, th, ig, sc, tk) print(type(list(query)[0])) if type(list(query)[0]) == 'src.link.models.Fblink': print("This is a facebook link") The first print statement prints the following <class 'src.link.models.Fblink'> and the second and one prints nothing. -
How to display Logs of Django middleware in terminal
I created my own Middleware to validate HTTP-Requests. To make sure everything works fine, I added some logs into the code. I excpect that they will be display in the terminal (if reached obviously). import logging LOG = logging.getLogger(__name__) class ValidationMiddleware: # init-Method is called once the server starts def __init__(self, get_response): self.get_response = get_response # call-Method is called for every new request to the Django application def __call__(self, request): # Code to be executed before middleware is called validate_settings = settings.VALIDATIONMIDDLEWARE.get("default") token_header = 'X-Token' if token_header in request.headers: request_token = request.headers[token_header] url = validate_settings.get("VALIDATE_URL") md5_token = hashlib.md5(request_token.encode('utf-8')).hexdigest() payload = {'checksum': md5_token} LOG.info("Calling" + url + " to validate token.") req = requests.post(url, json=payload) result = req.json() if result['result'] is False: LOG.info("Token not valid anymore.") raise PermissionDenied else: LOG.info("Big Error") requests.HTTPError() response = self.get_response(request) return response I start my django server and did some Post requests (created users via admin, login, etc.), but none of the Logs in the code was displayed in the terminal. Why? -
Django ORM convert month name to date
I want to convert a month name (stored as CharField) to a DateField using the Django ORM. For example, if I have July in the database, then I want it to return as 07/01/2021 The way I have done it before without Django ORM is like this: dt.datetime.strptime(MONTH_NME + ', 01, ' + str(dt.datetime.now().year), '%B, %d, %Y') However, I would perfer to use the Django ORM, but am unable to get my head around how to do this. Here is what I have so far: QS = MyModel.objects.all().Annotate( review_dte = dt.datetime.strptime(F('MONTH_NME') + ', 01, ' + str(dt.datetime.now().year), '%B, %d, %Y') ) Any help would be appreciated! -
Django ORM: how do I count objects that have the same properties?
I want to use the Django ORM to find instances in my models that have some of the same properties. For instance, given this model: class Person(Model): name = CharField() age = IntegerField() gender = CharField() how can I find all persons that don't have a unique age and gender? For instance given the following data: John 20 M Bob 21 M Diana 20 F Janet 20 F I want a query that would return Diana and Janet. Thanks! -
Why does one user can add only one record in form in django?
I have created form, in which users can add some kind of information. But, I noticed that one user can add only one object. I mean, after secod time of filling out a form, new infermation displayed, but old record was deleted. models.py: from django.db import models from django.contrib.auth.models import User class File(models.Model): customer = models.ForeignKey(User, on_delete=models.CASCADE, null=True) graf_title = models.CharField('Название файла', max_length = 200) chart = models.TextField('Значения осей') title = models.CharField('Название Графика', max_length = 50) x_title = models.CharField('Название Оси Х', max_length = 50) y_title = models.CharField('Название Оси Y', max_length = 50) forms.py: from .models import File from django import forms class FileForm(ModelForm): class Meta: model = File fields = '__all__' exclude = ['customer'] views.py: #It is the form view def main(request): error = '' customer = File.objects.get(customer=request.user) formset = FileForm(request.POST) if request.method == 'POST': formset = FileForm(request.POST, instance=customer) if formset.is_valid(): formset.save() return redirect('grafic:list') else: error = 'Форма была неверной(' formset = FileForm() data = { 'form': formset, 'error': error, } return render(request, 'graf/first.html', data) #list is the view, which show all user's records def list(request): record= File.objects.filter(customer=request.user) return render(request, 'graf/list.html', {'record': record}) SO as I said, when one user fills out form more than one time, in the list … -
Run ansible playbook after changing host file and vars
I am referencing ansible playbook to create some VMs from django, and dynamically change host file and extra vars in ansible based on user submitted form. Now it is stuck on the implementation of the race condition for the host file and extra vars, say 2 users are modifying them at the same time, so I use lock for the modification in a celery task, however, when the 1st user changed the files and run playbook using his own variables and host files. The 2nd user is doing the change as well, my question is whether the 2nd user changing the files(host and vars) will cause the 1st to run the playbook abnormally? Thanks. -
Django - can't update existing data in database, doesn't update
I have an authenticated user with related data, such as a file which the user uploaded and a description and ID number associated with the user. (The user previously used a Document model and associated form to upload the original info. This is working fine. Now I have an EditForm which I want to use to update the user ID and description, but when I call save, it doesn't get updated. Here is the views and models. I can print to the console my new data as entered in the form, I'm just not saving it correctly. Thanks in advance. views.py: def edit(request): items = Document.objects.filter(created_by=request.user) for object in items: print(object.id_number,'original') # shows original data print(object.description,'original') # shows original data if request.method == 'POST': form = EditForm(request.POST, instance = request.user) if form.is_valid(): post = form.save(commit = False) post.description = form.cleaned_data['description'] post.id_number = form.cleaned_data['id_number'] print(post.id_number,'############') #shows form data as entered print(post.description,'!!!!!!!!!!!') #shows form data as entered post.save() else: return render(request, 'edit.html', {'form': form}) messages.info(request, 'Successfully Saved') return redirect('home') else: form = EditForm( instance = request.user) return render(request, 'edit.html',{ 'form':form, 'items':items }) Models.py from django.db import models from django.conf import settings # Create your models here. class Document(models.Model): description = models.CharField(max_length=255, blank=True) … -
Should I automatically update my Profile model on User updates?
I am wiring a Profile model to my User with a signal receiver that updates the Profile on User updates, but I'm not sure what is the drawback of dealing with the Profile update in my own code? My logic for posing this question is that I might want an user to exist without a profile, for example I don't want my admins to be associated with a credit card number nor I want the credit card number to be nullable. Is assigning a signal receiver from the User to a Profile model just a matter of convenience or is there some other interaction that would be difficult to manage otherwise? -
how to overwrite wagtail function?
i want to overwrite wagtail function i want to add a column in admin user page but i want to use # add column class SiteUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) note = models.TextField(verbose_name='note') this way to add column and i found wagtail is not allow to custom admin user view in wagtail/users/views/users.py so i want to overwrite function in users.py def index(request, *args): i want to edit it and change users column how i can do that? thanks for help~ -
Adding product variants into database with forms in Django
First of all I'm new to Django so I apologize in advance for wasting your time if I have any silly questions. I'm trying to create an e-commerce project in Django and need to add product variations into the database. What is the correct way doing this? I've come so far, but can't go any further. I appreciate if you can help. What I want to do: "Generate" button generates all the possible variations according to selection as html(Javascript). "Submit" button post the form Try to save variations to the database Error: SkuForm.variation_value1 is not an instance of VariationValuesModel. Variation Section ScreenShot FORM: class ProductsForm(forms.ModelForm): class Meta: model = ProductsModel fields = ['name',] class SkusForm(forms.ModelForm): variation_value1 = forms.ModelMultipleChoiceField(queryset=VariationValuesModel.objects.filter(variation_id=2).order_by("name"), required=False, widget=forms.SelectMultiple(attrs={ 'id' : 'var_color', 'class' : 'form-control selectpicker', 'title' : 'Select Color', })) variation_value2 = forms.ModelMultipleChoiceField(queryset=VariationValuesModel.objects.filter(variation_id=1).order_by("name"), required=False, widget=forms.SelectMultiple(attrs={ 'id' : 'var_size', 'class' : 'form-control selectpicker', 'title' : 'Select Size', })) variation_value3 = forms.ModelMultipleChoiceField(queryset=VariationValuesModel.objects.filter(variation_id=3).order_by("name"), required=False, widget=forms.SelectMultiple(attrs={ 'id' : 'var_pattern', 'class' : 'form-control selectpicker', 'title' : 'Select Pattern', })) class Meta: model = SkusModel fields = ['variation_value1', 'variation_value2', 'variation_value3',] MODEL: class ProductsModel(models.Model): name = models.CharField(max_length = 200, blank=False, null=False, class SkusModel(models.Model): product = models.ForeignKey(ProductsModel, related_name='product_sku', on_delete=models.DO_NOTHING) variation_value1 = models.ForeignKey(VariationValuesModel, related_name='VariationValue1_sku', blank=True, null=True, on_delete=models.DO_NOTHING) … -
Calling Model method inside template file
I am learning to create a blog website using django. I encountered an issue while calling my model method inside template file. The site is not displaying contents inside the body. It was working fine when i used article.body but its not working when i use article.snippet. models.py file:- ... from django.db import models class Article(models.Model): title = models.CharField(max_length = 100) slug = models.SlugField() body = models.TextField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def snippet(self): return self.body[:50] ... articles_list.html file:- ... <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Articles</title> </head> <body> <h1>Articles List</h1> <div class="articles"> {% for article in articles %} <div class="article"> <h2><a href="">{{article.title}}</a></h2> <p>{{article.body.snippet}}</p> <p>{{article.date}}</p> </div> {% endfor %} </div> </body> </html> ... views.py file:- ... from django.shortcuts import render from django.http import HttpResponse from .models import Article def articles_list(request): articles = Article.objects.all() return render(request, 'articles/articles_list.html', {'articles': articles}) ... There is no error displayed in code but still there is no output inside body tag. -
Algolia ranking edge cases
I am new to Algolia and Django so any help with the following task would be much appreciated. I am trying to re-rank the search results on the UI such that certain edge cases don't cause issues anymore. The problem was that initially there was only one searchable attribute that was used but we actually want that one to be split into 2. I did that so I split the initial attribute into 2 attributes, call them attribute_1 and attribute_2 and also passed them in the settings of the index.py file as follows: "searchableAttributes": [ "attribute_1", "attribute_2" ] From the documentation I understand that the order in which the attributes are added in the above lists prioritizes the search so the search engine will first look for matches in attribute_1 and then in attribute_2. This solved the issue for one of the edge cases but there is still one edge case that is not solved. I will explain the issue with this edge case below in more detail. Call the 2 examples that I want to be ranked for the remaining edge case E1 and E2. The search keyword, call it some_text, matches perfectly attribute_1 of E1 but it is … -
Perform action on saving inline django model
I have two models, one CommentModel displayed as an inline to the MainModel in the admin. models.py: class MainModel(models.Model): customer = models.OneToOneField(Customer, on_delete=models.CASCADE) class CommentModel(models.Model): main = models.ForeignKey(MainModel, on_delete=models.CASCADE, default=None) comment_german = CharField(blank=True, default='', null=True) comment_english = CharField(blank=True, default='', null=True) admin.py: class MainModelAdmin(SimpleHistoryAdmin): model = MainModel inlines = [CommentModelInline] class CommentModelInline(admin.StackedInline): model = CommentModel fields = ['comment_german', 'comment_english'] Suppose I want to automatically translate what the user writes in the comment_german field and save it to the comment_english field when the MainModel is saved. I tried overriding the save method. I successfully did it for another model which is not an inline. But this does not work for inlines. I need something like this: def save(self, *args, **kwargs): super().save(*args, **kwargs) for comment in CommentModel.objects.filter(main=self): if comment.comment_german != '' and comment.comment_english == '': comment.comment_english = comment.comment_german.translate_to_english() There must be a way to do this, maybe with a formset, but I can't wrap my head around it. -
Django Clear Sessions and Flags every 20 mins
I am working on a Django Website in which whenever a user logs in it creates a session and in Models active is set to true (is_active=true) when users logout the sessions clear and is_active=false for the user But the problem is when a User closes the tab/ browser instead of logging out user is still said to be active . How to make a function which will logout all active users after 15 mins of their login? Models.py class Employee(models.Model): emp_id = models.CharField(primary_key=True,max_length=50) name = models.CharField(max_length=50) gender = models.CharField(max_length=50,default="None") email = models.EmailField(max_length=50) password = models.CharField(max_length=50,help_text="Minimum of 8 Characters") dept = models.CharField(max_length=50) phone = models.CharField(max_length=20) last_login=models.DateTimeField(auto_now_add=True, blank=True) is_active=models.BooleanField(default=False) authcode=models.CharField(max_length=25) Views.py def home(request): loginUser= request.session['username'] if loginUser == '': return redirect('log') name= request.session['name'] return render(request,'home.html') def logot(request): loginUser=request.session['username'] Employee.objects.filter(emp_id=loginUser).update(is_active=False) request.session['name']=''; request.session['username']=''; return redirect('welcome') # def scheduled_logout # Logout all user's after 15 mins of last_login Thanks in advance -
Django migration : deleted column, now django says it doesn't exist
I want to get rid of a field of one of my models which has quite a few objects. This field was barely used so I removed every call to it from my code and did the migration. This migration couldn't be simpler, and it didn't cause any issue on my dev server. So I did the same on my running server. # Generated by Django 2.2.19 on 2021-06-22 12:29 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('my_app', '0010_auto_20210611_0751'), ] operations = [ migrations.RemoveField( model_name='permission', name='type', ), ] But when I try to access objects that relate to this model in my admin view, it throws psycopg2.errors.UndefinedColumn: column my_app_permission.type does not exist LINE 1: SELECT "my_app_permission"."id", "my_app_permission"... I don't understand why it looks for type when there is no reference to it in my code. I ran Django's manage.py shell and requested my Permission objects. I got them without any issue. I tried to access their type field, but it didn't exist as expected since the migration. Which means in the database the column "type" has been deleted as I asked. The error message doesn't give any insight as to what causes my error, it says the error … -
I cannot view my sqlite images in Django(uploaded to server-Plesk)
I made a site in Django and when i try to view the pages from the database i get the alt and not the image. File Structure Project -.venv -main -static (again here, only then does it seem to show static files) *settings.py *urls.py *wsgi.py ... -app ... *views.py *models.py *admin.py *apps.py ... -templates ... *offers.html ... -static -static stuff are in here, not important -staticfiles -static stuff are in here, not important -media -offers *VSy6kJDNq2pSXsCzb6cvYF.jpg *db.sqlite3 *passenger_wsgi.py *passenger_wsgi.pyc Settings.py MEDIA_URL= '/media/' MEDIA_ROOT= os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' STATIC_ROOT=os.path.join(BASE_DIR,'staticfiles') STATICFILES_DIRS = [ BASE_DIR / "static", ] urls.py urlpatterns = [ path('', homepage), path('servises', servisespage), path('offers', offerpage), path('products', productspage), path('admin/', admin.site.urls), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) # Adding MEDIA_URL and root does not work either views.py def offerpage(request): ids = Offer.objects.values_list('id', flat=True) obj_list = [] for id in ids: obj = Offer.objects.get(id=id) obj_list.append(obj) context = { "objects": obj_list } return render(request, "offers.html", context) offers.html <main> {% for obj in objects %} <div class="offer"> <h1 id="name">{{obj.name|title}} </h1> <img id="photo" src= '{{ obj.photo.url }}' alt="this is the image" width="500"> <h3 id="price">Τιμη: <span id="price-color">{{obj.price}} €</span></h3> <h3 id="summary"> {{obj.description}} </h3> </div> {% endfor %} </main> When i try to inspect the site on firefox, in the … -
JavaFX Websocket with python server(Django)
So I have a project already running on a Django server In the server I have used channel implement the socket server and I was creating a desktop application(in JavaFX) and I'm kinda stuck on how to implement WebSocket in JavaFX which will later establish a full-duplex with the Django server. Is there a way to accomplish this, some tutorial I can go through? Thanks in advance -
Ionic& Angular: Ran into status 0 Unknown Error, what can I do when I cannot reproduce the same error?
I have helped to develop a hybrid check-in mobile app using Angular & Ionic. One of the clients informed that the following error occurs. Http failure response for https://url.com/api/: 0 Unknown Error. But it seems I cannot reproduce the same error, as it happens randomly after some days. I have gone and added a retry feature to my subscription, as well as being able to send me an email if the error happens again; since I have to know what is causing the issue. The snippet code is below, but the same issue is happening on different endpoints: this.sharedService.uploadImageToVisionAPI(image.dataUrl) .pipe(retryWhen(error => { return error.pipe( // we use mergeMap instead of switchMap to have all request finished before they are cancelled mergeMap((error, i) => { const retryAttempt = i + 1; // if maximum number of retries have been met // or response is a status code we don't wish to retry, throw error const scalingDuration = 500; if (retryAttempt > 9) { return throwError(error); } console.log( `Attempt ${retryAttempt}: retrying in ${retryAttempt * scalingDuration}ms` ); return timer(retryAttempt * scalingDuration); }), finalize(() => console.log('We are done!')) )})) .subscribe(confidence_percentage => { let confidence = confidence_percentage['percentage'] }) Have you ran into a similar error, … -
How to use django-select2 widgets in django admin site?
In my django app I have modified the User entity to include a worker field (OneToOneField). But from the django admin site that field yiels so many result , so it is difficult for the logged user to select a worker. Is there any way to use the select2 (ModelSelect2Widget) widgets from the django admin site? For any regular form I have define the widgets in the following way: from django_select2.forms import ModelSelect2Widget class ProcessForm(forms.ModelForm): class Meta: model = ProcessModel exclude = ('id',) widgets = { 'name':forms.TextInput(attrs={'class': 'form-control'}), 'code':forms.TextInput(attrs={'class': 'form-control'}), 'description':forms.Textarea(attrs={'class': 'form-control'}), 'geom': LeafletWidget(), 'product': ModelSelect2Widget(model=ProductModel, queryset=ProductModel.objects.filter(), search_fields=['name__icontains'], attrs={'style': 'width: 100%;'}), } Is there any way to use the ModelSelect2Widget for the worker field in the admin site form? Here is my code: class User(AbstractUser): worker = models.OneToOneField(WorkerModel, on_delete=models.CASCADE, related_name="user", verbose_name=_("Trabajador"), null=True, blank=True) class Meta: default_permissions = () verbose_name="Usuario" verbose_name_plural="Usuarios" permissions = ( ("secretario", "Secretario(a)"), ("director", "Director"), ) from django.contrib.auth.admin import UserAdmin class UserAdminInherited(UserAdmin): fieldsets = ( (None, {'fields': ('username', 'password')}), (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}), (_('Worker info'), {'fields': ('worker',)}), (_('Permissions'), { 'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions'), }), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) admin.site.register(User, UserAdminInherited) -
not found(deploying via digitaloccean, nginx, ubuntu, Gunicorn )
I tried to deploy Django via digitaloccean, nginx, ubuntu, and Gunicorn. I followed the tutorial that digitaloccean provided. Everything was fine before the step of binding it with Gunicorn. I was able to use the run "manage.py runserver 0.0.0.0:8000"and was able to see the website on port 8000 of the IP address; however when I tried to run gunicorn --bind 0.0.0.0:8000 myproject.wsgioutput,and tried to connect to the IP address again, the 404 not found error occurred.output I also tried every port of the IP address but none of them worked. This is the output of systemctl status gunicorn.service output. And this is the output of sudo journalctl -u gunicornoutput. I have the following questions: What might possibly cause this error? Does being able to run it on local server means that the error is not caused by the source code? What can I try to fix this issue? Thank you !!! -
How to use a drop-down per column search form for django-tables 2?
Imagine you have the following table: views.py: class ActionView(SingleTableView, FormView, SingleTableMixin, FilterView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = SnippetFilter(self.request.GET, queryset = self.get_queryset()) queryset = kwargs.pop('object_list', None) if queryset is None: self.object_list = self.model.objects.all() context['actions'] = Action.objects.all() return context filters.py: class SnippetFilter(django_filters.FilterSet): class Meta: model = Action fields = ('name', 'description', 'control' ) action.html: <div class="row row-card-no-pd"> {% if filter %} <form action="" method="get" class="form form-inline"> {% bootstrap_form filter.form layout='inline' %} <button type = "submit" class ="btn btn-primary">Search</button> </form> {% endif %} <div class="col-md-12"> <div class="card"> <div class="card-header"> <div class="card-head-row card-tools-still-right"> <h4 class="card-title">Overview of all actions</h4> <div class="card-tools"> <button aria-pressed="true" class="btn btn-primary btn-lg active" data-target="#addRowModal" data-toggle="modal"> <i class="fa fa-plus"></i> Add Action </button> </div> </div> <p class="card-category">Please find below an overview of all the current actions</p> </div> <div class="card-body"> {% for action in filter.qs %} {% load django_tables2 %} {% render_table table %} {% endfor %} </div> </div> </div> </div> Which renders the following: How can you get drop down filter option inside the table per column? For example, when clicking on a column you can type the inside the form to filter I'm running into some trouble there because there is no documentation at hand for django-tables-2.. Please help! -
Twitter-Bootstrap 5 carousel indicators and controls not working. Why?
I am making a ecommerce website with Django framework. I cannot make my bootstrap carousel work. Clicking on indicators and controls has no effect. I have pulled in Bootstrap source files with NPM. main.html <!DOCTYPE html> {% load static %} <html lang="fr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="{% static 'css/main.css' %}" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css"> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <title> {% block title %} {% endblock title %} </title> </head> <body class="mt-sm-5 mt-md-5 mt-lg-5 mt-xl-5"> <header> <div class="container border-bottom border-primary border-1"> </div> </header> <section class="page-content" id="page-content"> {% block content %} {% endblock content %} </section> <script src="{% static 'js/bootstrap.js' %}"></script> </body> </html> product_details.html {% extends 'main.html' %} {% load static %} {% block title %} Boutique - {{ product.title }} {% endblock title %} {% block content %} <div class="container"> <div class="row" > <div id="product-carousel" class="col-sm-12 col-md-6 border border-danger carousel slide carousel-fade" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#product-carousel" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> {% if product.image2 %} <button type="button" data-bs-target="#product-carousel" data-bs-slide-to="1" aria-label="Slide 2"></button> {% endif %} {% if product.image3 %} <button type="button" data-bs-target="#product-carousel" data-bs-slide-to="2" aria-label="Slide 3"></button> {% endif %} </div> <div class="carousel-inner"> <div class="carousel-item active"> <img src="{{ product.image.url }}" class="img-fluid" alt="..."> </div> {% if product.image2 %} <div … -
How to create related objects from JSON in DRF?
I have JSON like: [ { "groupId": 123, "groupName": "Group 1", "monthName": "May", "monthNumber": 5, "year": 2021, "usersDutyList": [ { "userName": "Test1", "userFullname": "Test1 User", "userId": 553, "userEmail": "asd@asd.com", "isOnDutyThisMonth": true, "userPhone": "+1 234 5678", "userExt": "123", "isOwner": "false" }, ... ] } ] And I wrote the models: class Group(Model): groupId = SmallIntegerField(primary_key=True) groupName = CharField(max_length=100) monthName = CharField(max_length=8, choices=MONTH_NAME_CHOICES) monthNumber = SmallIntegerField(choices=MONTH_NUMBER_CHOICES) year = SmallIntegerField(choices=YEAR_CHOICES, default=datetime.datetime.now().year) class User(Model): userName = CharField(max_length=20, unique=True) userFullname = CharField(max_length=40) userId = SmallIntegerField(primary_key=True) userEmail = EmailField(unique=True, verbose_name='Email') userPhone = CharField(max_length=15) userExt = CharField(max_length=10) isOwner = BooleanField() group = ForeignKey(Group, on_delete=CASCADE, related_name='usersDutyList') I need to create a Group object and its associated User objects from the "usersDutyList" key. Now I have this serializers: class UserSerializer(HyperlinkedModelSerializer): class Meta: model = User fields = '__all__' class GroupSerializer(HyperlinkedModelSerializer): usersDutyList = UserSerializer(many=True, required=False) def create(self, validated_data): users = validated_data.pop('usersDutyList') group = Group.objects.create(**validated_data) for user in users: user_dict = dict(user) User.objects.create(group=group.groupId, **user_dict) return group But since no Group object is passed to UserSerializer I receive [ { "usersDutyList": [ { "group": [ "Required field." ] } ] }, ... ] Can't find any information about related objects creation in DRF. Can you help implement this functionality? -
open source project with graphql django
I am learning graphql django and to learn better I have to see the real source of the real project with Django and graphql on github, but I can not find any. Can anyone help me find an open source project with graphql django