Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is command prompt returning a gdal not found error
I am trying to add geodjango to an already existing django project. I have installed everything that is request e.g postgressql proj geos e.t.c. I can't seem to install gdal on my system though. Everytime I try to run the project in local host it throws back a gdal not found error. I have tried using Osgeo4w, the .whl and the .msi file to try and install gdal. Can't seem to figure out what I'm doing wrong here. -
vscode debug suite all of a sudden can not find Django module
I've had my vscode integrated with my Django project perfectly fine for about a month now. I went home for the weekend and all of a sudden this morning my vscode debug suite is not working. I could almost swear that I have not touched anything since last time it was working, but I suppose it's possible I may have done something. NOTE: The following command fails when I have vscode run it, but when I open python manage.py shell, I can do from django.core.management import execute_from_command_line perfectly fine. I'm trying to run the test suite on all my tests, but after running the command (I put on separate lines for readability) /Users/hgducharme/Programming/webapp ; env DJANGO_SETTINGS_MODULE=webapp.settings.development PYTHONIOENCODING=UTF-8 PYTHONUNBUFFERED=1 /usr/local/bin/python3-32 /Users/hgducharme/.vscode/extensions/ms-python.python-2019.8.30787/pythonFiles/ptvsd_launcher.py --default --client --host localhost --port 52944 /Users/hgducharme/Programming/webapp/manage.py test apps/tests/ I get the error: Traceback (most recent call last): File "/Users/hgducharme/Programming/webapp/manage.py", line 10, in main from django.core.management import execute_from_command_line ImportError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/hgducharme/.vscode/extensions/ms-python.python-2019.8.30787/pythonFiles/ptvsd_launcher.py", line 43, in <module> main(ptvsdArgs) File "/Users/hgducharme/.vscode/extensions/ms-python.python-2019.8.30787/pythonFiles/lib/python/ptvsd/__main__.py", line 432, in main run() File "/Users/hgducharme/.vscode/extensions/ms-python.python-2019.8.30787/pythonFiles/lib/python/ptvsd/__main__.py", line 316, in run_file runpy.run_path(target, run_name='__main__') File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/runpy.py", line 240, in run_path pkg_name=pkg_name, script_name=fname) File … -
Missing admin page when Mezzanine site deployed to Heroku
The admin page does not appear for whatever reason when i navigate to the associated URL. Instead I get a page not found page. With the default message "error: an error occured" The weird thing is that the page shows up when i run heroku local or when I run the app locally without heroku. I suspect this is an issue with mezzanine URLS. But im not sure how they work :| . My database setting in settings.py DATABASES = {'default': dj_database_url.parse('postgres://blahblahtheurl')} I also made some changes to the static settings: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Full filesystem path to the project. PROJECT_APP_PATH = os.path.dirname(os.path.abspath(__file__)) PROJECT_APP = os.path.basename(PROJECT_APP_PATH) PROJECT_ROOT = BASE_DIR = os.path.dirname(PROJECT_APP_PATH) # Every cache key will get prefixed with this value - here we set it to # the name of the directory the project is in to try and use something # project specific. CACHE_MIDDLEWARE_KEY_PREFIX = PROJECT_APP # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = "/static/" # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" # STATIC_ROOT = os.path.join(PROJECT_ROOT, … -
Timestamp "2019-08-15T18:00:21.042255-07:00" is postfixed with -07:00 when i run this piece of code
Timestamp=datetime.utcfromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S.%f") when I run the above piece of code I see the time zone(-07:00)but I don't want the timezone to be displayed, so what I can I do to not display the timezone. -
Add custom field to ModelSerializer and fill it in post save signal
In my API I have a route to add a resource named Video. I have a post_save signal to this Model where I proccess this video and I generate a string. I want a custom field in my serializer to be able to fill it with this text that was generated. So, in my response I can have this value. class VideoSerializer(serializers.ModelSerializer): class Meta: model = Video fields = ('id', 'owner', 'description', 'file') @receiver(post_save, sender=Video) def encode_video(sender, instance=None, created=False, **kwargs): string_generated = do_stuff() Right now what I am getting in my response is: { "id": 17, "owner": "b424bc3c-5792-470f-bac4-bab92e906b92", "description": "", "file": "https://z.s3.amazonaws.com/videos/sample.mkv" } I expect a new key "string" with the value generated by the signal. -
How to solve NOT NULL constraint failed: transactions_withdrawal.user_id
I'm fairly new to django and i've been trying to solve this problem for over 4 days, i've surfed the web and read a lot of documentation. i know this might be a trivial problem but i need help. This is my code accounts\models.py class User(AbstractUser): username = None # first_name = None # last_name = None account_no = models.PositiveIntegerField( unique=True, validators=[ MinValueValidator(1000000000), MaxValueValidator(9999999999) ] ) first_name = models.CharField( max_length=256, blank=False, validators=[ RegexValidator( regex=NAME_REGEX, message='Name must be Alphabetic', code='invalid_first_name' ) ] ) last_name = models.CharField( max_length=256, blank=False, validators=[ RegexValidator( regex=NAME_REGEX, message='Name must be Alphabetic', code='invalid_last_name' ) ] ) gender = models.CharField(max_length=6, choices=GENDER_CHOICE) birth_date = models.DateField(null=True, blank=True) balance = models.DecimalField( default=0, max_digits=12, decimal_places=2 ) objects = UserManager() # USERNAME_FIELD = 'email' # use email to log in USERNAME_FIELD = 'account_no' # use email to log in REQUIRED_FIELDS = ['email'] # required when user is created def __str__(self): return str(self.account_no) transactions\forms.py class WithdrawalForm(forms.ModelForm): class Meta: model = Withdrawal fields = ["amount",] transactions\models.py class Withdrawal(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) amount = models.DecimalField( decimal_places=2, max_digits=12, validators=[ MinValueValidator(Decimal('10.00')) ] ) def __str__(self): return str(self.user) transactions\views.py class FormWizard(SessionWizardView): template_name = "transactions/form.html" def dispatch(self, request, *args, **kwargs): return super(FormWizard,self).dispatch(request, *args, **kwargs) def get_form_instance(self,step): return self.instance_dict.get(step, None) def … -
Date not rendering in Django template
I am attempting to pass date values from views.py (passed in from managers.py), but they are not rendering in my template. I made sure that the date value is correct by printing it to the console and adding it to my template. It renders fine without any filters, but when I used the exact same syntax from earlier in my project—where it worked—all I get are blank values. managers.py tz = pytz.timezone('America/Chicago') class ProfileManager(Manager): def index(self, request): … return { … 'date': datetime.now(tz), } views.py def index(request): response = Profile.objects.index(request) return render(request, 'users/index.html', response) index.html <div id="datePickerDate"> {{ date }} <input type="hidden" name="year" value="{{ date|date:'Y' }}" autocomplete="off"> <input type="hidden" name="month" value="{{ date|date:'n' }}" autocomplete="off"> </div> Result <div id="datePickerDate"> Aug. 19, 2019, 4:27 p.m. <input name="year" value="" autocomplete="off" type="hidden"> <input name="month" value="" autocomplete="off" type="hidden"> </div> I can't think of what I'm missing. Any help is appreciated. -
Static files not being utilized by Django on docker with nginx
Background I am working on a docker-compose app made of 4 services: a django app, a wagtail django app, nginx, and postgresql. My main issue is with static files: they work fine with the development server, but not with nginx. The really strange part is that nginx shows that it is serving the static files, and they are accessible through their URL on a browser. How can I get them to show up? From settings.py in wagtail app STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATICFILES_DIRS = [ os.path.join(PROJECT_DIR, 'static'), '' ] STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' From settings.py in django app STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') docker-compose.yml version: '3.7' services: nginx: image: nginx:latest container_name: production_nginx volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf - ./nginx/error.log:/etc/nginx/error_log.log #- /etc/letsencrypt/:/etc/letsencrypt/ - cms_static_volume:/usr/src/cms/static - core_static_volume:/usr/src/core/static ports: - 80:80 - 443:443 depends_on: - core - cms core: build: context: ./cirrus_core dockerfile: Dockerfile.prod command: gunicorn cirrus_core.wsgi:application --bind 0.0.0.0:8000 volumes: - core_static_volume:/usr/src/core/static expose: - "8000" env_file: .env depends_on: - db cms: build: context: ./cirrus_cms dockerfile: Dockerfile.prod command: gunicorn cirrus_cms.wsgi:application --bind 0.0.0.0:8001 volumes: - cms_static_volume:/usr/src/cms/static expose: - '8001' env_file: .env depends_on: - db db: image: postgres:11.5-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: .env.db volumes: postgres_data: core_static_volume: cms_static_volume: nginx.conf … -
Can i render VueJS with Django?
I would like to add Vue to my Django project, but i'm having troubles understanding some parts of it. At the actual moment, my project already has a bunch of templates and views. Everything is rendered by the views, the only JS i'm using is for Jquery. The need to add Vue comes to improve my UI. I don't need Vue to be my frontend, i only want to add some Vue components to my templates here and there. After making some research, i found about the Webpack + Vue approach. It's not the right approach for my project since it should be used for a project where the frontend is entirely built on Vue and is divided from the Django backend, so it is not the right way for me. At this point, the only way to go would be to add it using the CDN on my django html template: <script src="https://cdn.jsdelivr.net/npm/vue@2.6.0"></script> Would this approach be possible? -
Django User OnetoOneField Form - Fails Validation
I am using OneToOne Fields to connect a UserProfile form model to the default django user model. Using this to extend the user information to include more than the user model has to offer. Currently the post request is failing the is.valid() command and will not allow me to process the data and commit to the DB. Have looked all over for the solution with no luck, scratching my head. Here is my current models.py: from django.db import models from django.utils.timezone import now from django.contrib.auth.models import User # User Profile Model class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_bio = models.CharField(max_length=1000) user_photo = models.CharField(max_length=1000) user_level = models.CharField(default="Novice", max_length=256) Here is my current models.py: from django.contrib.auth.models import User from django import forms from .models import UserProfile # Django Default User Class class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password'] # User Profile Class class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ['user_bio', 'user_photo'] Here is the UserFromView created to serve the form and then commit once posted: views.py Imported modules... class UserFromView(View): user_form_class = UserForm user_profile_form_class = UserProfileForm template_name = 'home/registration_form.html' # Display blank form def get(self, request): user_form = self.user_form_class(None) user_profile_form = self.user_profile_form_class(None) … -
How to Pass Parameters to View When Form Is Valid
I have a view which renders a form where all lines of 'manifest' information are displayed after a user selects an order # from a dropdown and submits. This form should allow for the user to enter a new line, and after doing so (and refreshing) the view should display the form again but with that updated line. My problem is that my view consumes a parameter 'Reference_Nos' from the dropdown that initially displays the view and form. After a user enters a new value, that dropdown isn't used again so the view doesn't display the correct info. In place of that, I am trying to use one of the fields from the form 'reference' which is the same as that dropdown value. I am getting an integrity error "Orders matching query does not exist" I don't understand why that query does not exist because the same query is used when request method isn't "post" and it works then. Any help? forms.py class CreateManifestForm(forms.ModelForm): cases = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'Enter Cases'})) class Meta: model = Manifests fields = ('reference', 'cases', 'product_name', 'count', 'CNF', 'FOB') widgets={ 'product_name': forms.Select(attrs={'style': 'width:170px'}) } views.py def manifest(request): form = CreateManifestForm(request.POST) if request.method == "POST": if form.is_valid(): form.save() … -
How does a multi-tenant application fit in Microservices based architecture?
I have a SaaS based multi-tenant monolith application (built with Django), that I want to divide into microservices based architecture. But I am not sure how to divide the application into correct partitions. And on what aspects should I take care of? In case of monolith application, it's easy to understand that I have a tenant model that decides the schemas but how this will be done in microservices if I want each service to be multi-tenant? Or should I even make the services multi-tenant? -
Unable to rebuild elasticsearch indexes when running in docker-compose
I am playing with a Django project and elasticsearch 6.3.1 (using django-elasticsearch-dsl). When I am running the project from my own environment having the elasticsearch running in a docker, then everything works fine. The command I am using to run the elasticsearch in docker is docker run -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" docker.elastic.co/elasticsearch/elasticsearch:6.3.1 When I am attempting to run the django project with the elasticsearch together in docker using docker-compose then I get the following error when running python manage.py search_index --rebuild from inside the container of the django project. elasticsearch.exceptions.RequestError: RequestError(400, 'mapper_parsing_exception', 'Root mapping definition has unsupported parameters: [prettyUrl : {type=text}] [summary : {analyzer=html_strip, fields={raw={type=keyword}}, type=text}] [score : {type=float}] [year : {type=float}] [genres : {analyzer=html_strip, fields={raw={type=keyword}, suggest={type=completion}}, type=text}] [id : {type=integer}] [title : {analyzer=html_strip, fields={raw={type=keyword}, suggest={type=completion}}, type=text}] [people : {analyzer=html_strip, fields={raw={type=keyword}, suggest={type=completion}}, type=text}]') Now if i try to add an object then the error coming up is RequestError(400, 'action_request_validation_exception', 'Validation Failed: 1: type is missing;') NOTE that i do not have any of these problems when I am running the django project from the terminal and the elasticsearch using docker run with the command above. The problems only occur when running the docker-compose The documents.py i am using … -
Aggregate the results of a union query without using raw
I have a table that looks like this date car_crashes city 01.01 1 Washington 01.02 4 Washington 01.03 0 Washington 01.04 2 Washington 01.05 0 Washington 01.06 3 Washington 01.07 4 Washington 01.08 1 Washington 01.01 0 Detroit 01.02 2 Detroit 01.03 4 Detroit 01.04 2 Detroit 01.05 0 Detroit 01.06 3 Detroit 01.07 1 Detroit I want to know how many car crashes for each day happened in the entire nation, and I can do that with this: Model.values("date") \ .annotate(car_crashes=Sum('car_crashes')) \ .values("date", "car_crashes") Now, let's suppose I have an array like this: weights = [ { "city": "Washington", "weight": 1, }, { "city": "Detroit", "weight": 2, } ] This means that Detroit's car crashes should be multiplied by 2 before being aggregated with Washington's. It can be done like this: from django.db.models import IntegerField when_list = [When(city=w['city'], then=w['weight']) for w in weights] case_params = {'default': 1, 'output_field': IntegerField()} Model.objects.values('date') \ .annotate( weighted_car_crashes=Sum( F('car_crashes') * Case(*when_list, **case_params) )) However, this generates very slow SQL code, especially as more properties and a larger array are introduced. Another solution which is way faster but still sub-optimal is using pandas: aggregated = false for weight in weights: ag = Model.values("date") \ .annotate(car_crashes=Sum('car_crashes')) … -
Getting Django error (models.E028). for 6 different models after moving from the Desktop folder to the var/www folder on Ububtu Server
I recently moved my django project files from a laptop to a web server. After moving the files I ran the django dev server to test things and everything was fine. After moving the project files once to the var/www folder I attempted again to see if everything still worked before finishing the process of launching the project. I am now getting a django error (models.E028) and don't know how to solve it. I have looked through the models.py folder where these models are and everything appears the same as before. Also I have yet to destroy the copies of the project on the laptop so I tried to launch it there and it works with no errors. Unfortunately the Django docs don't give further explanation of the error, or where to start looking for the cause. I'm sure the error has to do with moving the files from one location to another on the server, but I can't think of why it would affect the models. They have to be in the folder they are located in now, so moving them back isn't a solution. I moved the folder with the following command: sudo mv file/I/needed/to/move /var/www/ Here is … -
Django JSONField - get source text
When using a JSONField, the contents are automatically decoded from JSON into python objects when reading the value. I have a use-case where I'm encoding the string back into JSON to embed in a template. Is there any way to just get the raw JSON string from the object? -
Django - Create unique ID for multiple columns
I am creating a model in Django and want to create a unique ID that is "grouped" on multiple columns. For example, if Col1, Col2 are the same, but Col3 is unique, create a Group ID from that combination of similar and unique column values. UUID Col1 Col2 Col3 Group ID 1 1929 9183 8192 192843 2 1929 9183 8193 192843 3 1929 9183 8194 192843 4 1839 8391 9183 984821 4 1839 8391 9184 984821 -
Build Docker container for Django in Centos
I'm trying to build docker container in Centos VM. Getting error Here is the OS type: uname -a Linux host01 3.10.0-957.5.1.el7.x86_64 #1 SMP Fri Feb 1 14:54:57 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux DockerFILE: # pull official base image FROM python:3.7-alpine # set work directory WORKDIR /usr/src/src # set environment varibles ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 RUN apk update \ && apk add --no-cache --virtual build-deps gcc python2-dev python3-dev musl-dev \ && apk add postgresql-dev \ && pip install psycopg2 \ && apk del build-deps Getting ERROR: Step 6/15 : RUN apk update && apk add --no-cache --virtual build-deps gcc python2-dev python3-dev musl-dev && apk add postgresql-dev && pip install psycopg2 && apk del build-deps ---> Running in 3f4abc717bca fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/main/x86_64/APKINDEX.tar.gz ERROR: http://dl-cdn.alpinelinux.org/alpine/v3.10/main: IO ERROR WARNING: Ignoring APKINDEX.00740ba1.tar.gz: No such file or directory fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/community/x86_64/APKINDEX.tar.gz ERROR: http://dl-cdn.alpinelinux.org/alpine/v3.10/community: IO ERROR WARNING: Ignoring APKINDEX.d8b2a6f4.tar.gz: No such file or directory Getting the above error, is that related to OS, as the it is Alpine Linux. How to fix it the error? -
Django. 301 Redirect from old URL to new
Hello! Please tell me how to organize a redirect correctly. There is an old version of the site and a new one. In the old version (another CMS, not Django) the objects have their own URL, in the new revised scheme, and the objects have a different URL. In each object on the new site, there is a completed field with the old URL. In model.py it looks like this: old_url = models.CharField('Old URL', blank=True, max_length=100) I specifically moved the old url to a separate field. Or was it not necessary to do this? Question. How to set up a redirect correctly, so that after going to the object using the old URL, the site visitor will be redirected to the new URL of this object? -
Auto increment field in context of foreign key
I am writing as an (personal) exercise a little Issue tracker in django. I want to have for a model an integer field that is unique (auto incremented), but not for the whole model/table but in the context of a related model. class Parent(models.Model): name = models.CharField(max_length=10) class Child(models.Model): parent = models.ForeignKey(Parent, models.CASCADE) identifier = models.IntegerField() The goal is to have a parent classes with the names "ABC" and "XYZ". Now i want to create multiple instances of child classes and the identifiers should more or less auto increment in the context of the Parent class. Instance #1: parent is "ABC" -> identifier = 1 Instance #2: parent is "ABC" -> identifier = 2 Instance #3: parent is "DEF" -> identifier = 1 How do i achieve this in a transaction safe manner? -
I have a proble with Django, whit the manage.py file
I just began with Django, I'm following the steps of a youtube tutorial, but when I want to run this command: python manage.py runserver This is the error message: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03E82780> Traceback (most recent call last): File "D:\Personal\Dev\cfehome\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "D:\Personal\Dev\cfehome\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "D:\Personal\Dev\cfehome\lib\site-packages\django\utils\autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "D:\Personal\Dev\cfehome\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "D:\Personal\Dev\cfehome\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "D:\Personal\Dev\cfehome\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "D:\Personal\Dev\cfehome\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "D:\Personal\Dev\cfehome\lib\site-packages\django\apps\config.py", line 94, in create module = import_module(entry) File "D:\Personal\Dev\cfehome\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\Personal\Dev\cfehome\lib\site-packages\django\contrib\admin\__init__.py", line 4, in <module> from django.contrib.admin.filters import ( File "D:\Personal\Dev\cfehome\lib\site-packages\django\contrib\admin\filters.py", line 10, in <module> from django.contrib.admin.options import IncorrectLookupParameters File "D:\Personal\Dev\cfehome\lib\site-packages\django\contrib\admin\options.py", line 12, in <module> from django.contrib.admin import helpers, widgets File "D:\Personal\Dev\cfehome\lib\site-packages\django\contrib\admin\widgets.py", line 151 '%s=%s' % (k, v) for k, … -
400 Bad Request from Axios to Django, field is required
I'm trying to send a POST request from my React frontend using Axios import axios from 'axios' axios.post('http://server:port/auth/login', { username: 'admin', password: 'MY_PASSWORD', }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } }) .then(response => { console.log(response) }) .catch(error => { console.log(error.response) }); No matter what I do, I get a 400 Bad Request in response stating: "username":[This field is required], "password":[This field is required] I am using the Django REST framework in my Django Backend for authentication. Everything works fine using Insomnia but any requests through React results in a "Bad Request" django-cors-headers has been installed and configured as well. -
How to list Models in the django shell?
Say i have a simple model: class NewsFeed(models.Model): title = models.CharField(max_length=50) tags = models.TextField() def __str__(self) return self.title I have 50 entries and I want to display all the different tags field for each News Feed uniquely on the shell, how can i do so (bearing in mind the tags field isn't unique by default)? If i import the models and objects.all it, it simply displays the objects themself -
Translating a PHP project to Django framework
I'm a PHP developer and I'm very new to Django. I am stuck and don't know where else to turn to. I am trying to translate a program I developed in PHP into Django. So many aspects are working well, but I'm stick particular where I'm trying to display quizzes from a database. There is a database table called "table_assessment". It contains accessmemts. There is another table called "table_scores". Assessments are only sent to the database of the score is => 80%. That's the same exact thing I'm trying to implement in Django. My primary area of interest is the aspect where I get questions, options and answers all from one table, and update another table if the user scores =>80% Please help me out. My PHP code looks like this: <form id="form_assessment" rol="form" method="post" action='<?php echo $_SERVER["PHP_SELF"]."?assessment_id=".$assessment_id; ?>'> <?php $ql=mysqli_query($conn, "SELECT * from table_assessment where course_id ='".$assessment_id."'"); $count=0; while($row=mysqli_fetch_array($ql,MYSQLI_ASSOC)){ $count++; echo "<p>".$row["assessment_content"]."</p>"; echo "<ul style='list-style-type:none; required'>"; echo '<li><input type="radio" name="r_'.$count.'" value="a"/> '.$row["option_a"].'</li>'; echo '<li><input type="radio" name="r_'.$count.'" value="b"/> '.$row["option_b"].'</li>'; echo '<li><input type="radio" name="r_'.$count.'" value="c"/> '.$row["option_c"].'</li>'; echo '<li><input type="radio" name="r_'.$count.'" value="d"/> '.$row["option_d"].'</li>'; echo "</ul>"; } ?> <div> <input type="submit" id="btn_assessment" name="btn_assessment" class="btn btn-success" value="FINISH"> </div> </form> This checks to see if … -
Graphene Django mutation returning object with subobjects fails
When I execute a mutation (with SerializerMutation) and return the created object, the response contains an AssertionError that states User Error: expected iterable, but did not find one for field CreateTableMutationPayload.footSet The issue is in executor.py complete_list_value that checks that the footSet is an iterable. It is in fact a RelatedManager, which is not iterable as is. Normally, you'd just do a table.foot_set.all() to get the iterable. I find it stange that it is working fine in Queries but not Mutations. I created a sample project to illustrate this. I have a pretty simple model of Table with several Foot. Both objects are exposed with Relay and this works great. Querying: { tables { edges { node { id, name, height footSet { edges { node { id, number, style } } } } } } } } returns: { "data": { "tables": { "edges": [ { "node": { "id": "VGFibGVOb2RlOjE=", "name": "test1", "height": 11, "footSet": { "edges": [ { "node": { "id": "Rm9vdE5vZGU6MQ==", "number": 1, "style": "plain" } }, { "node": { "id": "Rm9vdE5vZGU6Mg==", "number": 2, "style": "Almost plain" } } ] } } } ] } } } But a mutation: mutation { createTable(input: { name:"test3" height: 60 …