Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the fields with checkbox tick in django(Boolean Field)
My template: I want to get the data which are tick marked and then render it to other view. <form class="hero-menu"> {% for test in test %} <div class="category-block"> <ul class="dropdown-list"> <li> <a href="#"><h4 data-modal-target="menu-test-popup"> {{test.name|title}} </h4></a> </li> {% for subtest in test.subtest.all %} <!-- {% if subtest.test_id == test.id %} --> <li> <div class="checkbox-group"> <input type="checkbox" id="aUniqueName" name={{subtest.name}} value="example"/> <label for="aUniqueName"> {{subtest.name|title}} </label> </div> </li> <!-- {% endif %} --> {% endfor %} </ul> </div> {% endfor %} <button class="button">Generate Report</button> </form> This is my models.In my models I have Test which has foreign key at subtest. class Test(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Subtest(models.Model): name = models.CharField(max_length=100) test = models.ForeignKey(Test,on_delete=models.CASCADE,related_name='subtest',blank=True, null=True) unit = models.CharField(max_length=10) reference_value = models.IntegerField() selected = models.BooleanField(default=False) def __str__(self): return self.name This is my view. I have used template_context_processor for my covinience. def list_subtest(request): return {'subtest':Subtest.objects.all(),'test':Test.objects.all().prefetch_related('subtest')} -
Pagination doesn't works on my Django App as expected
I'm trying to paginate, it shows in the address bar that I'm on page 2 but nothing new gets displayed. Below is an excerpt from my views.py looks: class JobList(ListView): model = Job template_name = "jobs/job_listings.html" context_object_name = "job_list" ordering = ['-published_date'] paginate_by = 3 def get_context_data(self, **kwargs): context = super(JobList, self).get_context_data(**kwargs) jobs_expiring_soon = Job.objects.filter(application_last_date__gte=datetime.now(), application_last_date__lte=lookup_date) state_list = State.objects.order_by('name') profession_list = Profession.objects.order_by('name') context['jobs_expiring_soon'] = jobs_expiring_soon context['state_list'] = state_list context['profession_list'] = profession_list return context Below is an excerpt from my urls.py file: path('', JobList.as_view(), name = 'job-list'), Below is the associated template: {% extends 'base.html' %} {% block page_content %} {% for job in job_list %} <div class="listing-wrapper"> <div class="listing-container border-top border-bottom"> <a href="{{ job.get_absolute_url }}"> <h2 class="heading mt-3 mb-1 mx-2 d-inline-block">{{ job.title|truncatechars:75 }}</h2> <p class="mx-2"><span class="sub-heading mr-1">Number of Posts:</span><span class="mr-1 ml-1">{{ job.nop }}</span>|<span class="sub-heading ml-1 mr-1">Last Date to Apply:</span><span>{{ job.application_last_date|date:"j-M-Y" }}</span></p> <p class="mx-2 mb-3">{{ job.summary|truncatechars:200 }}</p> </a> </div> </div> {% endfor %} {% if is_paginated %} <ul class="pagination justify-content-center my-4"> {% if page_obj.has_previous %} <li class="page-item"> <a class="page-link bg-dark text-white" href="?page{{ page_obj.previous_page_number }}">&larr; Previous Page</a> </li> {% endif %} {% if page_obj.has_next %} <li class="page-item"> <a class="page-link bg-dark text-white" href="?page{{ page_obj.next_page_number }}">Next Page &rarr;</a> </li> {% endif %} </ul> {% … -
data id iteration django
I really do not know how to iterate through my loop to display individual items. I have tried to rearrange the loop but has worked. The data id id="portfolioModal" is what I want to also iterate for individual items. {% for subjects in object %} <div class="col-lg-8"> <!-- Portfolio Modal - Title --> <h2 class="portfolio-modal-title text-success text-uppercase mb-0">{{subjects.title}}</h2> <!-- Icon Divider --> <div class="divider-custom"> <div class="divider-custom-line"></div> <div class="divider-custom-icon"> <i class="fas fa-star"></i> </div> <div class="divider-custom-line"></div> </div> <!-- Portfolio Modal - Image --> <img class="img-fluid rounded-circle mb-5" src=" {{subjects.img.url}}" alt=""> <!-- Portfolio Modal - Text --> <p>{{subjects.desc}}</p> <button class="btn btn-danger" href="#" data-dismiss="modal"> <i class="fas fa-times fa-fw"></i> Close Window </button> </div> </div> </div> </div> </div> </div> </div> {% endfor %} -
process_template_response doesn't get called
In views.py I use render() . In app -> middleware.py I have this code: from django.conf import settings class NoTrackingMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_template_response(self, request, response): no_tracking = True if request.GET.get("NO_TRACKING", default=False) is not False else False pub_id = "PUBLISHER_TEST" if no_tracking is True else settings.WFF_PUB_ID response.context_data["no_tracking"] = no_tracking response.context_data["pub_id"] = pub_id return response In settings.py I have: MIDDLEWARE = [ ... 'app.middleware.NoTrackingMiddleware', ] Yet if I place a breakpoint at process_template_response it gets ignored and pub_id is always empty. Why? -
Comparing JSONFields in Django
If two models both have JSONFields, is there a way to match one against the other? Say I have two models: Crabadoodle(Model): classification = CharField() metadata = JSONField() Glibotz(Model): rating = IntegerField() metadata = JSONField() If I have a Crabadoodle and want to fetch all the Glibotz objects with identical metadata fields, how would I go about that? If I know specific contents, I can filter simple enough, but how do you go about matching on the whole field? -
how to get Json response formatted differently on django
I have a custom user model and i implemented a user following and follower system that works well. But the problem I have is that when I request for the followers a particular user has, the JSON response I get is not exactly the way I want it returned. more details below models class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=250) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=255, unique=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] class FollowLog(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='followers') followed_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='following', null=True) followed_on = models.DateTimeField(auto_now_add=True) status = models.CharField(choices=FOLLOW_STATUS, default=FollowStatus.following.value, max_length=30) updated_on = models.DateTimeField(auto_now=True) unfollowed_on = models.DateTimeField(null=True) blocked_on = models.DateTimeField(null=True) serializer class FollowerSerializer(serializers.ModelSerializer): ''' Allows people to view follower of a user ''' followed_by = serializers.SlugRelatedField(read_only=True, slug_field='slug') class Meta: model = FollowLog fields = ('followed_by',) read_only_fields = ('followed_by',) view class UserFollowerView(APIView): ''' Gets all the followers to a user ''' permission_classes = [AllowAny] def get(self, request, slug): user = User.objects.get(slug=slug) followers = user.followers.all().filter(status='following').order_by("-followed_on") serializer = FollowerSerializer(followers, many=True) return Response(serializer.data, status=status.HTTP_200_OK) when I run the above, I get the appropriate response but in this format JSON response I … -
allauth unverified email remains unverified once verification email expires
I have a custom user model. and I use Django rest auth. the problem is that after sign up when the email is sent. if the user doesn't verify the email before it expires, it seems that it remains stuck like that indefinitely. I was expecting the verification email to be sent again or the user with his email to be deleted but that doesn't happen. I am lost as to what else to do and I can't seem to find any resource that helps. below is my model models.py class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=250) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=255, unique=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] in my settings.py the user has an expiry date of 2 days ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 2 ACCOUNT_EMAIL_VERIFICATION = "mandatory" -
Post Dynamic form data using Vue and Django
I am using Vue js to post data from a regular .html form to Django. Been using python and Django for a few days now. There is a section of my form which contains an area that allows the user to dynamically add form fields(regular inputs and file uploads). I increment name value by using the index everytime the user adds another row. I am not sure how to go about storing these form data. HTML .... <table class="table" id="documentsTable"> <thead> <tr> <th>Type</th> <th>Number</th> <th>File</th> <th>Expiry Date</th> <th></th> </tr> </thead> <tbody> <tr v-for="(required_document, doc_index) in required_documents" :key="doc_index"> <td> <select :name="`type${doc_index}`" class="form-control" :ref="`type${doc_index}`"> <option :value="index" v-for="(document_type, index) in document_types">[[document_type]]</option> </select> </td> <td> <input type="text" :name="`number${doc_index}`" class="form-control" :ref="`number${doc_index}`"> </td> <td> <input type="file" :name="`file${doc_index}`" class="form-control" :ref="`file${doc_index}`"> </td> <td> <input type="date" :name="`date_expiry${doc_index}`" class="form-control" :ref="`date_expiry${doc_index}`"> </td> <td> <button class="btn btn-danger delete-row" @click.prevent="removeRow(doc_index)"><i class="pe-7s-trash"></i></button> </td> </tr> </tbody> </table> ....Vue Section ... save() { form = document.getElementById('individualForm'); var formData = new FormData(form); axios.post('/customers/individual/store', formData).then((response) => { }).catch((errors) => { console.log(errors) }); } views.py def store_individual(request): if request.method == 'POST': individual_form = IndividualForm(request.POST) // for dynamic section required_document_form = RequiredDocumentForm(request.POST, request.FILES) forms.py class RequiredDocumentForm(forms.ModelForm): class Meta: model = RequiredDocument fields = ['type', 'number', 'file', 'date_expiry'] TYPES = (('', … -
Incompatibility between wagtail (my) django storage django-b2
I'm sure that problem is on my side. I try to make github.com/pyutil/django-b2 package (django storage, which uses official backblaze b2sdk). When I uploaded an image, it properly moved to backblaze. However it was not immediately accessible and Wagtail has failed when trying reopen the image (to create thumbnails?) I made an attempt to solve it so, that I want cache copies of media files locally in MEDIA_ROOT, for few days (and then delete local media via cron or so). This works better. Nothing fails, image is uploaded to both locations (my server MEDIA_ROOT and backblaze). The image in wagtailimages_image table has 'file' field: original_images/96ed15fd-e431-4615-9ae7-5744d4e1807f/szob2.png, which is correct relative path in backblaze and in MEDIA_ROOT too. Image is visible everywhere in Wagtail for editation (where proper backblaze url appears). However when I add it to RichTextField, it is not visible in the final page, only is rendered. This come from this place (sure, because I have changed this html tag and it has changed in the page too): wagtail/images/rich_text/init.py: def expand_db_attributes(cls, attrs): try: image = cls.get_instance(attrs) except ObjectDoesNotExist: return '<img alt="">' The get_instance seeks for a proper id but from unknown reason will fail with ObjectDoesNotExist. I was not able … -
If I pickle a string in Python myself, can unpickling it ever be dangerous?
Say we have a Postgres 12 database that has a table called MyClass that has a Text column called notes. Users have the ability to save whatever they wish in this notes field. For the purpose of this question, let's assume that they have somehow bypassed all data sanitation. Could the following lines of code ever be dangerous due to malicious text in obj.notes? import pickle # (obj is a Python3 instance of MyClass using the Django ORM, so obj.notes is always represented as a unicode string) obj = MyClass.objects.get(id=1) pickled = pickle.dumps(obj.notes) unpickled = pickle.loads(pickled) -
Is there a way to hash user ID for use in URI (path)?
Is there a way in Python (Django specifically) to build a url for a file that uses a hashed user ID? I want to use the hashed ID for file authentication. i.e compare request.user.id to the section of the file path. I’ve researched Django’s “make_password” but it seems like overkill for my need. I’ve read about os.urandom but it doesn’t sound like it can be reversed. In the end my goal is to protect user IDs from being a part of URLs, but allow for easy file access authentication/permissions. I appreciate any help. -
Problem with filtering by Title inside the category
So I have got a search page where I am getting the results for the items of chosen category. I can filter the items by title__icontains and price. I would like to list all the item titles of chosen category and be able to click on them to filter the items by exact title. Here's the form filtering for title_icontains, search.html : <form method="GET" action="{% url 'core:category_search' category.id %}"> <h5>Search</h5> <div class="form-row"> <div class="form-group col-8"> <div class="input-group"> <input class="form-control py-2 border-right-0 border" type="search" name="q" placeholder="Brand.."> <span class="input-group-append"> <div class="input-group-text bg-transparent"> <i class="fa fa-search"></i> </div> </span> </div> </div> </div> <button type="submit" class="btn btn-outline-primary btn-md">Search</button> </form> and below that inside the same template : <ul> {% for item in item_list %} <li> <a href="{% url 'core:title_search' title=item.title %}"> {{ item.title }} </a> </li> {% endfor %} </ul> views.py - SearchView SearchView(request, category_id=None): if category_id: category = Category.objects.get(pk=category_id) item_list = Item.objects.filter(category__id=category_id) else: item_list = Item.objects.all() query = request.GET.get('q') if query: item_list = item_list.filter(title__icontains=query) price_from = request.GET.get('price_from') price_to = request.GET.get('price_to') item_list = item_list.annotate( current_price=Coalesce('discount_price', 'price')) if price_from: item_list = item_list.filter(current_price__gte=price_from) if price_to: item_list = item_list.filter(current_price__lte=price_to) context = { 'item_list': item_list, 'category': category } return render(request, "search.html", context) views.py - TitleView + category_view def TitleView(request, … -
How can I use Django dynamic IDs in Ajax?
I have a Django HTML file like this: <button type="button" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" class="btn btn-primary form-control">{{ choice.choice_text }}</button> I have an Ajax .js file like this: $(document).ready(function(){ $('#choice{{ forloop.counter }}').on('click', function(){ (...) Where {{ forloop.counter }} obviously don't work. What I could use to replace it in ajax? Thank you -
Django Crispy Form Not Fitting Bootstrap Modal
I am trying to implement a bootstrap modal form in my Django project and I am attempting to use django-crispy-forms crispy_field to style the form. When I do this, everything works except the crispy fields are running much wider than the modal window. I feel like there's an easy fix here but I can't determine exactly what I'm doing wrong. Here is my html for the modal form: modal.html <form method="post" action=""> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Create new Book</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {{form.Reference_Number|as_crispy_field}} {{form.Ultimate_Consignee|as_crispy_field}} </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="submit-btn btn btn-primary">Create</button> </div> </form> -
Django Migrations Failing
I have two development machines for django projects - tower and laptop. I use a private git repo to keep the projects synchronized. I work on tower for awhile, commit the changes to my git repo (including the database), then do a git pull origin master, and git reset --hard origin/master, and then I work on the laptop when I travel. I seem to have made a mistake somewhere, as when I updated laptop as above, I have an error in my migrations. On tower, all the migrations are current and applied. On laptop, I have several migrations that cannot be applied. [X] 0044_remove_document_rotation [ ] 0041_remove_collectiondocument_position [ ] 0045_merge_20191023_1922 [X] 0045_auto_20191121_1536 [ ] 0046_merge_20200213_1523 [X] 0046_auto_20200213_1541 [ ] 0047_merge_20200213_1546 These migrations are all checked on tower. I get an error when I try to migrate on laptop: Applying memorabilia.0041_remove_collectiondocument_position...Traceback (most recent call last): File "./manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/mark/.virtualenvs/memorabilia-JSON/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/mark/.virtualenvs/memorabilia-JSON/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/mark/.virtualenvs/memorabilia-JSON/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/mark/.virtualenvs/memorabilia-JSON/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/mark/.virtualenvs/memorabilia-JSON/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/mark/.virtualenvs/memorabilia-JSON/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 233, in handle fake_initial=fake_initial, … -
Is it safe to store reset password token in html post form?
I want to add reset/forgot password functionality to my personal express.js app. I decided to implement it in similar way how Django does it. Basically, it generates unique token based on user (id, hashed password, email, last login time and current time, all mixed with unqiue password and salt). Then, user receives that token in his "reset password link". Someone explained it better than me in one of stackoverflow answers. And here is the source code of Django PasswordResetTokenGenerator class I will post my javascript implementation on the bottom. It would be nice if you check it for possible flaws, but it is not my main question :) So, user gets e-mail with "reset password link". Link looks like this https://example.com/reset-password/MQ/58ix7l-35858854f74c35d0c64a5a17bd127f71cd3ad1da, where: MQ is base64 encoded user id (1 in this example) 58ix7l is base36 encoded timestamp 35858... is actual token User clicks on link. Server receives GET request -> server checks if user with that id exist -> then server checks correctness of the token. If everything is OK, server sends user html response with "set new password" form. So far, everything was almost exactly the same how django does it (few minor differences). But now I want to … -
Django built-in user model
I'm new to Django. I would like to know, while creating a public use website like ecommerce etc, do we use django built-in user_auth_model or should create custom user model? -
Query a list with the top N elements in each group
Let's say i have two models: class Result(models.Model): b = foreignKey(ModelB) class ModelB(models.Model): code = models.CharField(...) What i need is to keep only N latest results for each modelb and delete the rest. The table ModelB and Result can really have many records. Is there a way i can perform this with django ORM without having to create a loop? -
How do I solve urlpatterns problem in django?
from django.conf.urls import url from django.contrib.auth.views import LoginView from django.contrib.auth.views import LoginView, LogoutView from . import views urlpatterns = [ url(r'^login/$', LoginView, name='login', kwargs={ 'template_name': 'accounts/login_form.html', }), url(r'^logout/$', LogoutView, name='logout', kwargs={ 'next_page': 'login', }), url(r'^signup/$', views.signup, name='signup'), url(r'^signup/$', views.signup, name='signup'), url(r'^profile/$', views.profile, name='profile'), ] enter image description here Hello I've read through other posts regarding this error and I thought I solved the problem, but I'm still having trouble. -
'Timeout when reading response headers from daemon process' [Django + Apache2 + WSGI]
I'm getting an error while deploying my project with Apache. Timeout when reading response headers from daemon process /etc/apache2/sites-available/myproject.conf <VirtualHost *:80> ServerName myproject.com ErrorLog ${APACHE_LOG_DIR}/myproject-error.log CustomLog ${APACHE_LOG_DIR}/myproject-access.log combined WSGIApplicationGroup %{GLOBAL} WSGIDaemonProcess myproject processes=2 threads=25 python-home=/svr/myproject/venv python-path=/svr/myproject WSGIProcessGroup myproject WSGIScriptAlias / /svr/myproject/myproject/wsgi.py Alias /robots.txt /svr/myproject/static/robots.txt Alias /favicon.ico /svr/myproject/static/favicon.ico Alias /static /svr/myproject/static/ Alias /media /svr/myproject/media/ <Directory /svr/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /svr/myproject/static> Require all granted </Directory> <Directory /svr/myproject/media> Require all granted </Directory> </VirtualHost> If I delete python-home=/svr/myproject/venv I get this error: ImportError: No module named django_cleanup.apps in my /var/log/apache2/myproject-error.log even though I have run pip3 install django-cleanup on my server and in my projects virtual environment. I'm also not sure if I should be leaving my virtual environment active or not.. Here is the contents of my requirements.txt incase any of these modules are causing this. requirements.txt blinker==1.3 chardet==2.3.0 cloud-init==0.7.9 configobj==5.0.6 cryptography==1.7.1 Django==2.2.10 django-autoslug==1.9.6 django-cleanup==4.0.0 idna==2.2 Jinja2==2.8 jsonpatch==1.10 jsonpointer==1.10 keyring==10.1 keyrings.alt==1.3 MarkupSafe==0.23 oauthlib==2.0.1 Pillow==7.0.0 prettytable==0.7.2 pyasn1==0.1.9 pycrypto==2.6.1 pygobject==3.22.0 PyJWT==1.4.2 pytz==2019.3 pyxdg==0.25 PyYAML==3.12 requests==2.12.4 SecretStorage==2.3.1 six==1.10.0 sqlparse==0.3.0 urllib3==1.19.1 -
"DisallowedHost" problem on docker container with digitalocean
I have a dockerized website built with django and react. I have created a docker container with nginx and gunicorn for django. Everything works fine on local, but when i deploy on the server i get this error Why is this happening ? also, it seems to be taking the settings from... i don't know, a default settings.py? i.e. My ALLOWED_HOSTS configuration, is not the same as this -
Start Django Application when NON-default databases are down
Currently, in my Django 3 application I have 2 databases defined in my settings: DATABASES = { 'default': dj_database_url.config( default='postgres://postgres:@postgres:5432/postgres', conn_max_age=int(os.getenv('POSTGRES_CONN_MAX_AGE', 600)) ), 'inventorydb': { "ENGINE": os.environ.get("INVENTORY_DB_ENGINE"), "NAME": os.environ.get("INVENTORY_DB_NAME"), "USER": os.environ.get("INVENTORY_DB_USER"), "PASSWORD": os.environ.get("INVENTORY_DB_PASSWORD"), "HOST": os.environ.get("INVENTORY_DB_HOST"), "OPTIONS": { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", } }, } My question is, how would I go about starting my application even if the inventorydb is down? I am only using that database in a read-only mode and the application is not dependant on that database. My default database handles the normal "default" stuff for auth, sessions, etc. For more clarification, I am using inventorydb to read data in and post it to a DRF API. I have appropriate models for the db, but my app will not perform any mutations on the database. If my database is down, my application should continue to work regardless of that database state. If the database is down, try to reconnect, if that fails I want to respond with an error. I can't seem to track down any information on how to do this. Any guidance would be great. Thanks! -
Filter Foreign Key Drop Down Field Django
I have 3 tables Student, K8Points, and TeacherClass . The table students tracks all student data information and you can assign them to a classroom, points tracks the points they earned for the day, classroom table is where you create the classroom names. What i want to accomplish is when you are logged in to /k8_points_classroom/1? page, there is a drop down field of students. 1 at the end of the classroom is the classroom id. The field student_name should only show the kids in that particular class, how do i filter that field ? Right now it just pulls up every student in the database. Thanks for the help . Model class TeacherClass(models.Model): class_name = models.CharField(max_length = 50, default= "") teacher_name = models.ManyToManyField(User) grade = models.CharField(max_length = 2, default= "") class Meta: verbose_name = "Teacher Class Room" def __str__(self): return self.class_name class Student(models.Model): studentpsid= models.CharField(primary_key = True , default = "", max_length = 50, unique = True) student_name = models.CharField(max_length = 50) student_grade = models.CharField(max_length = 2, default = "") home_room = models.CharField(max_length = 3, default = "") counseling_goal = models.TextField(max_length = 255) class_name = models.ManyToManyField(TeacherClass) image =models.ImageField(default ="default.png", upload_to='student_pics') class K8Points(models.Model): date = models.DateField(default=datetime.date.today) class_name = models.ForeignKey(TeacherClass, on_delete … -
django radio button ModelForm across multiple fields as values
I am using django to make a multiple choice Question Answer web app. What I have: a Model for a section: class Section(models.Model): section_type = models.CharField(max_length=100, choices=section_choices) text = models.TextField() equestions = models.ManyToManyField(Question) class Meta: app_label = "myapp" db_table = "section" managed = True A Model for Question (where i store all the questions i have made): class Question(models.Model): question_text = models.TextField() question_type = models.CharField(choices=question_type_choices, max_length=30) # MCQ Fields choice_1 = models.CharField(max_length=20, blank=True, null=True) choice_2 = models.CharField(max_length=20, blank=True, null=True) choice_3 = models.CharField(max_length=20, blank=True, null=True) choice_4 = models.CharField(max_length=20, blank=True, null=True) correct_answer = models.CharField(max_length=20, blank=True, null=True) users_answer = models.CharField(max_length=20, blank=True, null=True) marks = models.PositiveSmallIntegerField(default=2) class Meta: app_label = "myapp" db_table = "question" managed = True As you can see a question has 4 choices and they are present in choice_1, choice_2, choice_3 choice_4 What i need is a modelForm where i can display one whole section in a page with Radio button and note the responses of all the questions with a single submit button. Is this possible using forms and without using too much javascript with these models? -
Override default_manager of third party app (Django)
I am using django-address module (https://pypi.org/project/django-address/) in my project. Now I want to add get_by_natural_key method on the default manager of State model of django-address module. Before Django 1.10 I was able to do it using this code class CustomManager(models.Manager): def get_by_natural_key(self, state_name, country): country = Country.objects.get_or_create(name=country)[0] print(country) return State.objects.get_or_create(name=state_name, country=country)[0] State.add_to_class('objects', CustomManager()) State.add_to_class('_default_manager', CustomManager()) But from Django1.10, _default_manager is read-only and I am not sure how to add 'get_by_natural_key' method on default manager of model