Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django rest framework an always sorting field
I want to have a fixed sorting field applied to all custom sortings. To be more specific imagine we have a list of employees, if user choose this form be sorted by hire_date, I want the result be sorted by hire_date and employee_id together. I mean each ordering should be ordered by employee_id inside! For example if we have 5 employees hired today, if hire_date is the sorting field, these 5 be sorted by employee_id and for the other days the same story. using the following is not the cure. It only sorts them on employee_id when no ordering is set: queryset = models.Employee.objects.order_by('id') And this one's result is same as previous: filter_backends = (CustomFilterSetBackend, filters.OrderingFilter) custom_filters = ( ........ ) ordering_fields = (............) ordering = ('id',) tnx a million -
Django 2: TemplateDoesNotExist even if files placed properly
I have encountered interesting problem on Django 2. In my settings.py I have written this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] After that I have created folder templates in my projects root folder. Then I have created app with name front and added it into my settings.py INSTALLED_APPS: Inside my views.py I have added this view: def index(request): return render(request, 'front/index') I have assigned its url like this: url(r'^$', views.index, name='index'), When I'm trying to access to this view I get this error: TemplateDoesNotExist at / front/index Why this happening? Did I miss something? -
Django request URL gets appended
i visit admin interface and try to add support user in django.its a form with user name and email. the form data is posted successfully. after successful post request i have to redirect to 127.0.0.1:8000/admin/auth/user/. however at 127.0.0.1:8000/add_support_user if user exists already,url is changed like this 127.0.0.1:8000/add_support_user/add_support_user and again i make request if user already exists its like this 127.0.0.1:8000/add_support_user/add_support_user/add_support_user(gets appended every time) support_User_form and when new user is created url is changed like this 127.0.0.1:8000/add_support_user/add_support_user so it shows 500 error page that '127.0.0.1:8000/add_support_user/add_support_user' doesnt exists error_page. what mistake am i making here? URLS.PY url(r"^add_support_user/", AddSupportUserView.as_view(), name = 'support_user'), VIEWS.PY class AddSupportUserView(CsrfExemptMixin, View): def get(self, request): form_class = AddSupportUserForm return render(request, 'add_support_user.html', { 'form': form_class, }) def post(self, request): form_class = AddSupportUserForm username = request.POST.get('username') email = request.POST.get('email') try: user_obj = User.objects.get(username=username) return render(request, 'add_support_user.html', {'errors': 'User already exits', 'form': form_class}) except User.DoesNotExist: user_obj = User.objects.create_user(username=username, email=email, is_staff=True, is_superuser=False) user_obj.set_password(email) user_obj.save() group_obj = Group.objects.get(name='support_group') user_obj.groups.add(group_obj) return HttpResponseRedirect('/admin/auth/user/') CHANGE_LIST.HTML {% extends "admin/change_list.html" %} {% block object-tools-items %} {{ block.super }} <li> <a href="{% url 'support_user' %}" class="grp-state-focus addlink">Add Support User</a> </li> {% endblock %} ADD_SUPPORT_USER.HTML {% extends 'admin/base.html' %}{% block content %} <h1>Add Support User</h1> <form role="form" action="add_support_user/" method="post"> {% csrf_token … -
haystack search not indexing multivaluefield django
I am trying to use manytomanyfield for fetch searching but when I am trying to update index, it shows no attribute error #search_index.py class ProductCreateModelIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True,template_name='search/indexes/catalogue/product_text.txt') user = indexes.CharField(model_attr='user',faceted=True ) title = indexes.EdgeNgramField(model_attr='title') description = indexes.CharField(model_attr='description',null = True) category = indexes.CharField(model_attr='category',faceted=True ) brand = indexes.CharField(model_attr='brand_name',faceted=True ) availability_regions = indexes.MultiValueField(faceted=True ) model = indexes.EdgeNgramField(model_attr='model_name',null = True) def prepare_availability_regions(self, obj): return [ availability_regions.name for a in obj.availability_regions_set.all()] when I am trying to update it shows me this return [ availability_regions.name for a in obj.availability_regions_set.all()] AttributeError: 'ProductCreateModel' object has no attribute 'availability_regions_set' here is my product_text.txt {{object.title}} {% for a in availability_regions %} {{ a }} {% endfor %} {{object.category}} {{object.model_name}} {{object.brand_name}} {{ object.description|default:"" }} I just follow the tutoria, I don't know how to do it in right way, would you tell me the right way to do it and where can i find the documentation of this ? -
Django 1.11 - xadmin app, charts widget parameters
I'm using the xadmin app, specifically trying to work with the included charts plugin. How do I start adding data from my database / models into the chart? The official xadmin documentation is incomplete. I have looked through the Django docs regarding widgets and plugins, but they weren't useful for determining how this specific implementation works. Can someone help point me in the right direction - I want to start adding parameters, so is there an explanation somewhere covering how this might be done? These are the default parameters - so it's picking up the response model belonging to my survey app, and I'd like to start populating it with data from my model / database. Example of model fields in my Survey app: class Response(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) survey = models.ForeignKey(Survey, related_name="responses") user = models.ForeignKey(User, null=True, blank=True) interview_uuid = models.CharField(_(u"Interview unique identifier"), max_length=36) class Answer(models.Model): question = models.ForeignKey(Question, related_name="answers") response = models.ForeignKey(Response, related_name="answers") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) body = models.TextField(blank=True, null=True) @property def values(self): if len(self.body) < 3 or self.body[0:3] != "[u'": return [self.body] values = [] raw_values = self.body.split("', u'") nb_values = len(raw_values) for i, value in enumerate(raw_values): if i == 0: value … -
How to print a HttpResponse in a while loop and then append onto it for each loop?
Okay so I have this view: def fight(request): monster = Monster.objects.get(pk=request.POST['monster']) user = Profile.objects.get(pk=2) while monster.health > 0 and user.health > 0: monsterattack = random.randint(monster.minattack, monster.maxattack) userattack = random.randint(user.attack*.75, user.attack*1.5) user.health = user.health - monsterattack monster.health = monster.health - userattack HttpResponse('Player attacked for: %s\n Monster attacked for: %s\n' % (userattack, monsterattack)) return HttpResponse('You are fighting %s\n Player Health: %s \n Monsters Health: %s' % (monster.name, user.health, monster.health)) I was wondering if there was a way that i could have the first HttpResponse print to the template every time it looped and then have the second while loop print after the while loop has finished. -
Django API : Create Serializer Issue
I'm working on my Django web application and I'm beginning API part. I have a Create Serializer class like this : class IndividuCreateSerializer(serializers.ModelSerializer) : class Meta : model = Individu fields = [ 'Etat', 'Civilite', 'Nom', 'Prenom', 'Sexe', 'Statut', 'DateNaissance', 'VilleNaissance', 'PaysNaissance', 'Nationalite1', 'Nationalite2', 'Profession', 'Adresse', 'Ville', 'Zip', 'Pays', 'Mail', 'Telephone', 'Image', 'CarteIdentite', ] def create(self, validated_data): obj = Individu.objects.create(**validated_data) IdentityIndividuResumeView.get_context_data(obj.id) return obj In this class, I have my create function which should redirect to IdentityIndividuResumeView class when my person is created. class IdentityIndividuResumeView(LoginRequiredMixin, TemplateView) : template_name = 'Identity_Individu_Resume.html' model = Individu def get_context_data(self, **kwargs) : context_data = super(IdentityIndividuResumeView, self).get_context_data(**kwargs) id = self.kwargs['id'] personne = get_object_or_404(Individu, pk=id) NIU = lib.Individu_Recherche.NIUGeneratorIndividu(personne) personne.NumeroIdentification = NIU ... But I don't overcome to pass argument in my function get_context_data. I'm getting this issue : File "/Users/valentin/Desktop/Identity/api/serializers.py" in create 80. IdentityIndividuResumeView.get_context_data(obj.id) File "/Users/valentin/Desktop/Identity/views.py" in get_context_data 228. context_data = super(IdentityIndividuResumeView, self).get_context_data(**kwargs) Exception Type: TypeError at /Api/Identification/create/ Exception Value: super(type, obj): obj must be an instance or subtype of type -
Django Delete CBV with confirmation pop-up and multiple success url
In my case, an instance Model can be delete from: a ListView inherited View a DetailView inherited View By default, when a delete view is called: the get function calls 'confirm_delete' template. Instead I want a pop-up/modal to appear, and if delete is clicked in the modal will delete the object if the delete operation is on a ListView, after delete the user will remain on ListView and the ListView content will be updated if the delete operation is on a DetailView, after delete the user will be redirected to the ListView or another page(depending on other rules) -- So I want to know how to do Ajax calls on delete, how to have conditional success urls in delete, based of where I am before the action. -
How to integrate django apps with trac and vice versa? Is there any possibilities for that..?
Integration of trac and Django frameworls. To use the auth used in trac in django and intergrate their apps and plugins. -
Django Python - adding value to TimeField
I'm creating a basic model through the Django framework in Python, which demonstrates an offer on a product which will expire after 3 hours. This is my current model: class Offers(models.Model): product_id = models.CharField(max_length=10) original_price = models.CharField(max_length=5) discounted_price = models.CharField(max_length=5) offer_started = models.TimeField(auto_now_add=True, blank=True) offer_expires = ????????? (NB: The date is not important, which is why I have used a TimeField). Is there a simple way to automatically set the "offer_expires" field to 3 hours after the time in the "offer_started" field? Or if not linked to this field directly, the time that the entry is added? Many thanks! -
"Backend not found" django social auth
When I'm trying process social authorization with Google or Facebook, I get this error without trace for both socials. [Backend not found][1] Someone can find an mistake in social_django settings? settings INSTALLED_APPS = [ ... 'social_django', ... ] MIDDLEWARE_CLASSES = [ ... 'social_django.middleware.SocialAuthExceptionMiddleware' ] TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ... 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] AUTHENTICATON_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.google.GoogleOAuth2', 'users.backends.AuthBackend', ) SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_FACEBOOK_KEY = '...' SOCIAL_AUTH_FACEBOOK_SECRET = '...' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY ='...' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '...' urls.py urlpatterns = [ url('', include('social_django.urls', namespace='social')), ... ] template <a href="{% url 'social:begin' backend='google-oauth2' %}">FB</a> <a href="{% url 'social:begin' backend='facebook' %}">GOOGLE</a migrations all OK Applying social_django.0001_initial... OK Applying social_django.0002_add_related_name... OK Applying social_django.0003_alter_email_max_length... OK Applying social_django.0004_auto_20160423_0400... OK Applying social_django.0005_auto_20160727_2333... OK Applying social_django.0006_partial... OK Applying social_django.0007_code_timestamp... OK Applying social_django.0008_partial_timestamp... OK -
__get__() method without owner, instance parameters DJANGO
Quick question about something I am struggling with. Reading the Python-documentation, __get__ is defined with the necessary parameters: object.__get__(self, instance, owner) I am currently learning about writing custom middleware within Django. In the official Django documentation, an example of a middleware-class has a method: def __call__(self, request): How is this possible? How can the middleware- __call__ take request and skip instance and owner? Thank you! -
Django strange SlugField validation, error not raised before clean()
django 2.0 I have a django model, with a slug as primary key from django.core.validators import validate_slug class MyModel(models.Model): # with slug field alias = models.SlugField(max_length=200, primary_key=True, unique=True) # or charfield with slug validator (should be exactly the same) alias = models.CharField(max_length=200, primary_key=True, unique=True, validators=[validate_slug]) The problem i have, in my form i have a clean method, to validate the values of multiple fields, not individually. This method should theoretically be called after the clean_fields method, but with the SlugField, it seems the field validation is not raised before the form's clean() method. My forms.py: class MyForm(forms.ModelForm): class Meta: model = MyModel fields = '__all__' def clean(): cleaned_data = super().clean() cleaned_data['alias'] # key error with SlugField return cleaned_data To resume, with the CharField with validate_slug, everything works as intented, validation error is raised in my form, before the clean() method But with SlugField, the validation error is not raised and i got a key error because the field is missing, because not valid, even if the exception was not raised. To trigger the validation error i use accented characters, 'ééé', but allow_unicode is set to False by default. -
"SignatureDoesNotMatch" error when trying to connect AWS S3 storage to Django
I've gone through this tutorial to implement AWS S3 storage to my django project. I've completed everything up until the very final step where it says to run python manage.py collectstatic. When I perform python manage.py collectstatic it says: You have requested to collect static files at the destination location as specified in your settings. This will overwrite existing files! Are you sure you want to do this? I say yes and then it returns: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/james/postr/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/james/postr/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/james/postr/env/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/james/postr/env/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/james/postr/env/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 199, in handle collected = self.collect() File "/home/james/postr/env/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 124, in collect handler(path, prefixed_path, storage) File "/home/james/postr/env/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 354, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/home/james/postr/env/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 260, in delete_file if self.storage.exists(prefixed_path): File "/home/james/postr/env/lib/python3.5/site-packages/storages/backends/s3boto3.py", line 475, in exists if self.entries: File "/home/james/postr/env/lib/python3.5/site-packages/storages/backends/s3boto3.py", line 290, in entries for entry in self.bucket.objects.filter(Prefix=self.location) File "/home/james/postr/env/lib/python3.5/site-packages/storages/backends/s3boto3.py", line 288, in <dictcomp> self._entries = { File "/home/james/postr/env/lib/python3.5/site-packages/boto3/resources/collection.py", line 83, in __iter__ for page in self.pages(): File "/home/james/postr/env/lib/python3.5/site-packages/boto3/resources/collection.py", line 166, in pages for … -
Error when I creating django application in visual studio
When I create a django application in VS and I press the project name (in the solution expoler) -> python -> django create supreser (=> 1.7) there is such an error - Traceback (most recent call last): File "путь к проекту\manage.py", line 15, in from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The interactive Python process has exited. The interactive Python process has exited. and when I start the project - ModuleNotFoundError: No module named 'django' points to the string - from django.core.management import execute_from_command_line Although both python and django, the latest version is installed. Why is that? -
Advanced Django: validators within the model? UUID Field?
I'm tasked to develop a system that tracks how many times a certain task has been completed and which it was. The user who gives the tasks should be able to choose dynamically how many times that task should be completed. I think if you read the 'pseudo'-models you will understand: class Taskoverview(models.model): user = models.Foreignkey(User, related_name = 'taskoverviews') company = models.Foreignkey(Company, related_name = 'taskoverviews') limit = models.PositiveSmallIntegerField(default=5) done = models.PositiveSmallIntegerField(default=0) uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) class Task(models.model): taskoverview = models.Foreignkey(Taskoverview, related_name = 'tasks') category = models.CharField(max_length = 120) worth = models.PositiveSmallIntegerField(default=1) uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) In this example the limit declares how many tasks should be done and the done counter counts how many tasks have been done. I want to know: How can I do it, so that each 'worth' of task is allways one? Meaning that a task can't be made where worth is two? How can I ensure that a task can't be assigned to a taskoverview, if it would increase it's 'done'-counter to more that the 'limit'? How can I ensure the UUID is allways 32 digits long? Is there any method to set the first two digits of the UUID manually? Meaning can … -
Connecting Django to Hive
My requirement is to display few of Hive table data (aggregated value) in front-end once the user clicks on certain links. After searching the net felt Django framework would suit the need and tried to build the app, with just the standalone python script am able to access hive data and print in IDLE shell, however I am not sure how to fetch and display the same data using Django, searching till now has resulted in methods to connect to oracle (here), MongoDB (here) and MySQL (here), code to connect to hive as below, wanted the result of this to be printed in front-end: from impala.dbapi import connect import pandas as pd #PROD conn = connect(host='xxxxxx', port=yyyyy, auth_mechanism='PLAIN', user="rrrrrr", password="tttttt") #Enter your query here query = "select * from table1 limit 5" print('connected') cur = conn.cursor() try: cur.execute(query) names = [ x[0] for x in cur.description] rows = cur.fetchmany(1000) for row in rows: print (row) -
Do we also create content char field in models. I want to know the standard practice
New to Django and web development in general. For a blog post I understand we create model fields for author, publish date, title, category etc.My question is do we also create content char field or some other field in models for the content. I want to know the standard practice. I don't want the content to be purely restricted to the text I also want it to include images, embedded videos etc. is it possible to achieve this within the admin panel? -
call_command makemigrations does not work on EBS
I have a scenario, where I need to create a table dynamically, To create the table dynamically I have written code to create a model.py file with the table content that I want to create. Once this file get created then I want to perform the makemigrations command from the code itself like from django.core.management import call_command call_command('makemigrations') call_command('migrate') it is working fine in my local as well in AWS EC2 instance, but it is not working into the Elastic Beanstalk (eb). and when I'm trying to run the makemigrations command manually from the eb ssh then it gives me the following error. PermissionError: [Errno 13] Permission denied: '/opt/python/bundle/47/app/quotations/migrations/0036_dynamic_table.py' Anyone have any idea how can I handle this situation. One Other thing is that as I'm creating new dynamic models So how can I push that code to the git, as on new deployment EBS will replace the existing code to new code, so in this way I will lose the files that I created in EBS using these commands Thanks -
from django.shortcuts import reverse ImportError: cannot import name 'reverse'
I am getting this error: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f78dfe090d0> Traceback (most recent call last): File "/webapps/onehyr/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/webapps/onehyr/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/webapps/onehyr/lib/python3.6/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/webapps/onehyr/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/webapps/onehyr/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/webapps/onehyr/lib/python3.6/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/webapps/onehyr/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/webapps/onehyr/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/webapps/onehyr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/webapps/onehyr/ladislist/blog/models.py", line 5, in <module> from django.shortcuts import reverse ImportError: cannot import name 'reverse' Here are my imports in model.py from django.contrib.auth.models import User from django.db import models from django.shortcuts import reverse from django.utils import timezone, html from django.utils.safestring import mark_safe Django version is 2.0.1 It was all working perfectly until I installed django-grappelli. Now even after uninstalling it, I still face the same issue. Like … -
User Model Serializer required Validation Error
I want to create a registration app for my project. Here is my serializer: from rest_framework import serializers from rest_framework.validators import UniqueValidator from django.contrib.auth.models import User from rest_framework import serializers from django.contrib.auth import get_user_model # If used custom user model UserModel = get_user_model() class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) def create(self, validated_data): user = UserModel.objects.create( username=validated_data['username'], email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name'] ) user.set_password(validated_data['password']) return user class Meta: model = User fields = ('id', 'username', 'password','email','first_name','last_name') write_only_fields = ('password',) read_only_fields = ('id',) As you see, I use UserModel which is one of the default models of rest_framework. I want to make first_name field required for my registration serializer. Waiting for your help. -
include does not work in a template on live instance in django 1.11
I work with django 1.11 and I have a problem with include at base.html. When I work on localhost - everything is OK. The problem starts when the code goes live, on the server. The problem is here: {% include "pages/menu.html" %} -
How to perform .delete() queryset in Django in a ListView?
Here is what I've done so far: 1.) I've made a javascript function that gets all the id's of the items (using checkbox select) in the database like so (this is DataTables): function () { // count check used for checking selected items. var count = table.rows( { selected: true } ).count(); // Count check. // Count must be greater than 0 to delete an item. // if count <= 0, delete functionality won't continue. if (count > 0) { var data = table.rows( { selected: true } ).data(); var list = []; for (var i=0; i < data.length ;i++){ // alert(data[i][2]); list.push(data[i][2]); } var sData = list.join(); // alert(sData) document.getElementById('delete_items_list').value = sData; } } It outputs something like 1,2,5,7 depending on what rows I have selected. 2.) Passed the values inside a <input type="hidden">. Now, I've read a post that says you can delete data in Django database using a checkbox, but I'm not sure how exactly can I use this. I'm guessing I should put it in the ListView that I made, but how can I do that when I click the "Delete selected items" button, I can follow this answer? I'm trying to achieve what Django Admin … -
Django - Dictionary errors when saving multiple selection boxes in one form
I need to save multiple selections in one form, but I keep getting a MultiValueDictKeyError. This is how the form looks: This is my models.py class ChoiceManager(models.Manager): def rates (self, Assignment_id, rating, year): assignment = assignment.objects.get(assignment=Assignment_id) yo = year rate = rating rated = Choice.create( assignment = assignment, fy = year, rating = rating ) class Choice(models.Model): rating = models.ForeignKey(Rating, related_name="picks") year = models.ForeignKey(FiscalYear, related_name="choices") assignment = models.ForeignKey(Assignment, related_name="choice") objects = ChoiceManager() This is my views.py def task_rating(request, Assignment_id): rates = Choice.objects.rates(Assignment_id,request.POST['rating'], request.POST['year']) return redirect ((reverse('Project:assignment_page', kwargs={'Assignment_id': Assignment_id}))) HTML <div> <ul> <form action="{% url 'Project:task_rating' Assignment_id=tasks.id %}" method'POST'> {% for year in years %} <li class=cap_select> <div id=fyc>{{year.fy_year}}</div> <select name="rating"> <option>Choose From List</option> {% for cap in caps %} <option value="{{cap.rating}}">{{cap.rating}}</option> {% endfor %} </select> <input type="hidden" name="year" value={{year.fy_year}}> </li> {% endfor %} <br> <input id=save_cap type="submit" value="Save"> </form> </ul> </div> How can I save the rating for each year? -
Serializing wagtail image chooser
I didn't find information about that. And I'am not sure if it possible to do. So i have following Page models and their relationships: class TeamRooster(Page): team_logo = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) @register_snippet class GroupstageTournamentModel(ClusterableModel): team_1 = models.ForeignKey( TeamRooster, null=True, verbose_name='Erste Team', on_delete=models.SET_NULL, related_name="+", ) class GroupstageScreencastRelationship(Orderable, models.Model): page = ParentalKey('ScreencastPage', related_name='groupstage_screencast_relationship') match = models.ForeignKey('GroupstageTournamentModel', related_name='match_screen_relationship') panels = [ SnippetChooserPanel('match') ] class ScreencastPage(Page): content_panels = Page.content_panels + [ InlinePanel( 'groupstage_screencast_relationship', label="Choose Teams" ] def matches(self): matches = [ n.match for n in self.groupstage_screencast_relationship.all() ] return matches def serve(self, request): if request.is_ajax(): result = [ { 'team_2_logo': match.team_2.team_logo } for match in self.matches() ] json_output = json.dumps(result) return HttpResponse(json_output) else: return super(ScreencastPage, self).serve(request) Is it possible to get a picture from the TeamRooster model with an ajax request? If I try to do this as shown in the code above, then I get an error: TypeError: Object of type 'Image' is not JSON serializable