Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you perform a inner join between 2 tables in Django?
I am beginning to learn Django, and I need to perform a inner join between 2 of my tables. I have looked at many different questions here but none seem to help me. I have 2 modules: class Course(models.Model): course_id = models.CharField(db_column='Course_ID', primary_key=True, max_length=6) # Field name made lowercase. name = models.CharField(db_column='Name', max_length=255, blank=True, null=True) # Field name made lowercase. maxhp = models.DecimalField(db_column='MaxHP', max_digits=4, decimal_places=1, blank=True, null=True) # Field name made lowercase. def __str__(self): return self.name class Meta: managed = False db_table = 'course' class CoursePart(models.Model): MAYBECHOICE = ( ('True', 'Yes'), ('False', 'No') ) course = models.ForeignKey(Course, models.DO_NOTHING, db_column='Course_ID', primary_key=True) # Field name made lowercase. name = models.CharField(db_column='Name', max_length=255) # Field name made lowercase. hp = models.FloatField(db_column='HP', blank=True, null=True) # Field name made lowercase. part_completed = models.CharField(max_length=1, choices=MAYBECHOICE) def __str__(self): return self.name class Meta: managed = False db_table = 'course_part' unique_together = (('course', 'name'),) I want to perform something like this: SELECT * FROM course JOIN course_part ON course.Course_ID = course_part.Course_ID Please help me with this issue -
How do we rename Django PointField attribute names?
Currently when I set a PointField in my model, the JSON I receive is in this form: "type": "Point", "coordinates": [ 121, 52, 0 ] Is there a way we can change "type": "Point" to "type": "Vector" and "coordinates" : [...] to "xyz" : [...]? Would it be possible to achieve this renaming in our serializer? -
Cannot enter data into form inputs
I am trying to render to django form inputs on the same line. When I add col-md-6 to the class in form-group, I cannot click on the inputs to type data in. Can anyone see why? <div class="form-row"> <div class="form-group col-md-6"> <label for="CRF">Case Report Form Number</label> {{ general_info_form.case_report_form_number }} </div> <div class="form-group col-md-6"> <label for="CRF">Study Start Date</label> {{ general_info_form.study_start_date }} </div> </div> forms.py class Meta: model = GeneralInfo fields = '__all__' widgets = { 'form_type': forms.HiddenInput(), 'case_report_form_number': forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Case Report Form Number', 'id': 'CRF'}), 'study_start_date': forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Studying Beginning Date', 'id':'study_start_date'}) } -
Django URL regex to include forward slashes
I am having trouble with creating a Django URL regex which allows all characters (including forward slashes). More specifically, the problem I am having is differentiating between forward slashes used in the URL args and forward slashes used as delimiters in the URL. example: I have a URL which looks like this: localhost:8000/jfe/customer/customerNumb/invoice2/portfolio/ this consists of 3 URL arguments: customerNumb, invoice2, portfolio. My goal is to make it so argument 2 can contain special characters including '/' so the 2nd argument could be something like "KJ 02/2017" (without quotes). example: localhost:8000/jfe/customer/customerNumb/KJ 02/2017/portfolio/ in the example of using "KJ 02/2017" I am having trouble with differentiating the '/' in "KJ 02/2017" and the '/' which separates arg2 and arg3. my regex: url(r'^customer/(?P<customer_number>[0-9]+)/(?P<invoice>[^/]+)/$') url(r'^customer/(?P<customer_number>[0-9]+)/(?P<invoice>[^/]+)/(?P<portfolio>[^/]+)/$') I have also tried url(r'^customer/(?P<customer_number>[0-9]+)/(?P<invoice>.+)/$') url(r'^customer/(?P<customer_number>[0-9]+)/(?P<invoice>.+)/(?P<portfolio>[^/]+)/$') If I encode the URL: example: localhost:8000/jfe/customer/customerNumb/KJ%2002%2F2017/portfolio/ the regex will parse it like this: arg1: customerNumb, arg2: KJ%2002%2F2017/portfolio/ when I want: arg1: customerNumb arg2: KJ%2002%2F2017 arg3: portfolio can someone please help me understand where I am messing up in my regex? or let me know if its even possible to have '/' included in url arguments? thank you -
Django no reverse match exception in the homepage localhost:8000
I am trying to access the homepage of my website using the localhost:8000, but it is not working. It keeps giving me the "No reverse match" exception. More information on the exception is here: NoReverseMatch at / Reverse for 'product_list_by_category' with arguments '('kids',)' not found. 1 pattern(s) tried: ['(?P<category_slug>[-/w]+)/$'] I just created one category of products in the website, called "kids". As I am trying to access the homepage, I cannot understand why it is giving me that error. I believe it is an error with the url patterns I included or with the models I defined for my "shop" class. Directory: Urls.py of the shop app: urlpatterns = [ url(r"^$", views.product_list, name="product_list"), url(r"^(?P<category_slug>[-/w]+)/$", views.product_list, name="product_list_by_category"), url(r"^(?P<id>\d+)/(?P<slug>[-/w]+)/$", views.product_detail, name="product_detail"), ]; Urls.py of the main project folder: urlpatterns = [ path('admin/', admin.site.urls), url(r"^cart/", include(("cart.urls", "cart"), namespace="cart")), url(r"^", include(("shop.urls", "shop"), namespace="shop")), ]; if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT); models.py of the shop app: class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) class Product(models.Model): category = models.ForeignKey(Category, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) … -
How does drf handle serialize manytomany fields
How does DRF by default handle serializing a manytomany? I see it defaults to render the field as an array of ids ex: [1,2,3] And only uses 2 queries when I prefetch the related model. However, when I generate it myself with .values_list('id', flat=True) it makes an extra query for every row. Models class Fails(models.Model): runs = models.ManyToManyField(Runs, related_name='fails') class Runs(models.Model): name = models.TextField() View class FailsViewSet(viewsets.ModelViewSet): ... def get_queryset(self): ... return Fails.objects.filter(**params).prefetch_related('runs') Serializer class FailsSerializer(QueryFieldsMixin, serializers.ModelSerializer): runs = serializers.SerializerMethodField() def get_failbin_regressions(self, obj): runids = self.context.get('runids') return obj.runs.values_list('id', flat=True) #this creates an extra query for every row The end goal is to get runs to display a filtered list of runids. return obj.runs.values_list('id', flat=True).filter(id__in=runids) or runs = obj.runs.values_list('id', flat=True) return [x for x in runs if x in runids] #to avoid an extra query from the .filter I know the filter creates more queries, I assume the prefetch model is lost in the serializerMethodField. Is there a way of getting the list of ids like drf does it without the extra query cost when I manually? I can't find any documentation on how they implement the manytomany render. -
DJANGO - XML Parsing Error: not well-formed Location
I am getting the following error message: XML Parsing Error: not well-formed Location: http://localhost:8000 /see/scheduleRequest/new Line Number 20, Column 97: <p><label for="id_RequestType">RequestType:</label> <select name="RequestType" required id="id_RequestType"> But Django is prepopulating that field, does anyone know what causes that error? The coded from models is REQUEST_TYPES = ( ('Hardship','Hardship Accommodation'), ('Religious','Religious Accommodation'), ('School','School Accommodation'), ) RequestType = models.CharField(max_length=40, choices=REQUEST_TYPES) -
Is it possible to create new charfields using django admin page interface?
I am new to Django and I wonder, if is it possible to create and delete new charfields on django admin page without harcoding them. For example, I have a simple model, registered in Django admin page class DocumentList(models.Model): title = models.CharField(max_length=200) def __str__(self): return self.title Obviously, it has only one charfield on admin page,something like: DocumentList: [___________] How can I add another one and delete her later if needed from Django admin page without actually hardcoding another charfield in models.py, to make it look like DocumentList: [___________] *****************[___________] -
Why is this not displaying properly?
I am really not sure why this isn't displaying the band names with their hyperlinks, all that is appearing is the title 'Band List' with nothing beneath it. There is data in the database but nothing is showing. Here is the template. {% block content %} <h1>Band List</h1> {% for band in bands %} {{ band.id }} <h3><a href='/bandlist/{{band.id}}'>{{ band.bandname }}</a></h3> {% endfor %} {% endblock %} Here are my views.py from django.http import HttpResponse from django.shortcuts import get_object_or_404, render, render_to_response, redirect from django.contrib.auth.decorators import login_required from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from polls.forms import NormalSignUpForm, VenueSignUpForm, BLSignUpForm, BMSignUpForm, ProfileForm from django.contrib.auth import get_user_model from django.views.generic.detail import SingleObjectMixin from django.views.generic import UpdateView, TemplateView from django.utils.decorators import method_decorator from django.db.models.signals import post_save from .models import * from polls.models import User from django.http import Http404 def bandlist(request): query = Band.objects.all() print(query) args = {'query': query} return render(request, 'bandlist.html', args) Here are my models.py class Band(models.Model): bandname = models.CharField(max_length = 50) description = models.TextField() picture = models.ImageField() members = models.ManyToManyField('User') def __str__(self): return self.bandname If anyone could provide clarification on this it would be really helpful, thank you. -
Chaining custom querysets inside the Queryset Object to obtain a different custom queryset
I have the following code: class MQuerySet(models.query.QuerySet): def active(self): return self.filter(is_active=True) def type_a(self): return self.filter(type=AB) def active_type_a(self): return self.active().self.type_a() The issues is in chaining in active_type_a method, because my example will fail. Off course the above example is simple, and I can add the filter, but I have also more complex querysets, where I want to do this. -
Table level logic Django
I have this model: class Sesion(models.Model): maq = models.CharField(max_length=25) ini_sesion = models.DateTimeField(auto_now_add=True) fin_sesion = models.DateTimeField(null=True, blank=True) cont_ini_a = models.IntegerField(null=True, blank=True) con_ini_b = models.IntegerField(null=True, blank=True) con_fin_a = models.IntegerField(null=True, blank=True) con_fin_b = models.IntegerField(null=True, blank=True) @staticmethod def cierre(): instance = Sesion.objects.filter(fin_sesion__isnull=True).latest('ini_sesion') sesion_abierta = None try: sesion_abierta = Sesion.objects.filter(maq=instance.maq).filter(fin_sesion__isnull=True) \ .filter(ini_sesion__lt=instance.ini_sesion).latest('ini_sesion') except Exception: print('Ha ocurrido una excepcion!') if sesion_abierta: sesion_abierta.con_fin_a = instance.con_fin_a sesion_abierta.con_fin_b = instance.con_fin_b sesion_abierta.fin_sesion = instance.ini_sesion return sesion_abierta.save() Now the thing is i can't make it work every time a model instance is saved. I works when it is called from python/django shell >>> Sesion.cierre() but not when a model instance is saved and it doesn't work on save() override or signals either. Thx in advance. -
How can I change my request.GET url in Django Class view?
I want to change my the url string that my class view redirects to after a GET request. How can I do this? class ReportView(View): template_name = 'results/reporting.html' context = {} runsearchform = RunSearchForm def get(self, request, *args, **kwargs): form = self.runsearchform() self.context = {'form':form} if 'run' in request.GET: run = request.GET['run'] self.context = {'run': run} return render(request, self.template_name, self.context) When form is submitted i go to: localhost/reporting/?run=2&submit=Search+for+run where the 2 is Run model PK. I would like to change ?run=2&submit=Search+for+run into a run_name based on other attributes of my Run model. -
Django save some fields
When I press "Upload" i have error: UNIQUE constraint failed: main_profile.user_id. Where do you need to insert the profile id? <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label for="pic">Загрузить фото:</label> {{ form.as_p }} <button type="submit">Upload</button> </form> views.py def profile(request, user_name): user = User.objects.get(username=user_name) if request.method == 'POST': form = ImageForm( request.POST, request.FILES, instance=Profile(user=user) ) if form.is_valid(): form.save() #When I put commit=False the error disappears, but image don`t save return redirect('/') else: form = ImageForm() return render(request, "profile.html", {"profile_data": user, 'form': form}) models.py User class extension class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) photo = models.ImageField(verbose_name="Фото", upload_to="images/profile", default="images/profile/profile.png", blank=True) forms.py from django import forms from main.models import Profile class ImageForm(forms.ModelForm): class Meta: model = Profile fields = ('photo', ) -
Makemigrations in dev machine, without database instance
I am working in my dev machine. The code is tested during development in docker containers, because: I have a nice docker-compose.yml I want to develop in an environment as similar to the deploy environment as possible I do not want to install any package system wide (specifically postgres): I only want in my development machine applications for development, not for testing or running applications. Now I am trying to update my migrations: » DJANGO_SECRET_KEY=xxx python manage.py makemigrations .... django.db.utils.OperationalError: could not translate host name "postgres" to address: No address associated with hostname Well, yes, of course, my host machine can not see the postgres container (only the running containers can see each other, as per docker compose architecture) I could connect to the app container, make the migrations there, and retrieve the migrations to my development machine, but this does not seem a good solution. My understanding is that the migrations are computed based on: - the currently stored migrations, in the development repo - the changes in the models, as compared to those migrations I do not see why I need a database instance to make the migrations. Can I make migrations without a connection to the database? … -
Django doesn't create object in database
I am not sure what's wrong. I have tried migrate/makemigrations and that doesnt help, Im working in virtualenv tho. my models.py from django.db import models import re # Create your models here. class Currency(models.Model): def __str__(self): return self.short name = models.CharField(max_length=32, null=True, blank=True) country = models.CharField(max_length=50, null=True, blank=True) short = models.CharField(max_length=10, null=True, blank=True) class Source(models.Model): def __str__(self): return self.name + '({}...)'.format(self.url[:20]) url = models.URLField() name = models.CharField(max_length=250, verbose_name='Source_name') timestamp = models.DateTimeField(auto_now_add=True) currency = models.ForeignKey(Currency) def save(self, *args, **kwargs): self.name = ''.join(re.sub('\s+', ' ', self.name).strip()) super(Source, self).save() class Product(models.Model): def __str__(self): return self.name name = models.CharField(max_length=250, blank=False) prices = models.ManyToManyField(to='Price', blank=True) date_creation = models.DateField(auto_now_add=True) prod_code = models.CharField(max_length=250, blank=True, null=True) def save(self, *args, **kwargs): self.name = ''.join(re.sub('\s+', ' ', self.name).strip()) super(Product, self).save() My function that creates objects def from_csv_to_db(csv_name): # empty DB try: df = pd.read_csv(csv_name, sep=';') except FileNotFoundError: return ('Please input correct path to csv file or check spelling. Process finished') for i, row in df.iterrows(): Currency.objects.get_or_create(short=row['source__currency__short'], id=row['source__currency_id']) Product.objects.get_or_create(id=row['product__id'], name=row['product__name']) Source.objects.get_or_create(id=row['source__id'], name=row['source__name'], url = row['source__url'], currency_id=row['source__currency_id']) Parser.objects.get_or_create(script=row['script'], boolean=row['boolean'], product_id=row['product__id'], source_id=row['source__id']) return 'Done' However, django does display my models object via queryset in python manage.py shell from Parser.models import * Product.objects.all() <QuerySet [<Product: test product>, <Product: iphone>, <Product: Mac>, <Product: iPad>]> however … -
DjangoAdmin form with 1:N selection wont save object
I was looking for a way to assign one, or more, already existing objects to the current one, while creating in the add section. Something like InLine but I do not want to create them, only select and assign. Two example models: class Location(models.Model): name = models.CharField(max_length=30) class Device(models.Model): name = models.CharField(max_length=20) location = models.ForeignKey(Location, null=True, blank=True, on_delete=models.DO_NOTHING) So while creating Location in Django Admin, I want to be able to assign 1-N existing Devices. I found a way to do so, with a custom Form Here is my custom Form inside admin.py class LocationForm(forms.ModelForm): class Meta: model = Location fields = '__all__' devices = forms.ModelMultipleChoiceField(queryset=Device.objects.all()) def __init__(self, *args, **kwargs): super(LocationForm, self).__init__(*args, **kwargs) if self.instance: self.fields['devices'].initial = self.instance.device_set.all() def save(self, *args, **kwargs): instance = super(LocationForm, self).save(commit=False) self.fields['devices'].initial.update(location=None) self.cleaned_data['devices'].update(location=instance) return instance @admin.register(Location) class LocationAdmin(admin.ModelAdmin): form = LocationForm That works fine as long as I dont save the Location object. Here is a picture of how it looks in django admin. However when I try to save the Location, I got the following error: File "admin.py", line 21, in save api | self.cleaned_data['devices'].update(location=instance) api | File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 692, in update api | rows = query.get_compiler(self.db).execute_sql(CURSOR) api | File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1378, … -
django-rq and rqscheduler deployment on AWS Elastic Beanstalk
I have a Django app that runs on AWS EB environment. With recent updates I had to integrate django-rq and rqscheduler for some queue based background tasks. This all works fine on localhost with commands rqworker and rqscheduler. But I am having real trouble finding a way to make it run on AWS EB environment. My analysis says the only way to go is use ElastiCache. Can anyone guide me to the right direction or any blog posts that could help me with this? -
Show total count of Reports per Profile in Django Admin
I have two models, Report and Profile and Profile is connected to Report as a foreignKey. In my admin.py I want to show each Profile along with the amount(count) of times that the profile has been reported. Can't get the function to work as I am left with a "type object 'Profile' has no attribute 'total'" Attribute error. Profile model has no 'total', but I have defined it in the function. from django.contrib import admin from .models import Profile,Report from django.db.models import Count class ProfileAdmin(admin.ModelAdmin): list_display = ('id', 'birth_date', 'sessions_played','user_report') def user_report(self, obj): total = Report.objects.count() amount = Profile.total return amount admin.site.register(Profile, ProfileAdmin) class ReportAdmin(admin.ModelAdmin): list_display = ('report_reason','sent_by', 'session', 'user_reported') admin.site.register(Report,ReportAdmin) Models are Linked here as an image link,click to view: https://ibb.co/b9YwsH -
django inline_formset - form.empty_permitted = False doesn't work
I have two models - Invoice and InvoiceItem. I have the following formset. class InvoiceItemFormSet(forms.BaseInlineFormSet): def __init__(self, *args, **kwargs): super(InvoiceItemFormSet, self).__init__(*args, **kwargs) for form in self.forms: form.empty_permitted = False def clean(self): cleaned_data=super(InvoiceItemFormSet, self).clean() print('inside form.clean') Inside my CreateViw, I have the following code for the formset. ItemInlineFormSet = inlineformset_factory(Invoice, InvoiceItem, form=InvoiceItemForm, extra=1, can_delete=False,validate_min=True, min_num=1, formset=InvoiceItemFormSet) However, when I press the Submit button, even if all (two) forms of the formset are empty, the parent form gets submitted. What I'm missing here? Thanks. -
Django distinct() query issues with annotation
So basically I've got view for the query Route.objects.distinct().annotate(mtr = Sum('arms__km'), sum=Sum('arms__price'), wgh=Sum('arms__cmrs__pipe_weight') ) The results for wgh are ok, but the results for mtr & sum multiply by the number of how many cmrs objects are linked to arms object. My models: class CMR(models.Model): pipe_weight = models.DecimalField() class Arm(models.Model): cmrs = models.ManyToManyField(CMR) km = models.PositiveIntegerField() class Route(models.Model): arms = models.ManyToManyField(Arm) Could you please explain how can I avoid duplication? Thanks in advance. -
Django: Change url in Class based view GET request
Hi I have two forms which render to the same template. When i submit my runsearchform, it takes me to the page: localhost/reporting/?run=2&submit=Search+for+run where 2 is my run PK id How can I modify this URL into something like localhost/reporting/run_name where run_name = a unique field in my Run model that is not the primary key views: class ReportView(View): runsearchform = RunSearchForm samplesearchform = SampleSearchForm def get(self, request, *args, **kwargs): runsearchform = self.runsearchform() context = {'runsearchform': runsearchform} if 'run' in request.GET: samplesearchform = self.samplesearchform(request.GET) context = {'samplesearchform': samplesearchform} return render(request, 'results/reporting.html', context) def post(self, request, *args, **kwargs): """ do stuff with samples... """ -
I can save picture files to but I can't retrieve them with Django Admin page
I have this model in my models.py: class Photograph(models.Model): owner = models.ForeignKey(User, on_delete=models.PROTECT, related_name='photos_of_user') photo = models.ImageField() album = models.ForeignKey('Album', on_delete=models.CASCADE, related_name='photos_of_album') description = models.CharField(max_length=256) def __str__(self): return self.description I can save image files with Django Admin site (I can see them with ls) but, when I try to see the image by clicking in the link with the name of the file, I get a Photograph with ID "5/change/IMGT75.JPG" doesn't exist. Perhaps it was deleted? In fact, the name of the file (IMGT75.JPG in the example) is different to the actual name of the file. I don't know where Django takes it from. Thanks for your help. -
Django: Image Compression
In my django app i'm trying to resize & compress an Image before saving it to the database. Here's how I did it inside the models class Data(models.Model): image = models.ImageField(upload_to='all_images/', null=True, blank=True) def save(self, *args, **kwargs): if self.image: img = Image.open(self.image) resize = img.resize((240, 240), Image.ANTIALIAS) new_image = BytesIO() resize.save(new_image, format=img.format, quality=80, save=False) temp_name = os.path.split(self.image.name)[1] self.image.save(temp_name, content=ContentFile(new_image.getvalue()), save=False) super(Data, self).save(*args, **kwargs) Here's the problem, I saved an image named tesla.jpg into the database, it compressed & resized it well, but it renamed it something like, tesla_CKBw0Kr_iWKC4Ry_ucPoh4b_BB2C8Ck_WrfWkPR_Tzig2T1_tdhst4b_3Bysn6k_i4ffhPR_yhig2T1.jpg I'm worried about the new name because normally it should be tesla_CKBw0Kr.jpg or something smaller, so what's the problem in my code & how can we fix that? -
How to join tables in Django?
Below is my models.py class Topic(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=300) created_on = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, related_name='topic') def __str__(self): return self.name class Question(models.Model): name = models.CharField(max_length=300, unique=True) img = models.CharField(max_length=100) topic = models.ForeignKey(Topic, related_name='question') created_by = models.ForeignKey(User, related_name='question') created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Answer(models.Model): ans = models.TextField() img = models.CharField(max_length=100) created_by = models.ForeignKey(User, related_name='answer') created_on = models.DateTimeField(auto_now_add=True) ques = models.ForeignKey(Question, related_name='answer') def __str__(self): return self.ans class Upvote(models.Model): upvote = models.BooleanField(default=False) upvote_by = models.ForeignKey(User, related_name='upvote') upvoted_on = models.DateTimeField(auto_now_add=True) ques = models.ForeignKey(Question, related_name='upvote') ans = models.ForeignKey(Answer, related_name='upvote') class Comment(models.Model): comment = models.TextField() comment_by = models.ForeignKey(User, related_name='comment') commented_on = models.DateTimeField(auto_now_add=True) ques = models.ForeignKey(Question, related_name='comment') ans = models.ForeignKey(Answer, related_name='comment') class Follow(models.Model): topic = models.ForeignKey(Topic, related_name='follow') user = models.ForeignKey(User, related_name='follow') I am trying to get questions and answers based on the follow table which has user-topic mapping. user_topic = Take topics for the user from follow table question = Take question where topic = user_topic answer = Take answer where ques = question Below is my views.py def home(req): user_id = req.user.id follow = Follow.objects.filter(user = user_id).all() user_follow_topics = Topic.objects.filter(pk__in=follow).all() question = Question.objects.filter(topic__in=user_follow_topics).all() answer = Answer.objects.filter(ques__in=question).all() topic = Topic.objects.all() return render(req,'home.html',{'topic':topic,'user_follow_topic':user_follow_topics,'question':question,'answer':answer}) Below is my home.html <div class="container" id="cont"> <div … -
unable to create a SerializerMutation without errors, but data is created
I do not why but when I try to create new data using serializermutation, data is created but graphiql return an error. Here is my code. graphene(2.1) _graphene_django(2.0.0)_ models class CompanyRole(models.Model): name = models.CharField(null=False, blank=False, max_length=20) def __str__(self): return '{}'.format(self.name) class Meta: verbose_name = _('Company role') verbose_name_plural = _('Company roles') serializers class CompanyRoleSerializer(serializers.ModelSerializer): class Meta: model = CompanyRole fields = ('name',) mutations class CreateCompanyRole(SerializerMutation): class Meta: serializer_class = CompanyRoleSerializer class CompanyRoleMutation(AbstractType): create_company_role = CreateCompanyRole.Field() schema class Query(CompanyRoleQuery, CompanyQuery, graphene.ObjectType): pass class Mutation(CompanyRoleMutation, graphene.ObjectType): pass schema = graphene.Schema(query=Query, mutation=Mutation, types=[ CompanyRoleType, CompanyType, ]) this is the query used mutation { createCompanyRole(input:{name:"name"}){ errors { field messages } name } } and this is the error { "data": { "createCompanyRole": null }, "errors": [ { "message": "SubclassWithMeta_Meta object argument after ** must be a mapping, not CompanyRole", "locations": [ { "column": 3, "line": 2 } ] } ] } But I can access to the new data from the admin. Anyone could help me?