Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-channels nginx settings
My django app uses django-channels. I was able to configure django to run using gunicorn and nginx. The app run if i use python manage.py runserver and redis-server sends notification etc but i am unable to configure it using nginx. server { listen 80; server_name 159.65.160.71; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/amir/clientcode; } location / { include proxy_params; proxy_pass http://unix:/home/amir/clientcode/adminpanel.sock; } } However when I try to configure it for django-channels it is giving me status 502 upstream channels-backend { server localhost:8000; } server { listen 80; server_name 159.65.160.71; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/amir/clientcode; } location / { try_files $uri @proxy_to_app; include proxy_params; proxy_pass http://unix:/home/amir/clientcode/adminpanel.sock; } location @proxy_to_app { proxy_pass http://channels-backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } My asgi.py file import os import django from channels.routing import get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "adminpanel.settings") django.setup() application = get_default_application() `` -
how to define global queryset object which i can use in my django views
I want to define global variable which stores data from database table. I need that data in every view functions defined. I dont want to fire a query every time when my function calls. I am using django framework for this. Any suggestion on this how can i optimize this solution? Thanks!! -
How can I display my comment form on the post detail page Django
So basically at the moment, if users want to add a comment to a post on my site, it takes them to another page with the form on it. However, I want the comment form to be on the actual Post Detail page, so users don't have to go to another page to comment. So far I have tried adding some context things and changed the url for the comment form's location to post_detail.html, and put the comment_form.html's code there, however this did not work. Here are the relevant views.py The add_comment_to_post view @login_required(login_url='/mainapp/user_login/') def add_comment_to_post(request,pk): post = get_object_or_404(Post,pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.author = request.user # add this line comment.save() return redirect('mainapp:post_detail',pk=post.pk) # remove `def form_valid` else: form = CommentForm() return render(request,'mainapp/comment_form.html',{'form':form}) Here is the PostDetailView view. class PostDetailView(DetailView): model = Post Here is the comment_form.html code <form class="post-form" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="submitbtn">Comment</button> </form> And here is the relevant urls.py files path('post/<int:pk>/comment/', views.add_comment_to_post, name='add_comment_to_post'), path('post/<int:pk>', views.PostDetailView.as_view(), name='post_detail'), So at the moment, when doing my solutions I thought would work, I added the comment_form.html's code into the post_detail.html document, however it only showed … -
Django Templates - Check and Uncheck Checkbox
I have a django Task with a todo list inside it, this is a list of strings and checkboxes. When I tap a checkbox it changes value but doesn't send it to the model via a POST request. What I want to do is create two views, one that makes the value in the model Checker to 'True' and one that makes it 'False'. These are my Task and Checkbox Models: class Task(models.Model): name = models.CharField(max_length=150) description = models.CharField(max_length=1000) state = models.CharField(max_length=15) deadline = models.DateField(default=date.today) workers = models.ManyToManyField(UserProfile, blank=True, related_name="task") stickers = models.ManyToManyField(Sticker, blank=True, related_name="task") checkers = models.ManyToManyField(Checker, blank=True, related_name="task") files = models.ManyToManyField(File, blank=True, null=True) class Checker(models.Model): name = models.CharField(max_length=100) checked = models.BooleanField(default=False) This is the view To create a checkbox: @login_required def create_checker(request, task_id): if request.method == 'POST': name = request.POST.get('Checker-Name') userprofile = UserProfile(id=request.user.id) checker = Checker(name=name, sender=userprofile) checker.save() task = Task(id=task_id) task.checkers.add(checker.id) return redirect('detailTaskPage', pk = task_id) I want to do something like this when I check versus uncheck the boxes: //Check @login_required def check_checker(request, task_id, checker_id): if request.method == 'POST': checker = Checker(id=checker_id) checker.save() checker.checked=True checker.save() return redirect('detailTaskPage', pk = task_id) //Uncheck @login_required def un_check_checker(request, task_id, checker_id): if request.method == 'POST': checker = Checker(id=checker_id) checker.save() checker.checked=False checker.save() … -
Django files upload causes memory leak
I have an observation about memory leak: If we try to POST files to Django view, Django will not release memory even a response has been made. The memory will keep rising if you keep uploading files even if you do nothing in views.py. (I have tried uploading 100 files concurrently calling the same API). I know that if an uploaded file is smaller than 2.5 megabytes, Django will hold the entire contents of the upload in memory. So I am wondering this could be an issue for a possible memory leak because it will never release the memory. PS: Even if I set FILE_UPLOAD_MAX_MEMORY_SIZE=0, which means use disk to store the files instead of using memory, I can still see a memory rise at the background. Does anyone know how to solve this issue ? Thanks a lot. -
redirect authenticated user at Createview in django
i used CreateView for registration in my project and i wanna prevent authenticated user from accessing to the register url and redirect it to another page can anyone tell me how can i do it? hear is my register view code: class RegisterUserView(CreateView): model = ChatUser template_name = 'login/registration_page.html' form_class = UserForm second_form_class = ProfileForm -
Looking for an alternative way to filter my objects before using a django-filters class
I've implemented a filter using the django-filters third party framework but want to run the filter on an already filtered set which was giving errors. class BlogView(ListView): template_name="blog/blog.html" model = Post # def get_queryset(self): # return Post.objects.filter(posted_date__lte=timezone.now()).order_by("-posted_date")[:25] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = PostFilter(self.request.GET, queryset=self.get_queryset()) return context my view ^ my filter v class PostFilter(django_filters.FilterSet): class Meta: model = Post fields = ["title"] My blog needs the ability to schedule posts in the future meaning when i display them i am filtering posts by posted_date__lte=timezone.now() however this is causing a problem when i am then using the filter because i cannot filter an already spliced object. I've read through and understand the problem comes from the way the database works so i am looking for an alternative way to make only posts that posted_date__lte=timezone.now() show without using the currently commented out def get_queryset filter i was previously using. -
Django test: cannot find object already created
My goal is to have a sort of generic function that creates a row only if this one doesn't exists. A bit of an extension of [get-or-create][1] When I create self.created_object in the setUp, I get an id for the object, which seems to be the definition for an object being persisted on the database. However, when I then try to query MyObject.objects.all(), I get an empty set. The test fails, and the error I get is the following: AssertionError: UUID('b8680f60-1fc0-4bc5-8a26-735ee43247ea') != UUID('38d9b535-2f12-4e76-b637-d52030798f3d') Here's a simplified version of what I'm trying to do from django.test import TestCase from app.models import MyObject from utils import get_object_or_create_it # the implementation is not relevant here class TestCreateOnlyIfNotExists(TestCase): def setUp(self): self.created_object = MyObject.objects.create( name="nobody_cares" ) def test_get_object_or_create_it(self): create_object_only_if_exists = get_object_or_create_it( {'name': 'nobody_cares'}, ('name',), MyObject, ) self.assertEqual( self.created_object.id, create_object_only_if_exists.id ) [1]: https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create Any idea of what's going on here? -
How to create a Enterprise Application with Django
I love to create webapps with Django. I would like to develop an app exclusively for my company. That means no access for people outside the company. Because I'm the only developer, I need a solution that focuses on developing rather than administrative work. Heroku and Azure are good for deploying django but I do not know, how to create a network, that only interacts with the employees of my company. Running a own web server like Apache in the internal company network is also a solution, but I have no skills for it. The appidea: Djangoapp is showing data from a SQL Database. My company mainly works with Microsoft. I am very happy about suggestions -
Error while updating user group in django?
Here I am trying to add/update group name and user permissions and i tried like this. For add it is working fine but while updating with function edit_user_group i got problem. The problem is Exception Type: IntegrityError Exception Value: (1062, "Duplicate entry 'Developer' for key 'name'") I think this is because of OneToOne relation. How can I update user group here ? views.py @permission_required('organization.add_user_group', raise_exception=True) def add_user_groups(request): form = AddUserGroupForm() user_permissions = Permission.objects.all() if request.method == 'POST': form = AddUserGroupForm(request.POST) if form.is_valid(): group_name = form.cleaned_data['name'] permissions = request.POST.getlist('user_permissions') new_group = Group.objects.create(name=group_name) new_group.permissions.set(permissions) messages.success(request, 'New group added.') return redirect('organization:view_user_groups') return render(request, 'organization/add_user_groups.html', {'user_permissions': user_permissions, 'form': form}) @permission_required('organization.edit_user_group', raise_exception=True) def edit_user_group(request, pk): group = get_object_or_404(Group, pk=pk) user_permissions = Permission.objects.all() form = AddUserGroupForm() if request.method == 'POST': form = AddUserGroupForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] permissions = request.POST.getlist('user_permissions') group = Group.objects.update(name=name) group.permissions.set(permissions) messages.success(request, '{} group Updated.'.format(group.name)) return redirect('organization:detail_user_group',group.pk) return render(request,'organization/edit_user_group.html',{'group':group,'form':form,'user_permissions':user_permissions}) forms.py class AddUserGroupForm(forms.Form): name = forms.CharField(max_length=255) template for edit group <form action="{% url 'organization:edit_user_group' group.pk %}" method="post"> {% csrf_token %} <label> Group Name : </label> <input type="text" value="{{group.name}}" name="name"> <b class="text-danger"> {{ form.name.errors|striptags }} </b> <label>Permissions ({{user_permissions|length}}):</label> {% for permission in user_permissions %} <input name="user_permissions" type="checkbox" id="permission-{{permission.id}}" value="{{permission.id}}" {% if permission in group.permissions.all … -
How to get url to action method from ModelViewSet(Django Rest Framework) with reverse function?
I have this ModelViewSet class: class DriveInvoiceViewSet(viewsets.ModelViewSet): filter_fields = ('location_id', 'logical_deleted') permission_classes = (UserCanManageFacilityPermission,) pagination_class = None def get_serializer_class(self): ... def get_queryset(self): ... @action(detail=False, methods=['GET']) def get_subtotals_by_unit(self, request): invoices_list = self.filter_queryset(self.get_queryset()) grouped_invoices = get_subtotals_by_unit(invoices_list) return Response(grouped_invoices) How can I get the URL from reverse function to test the get_subtotals_by_unit action? The ViewSet registred by the router router.register('drive_invoices', DriveInvoiceViewSet, base_name='drive_invoices') -
How to give full access (= anyone) POST to a JWT view?
I'm using djangorestframework with djangorestframework-simplejwt. Everything works fine except one thing: I want to access to a reset-password view with a POST method (= REST "create"). from django.views.decorators.csrf import csrf_exempt from rest_framework.generics import CreateAPIView # JSON views are never accessed through classical forms = no csrf possible: @method_decorator(csrf_exempt, name='dispatch') class UsersResetPasswordView(CreateAPIView): serializer_class = UserResetPasswordSerializer permission_classes = [permissions.AllowAny] def create(self, request, *args, **kwargs): return Response({'reset-url': 'test url'}, status=status.HTTP_202_ACCEPTED, headers=headers) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) permissions.AllowAny is not enough, I get a 401 "Given token not valid" (if I send the token, otherwise I get "forbidden"). I've tried to add authentication_classes = [] but nothing changes. I just want to make a simple view that anybody can access, via a POST! -
Online collaborative list of references
I am working in academia in a very wide field of research mixing a lot of different domains. This broadness is also a problem, since there is no proper references for the basis of the theory, and we have to deal with a lot of material scattered in very different places, often in the form of lecture notes, conference proceeding or unpublished documents. Therefore, I would like to propose a collaborative online list of these references, in a light way so that anyone could add or improve the list. The best current list of references is here, which is neither up to date nor really easy to use (no tags, list by authors, etc). I would like something slightly more powerful, I though about some framework like Django but don't really know if it is a suitable solution. I would like to be able for anyone to sort in different ways add tags add or edit references entries rate difficulty (this is a bonus) comment (this is a bonus) Moreover, it should be better if the list were accessible without any amount on a simple webpage. Any suggestion is welcome! -
How to use django-graphql-geojson - Problems with distance_Lte Filter
I want to use the distance_Lte filter as in the readme-file https://github.com/flavors/django-graphql-geojson described. But I didn´t get the expected result. Can someone tell me what my failure is? My django classes: class Location(models.Model): calendar = models.ForeignKey(Calendar, on_delete=models.CASCADE) name = models.CharField(max_length=255) location = models.PointField(srid=4326, unique=True) address = models.CharField(max_length=100) city = models.CharField(max_length=50) class LocationType(GeoJSONType): class Meta: model = Location geojson_field = 'location' filterset_class = LocationFilter interfaces = (relay.Node,) exclude = [] class LocationFilter(GeometryFilterSet): class Meta: model = Location fields = { 'city': ['exact', 'icontains', 'istartswith'], 'location': ['exact', 'intersects', 'distance_lte'] } class Query(graphene.ObjectType): location = relay.Node.Field(LocationType) locations = DjangoFilterConnectionField(LocationType) My graphql-Query: query{ locations(location_DistanceLte:{geometry:"{'type': 'Point', 'coordinates': [13.28702,52.4581]}", value:400, unit:"km"}){ edges{ node { id } } } } The error-msg: { "errors": [ { "message": "Argument \"location_DistanceLte\" has invalid value {geometry: \"{'type': 'Point', 'coordinates': [13.28702,52.4581]}\", value: 400, unit: \"km\"}.\nExpected type \"Geometry\", found {Geometry: \"{'type': 'Point', 'coordinates': [13.28702,52.4581]}\", value: 400, unit: \"km\"}.", "locations": [ { "line": 2, "column": 34 } ] } ] } I don´t know, what I´m doing wrong... It would be nice if you can help. Thanks -
Django 2.1 created migration with makemigrations did not show up in migrations folder
After running python manage.py makemigrations terminal showed Migrations for 'api_app': api_app/migrations/0004_analysis_error.py But the file didn't show up in the directory. I ran python manage.py migrate and it even showed: Applying api_app.0004_analysis_error... OK But still no api_app.0004_analysis_error.py in the directory. I also tried making an empty migration, the same behavior occurred. I also tried removing the changes and resetting the migrations, no changes were detected (even though there were). The application name has been included in the [INSTALLED_APP] module in settings.py. -
Django - saving manually generated ImageField raises error
I have anInvoice model which has qr_code = ImageField(...) field. In save method, I want to generate the qr_code file and save it to the field. The problem is a path. When I set path including /media/ - so /media/qr/myfile.png, Django then looks for it in templates this way: /media/media/qr/myfile.png. But when I not include /media/ it cannot be saved: FileNotFoundError: [Errno 2] No such file or directory: 'qr/myfile.png' I think the problem is either in first function or at the end of the other. Invoice.generate_qr def generate_qr(self, save=False): path = qr.generate_qr(self, f"Faktúra č. {self.number}") self.qr_code = path if save: self.save() qr file def generate_qr(invoice, note: str = None) -> Optional[str]: ... qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) qr_php_script_path = os.path.join(settings.BASE_DIR, 'dashboard', 'faktury', 'qr.php') proc = subprocess.Popen( ["php", qr_php_script_path, str(total), splatnost, variable_symbol, "", "", note or "", iban, "", ], stdout=subprocess.PIPE) qr_string, _ = proc.communicate() qr.add_data(qr_string) qr.make(fit=True) img = qr.make_image(fill_color="black", back_color="white") img_path = os.path.join(settings.MEDIA_ROOT, 'qr', 'myfile.png') img.save(img_path) return img_path Do you know how to make it work? -
How to solve this celery Error: Unable to load celery application. Module 'forecast' has no attribute 'celery'
I am trying to seting up Celery and Amazon SQS for my project but faced with problems. I did following. I put celery.py file inside my project directory where settings py located. Here is snapshot of my project --predictions --forecast --dataflow --forecast ** __init__.py ** celery.py ** urls.py ** settings.py ** wsgi.py --manage.py --env I doted with "--" folders and with "**" files. Inside celery.py file i have the folliwing code from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault ('DJANGO_SETTINGS_MODULE', 'forecast.settings') app = Celery('forecast') app.config_from_object ('django.conf:settings') app.autodiscover_tasks() app.conf.beat_schedule = { 'display_time-30-seconds': { 'task': 'demoapp.tasks.display_time', 'schedule': 10.0 }, } @app.task(bind=True) def debug_task(self): print('Request: {0r}'.format(self.request)) Inside settings.py file i set up Amazon credentials,broker_url etc #settings.py # AWS Credentials AWS_ACCESS_KEY_ID = ('lol') AWS_SECRET_ACCESS_KEY = ('Lol') # Celery BROKER_URL = "sqs://%s:%s@" % (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_DEFAULT_QUEUE = 'test.fifo' CELERY_RESULT_BACKEND = None # Disabling the results backend BROKER_TRANSPORT_OPTIONS = {'region': 'us-west-2', 'polling_interval': 20,} Inside init.py file i put the following code from __future__ import absolute_import, unicode_literals from .celery import app as celery_app__all__ = ['celery_app'] Then i added in my django app task.py which contain the following code from datetime import datetime from celery … -
React BrowserRouter Route doesn't change url
I am trying to make my React Router change my actual url. Right now it changes the component but does not change the actual url in my browser Here is my app.js import React, { Component } from 'react'; import './App.css'; import { BrowserRouter, Route, Redirect, Switch} from 'react-router-dom'; import PaintingList from './paintings/PaintingList'; import PaintingDetail from './paintings/PaintingDetail'; import PaintingCreate from './paintings/PaintingCreate'; class App extends Component { render() { return ( <BrowserRouter> <Switch> <Route exact path='/' component={PaintingList}/> <Route path='/paintings' component={PaintingList}/> <Route path='/paintings/create' component={PaintingCreate}/> <Route path='/detailed-view/:slug' component={PaintingDetail}/> </Switch> </BrowserRouter> ); } } export default App; I am trying to make the PaintingDetail component point to the /detailed-view/:slug path but my actual browser keep displaying http://127.0.0.1:8000/paintings/sad-man (sad-man is the slug in this case) I have even tried to delete this line all together <Route path='/detailed-view/:slug' component={PaintingDetail}/> The component still works but the the browser still displays http://127.0.0.1:8000/paintings/sad-man I am using Django for my backend, I am not sure if that has anything to do with it. Here is my url.py for my paintings model from django.urls import path, re_path from .views import ( PaintingDetailAPIView, PaintingListCreateAPIView, ) app_name = 'paintings-api' urlpatterns = [ path('', PaintingListCreateAPIView.as_view(), name='list-create'), re_path(r'^(?P<slug>[\w-]+)/$', PaintingDetailAPIView.as_view(), name='detail'), ] here is my urls.py … -
How to hide some Usergroups from Django Admin in ManytoMany field
I have the following model: class Task(models.Model): site=models.OneToOneField(Site,on_delete=models.CASCADE,default=1) executor=models.ManyToManyField(People) It is related to the following model: class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) phone_number = models.CharField(max_length=200, blank=True, null=True) #department = models.CharField(max_length=200, blank=True, null=True) title = models.CharField(max_length=200, choices= titles, blank=True, null=True) What I want is that in DjangoAdmin in the field executor only people__title='titleone' was displayed. So that the executor search field would not be overload with other people who cannot ever be related to the Tsk since I have them in the same database. -
How to add a new field to oscar dashboard
After following various examples here on stackoverflow my new field isn't showing up on django oscar dashboard here are my models and dashboard fork. catalogue models.py from django.db import models from oscar.apps.catalogue.abstract_models import AbstractProduct class Product(AbstractProduct): file = models.FileField(upload_to='files/%Y/%m/%d') from oscar.apps.catalogue.models import * dashboard/catalogue/forms.py from oscar.apps.dashboard.catalogue import forms as base_forms class ProductForm(base_forms.ProductForm): class Meta(base_forms.ProductForm.Meta): fields = ('file',) I am wondering what i did wrong for people that have faced this issue before I need help. thanks. -
Redirecting from Django App to Asp.Net webpage
I have a Django app that is a form that is supposed to be in multiple languages. Temporarily, I would like to release my app with the English form and use the other language buttons to redirect to an old ASP.Net version of the form while I work on making my form multi-lingual. I did manage to have my form redirect to the right place when I click on my "Spanish" button, but there are missing necessary Session parameters that the ASP.NET form needs to function properly. From my Django app: HTML Template <a href="{% url 'to_spanish' %}"><button type="button" class="btn-outline-secondary">Español</button></a> views.py (redirecting FROM this page) def to_spanish(request): request.session["Language"] = 'Spanish' # request.session["RandomID"] = '' # request.session["email"] = '' # request.session["nameidentifier"] = '' return HttpResponseRedirect('https://lspintake.nbn.org.il/IntakeForm') urls.py urlpatterns = [ path('', views.index, name='Auth0 homepage'), path('IntakeForm/1', views.personal_details_section), path('IntakeForm/2', views.parents_section), path('IntakeForm/3', views.citizenship_section), path('IntakeForm/4', views.idf_section), path('https://www.google.com', views.to_spanish, name='to_spanish'), ] (I used 'google.com' here as a placeholder. It still redirects to the url I put in the view and I'm not really sure what to put in the urls file in that spot.) From the ASP.NET app (what I'm trying to redirect TO): Lines of code are used like this in C# in this app: int … -
jQuery Core test/data/jsonp.php callback Parameter XSS
jQuery Core contains a flaw that allows a cross-site scripting (XSS) attack. This flaw exists because the test/data/jsonp.php script does not validate input to the 'callback' parameter before returning it to users. This may allow a context-dependent attacker to create a specially crafted request that will execute arbitrary script code in a user's browser session within the trust relationship between their browser and the server.| Which version of jquery or django-jquery have this fix? -
In City Field Input Type problem in django
This Is the Code. <div class="col-lg-4 col-sm-12"> <div class="control-group"> <label for="City" class="control-label">City*</label> <div class="controls"> <input type="text" value="{{ org.city }}" id="city" name="city" placeholder="Enter your city" required="" aria-required="true"> </div> <!-- /controls --> </div> <!-- /control-group --> </div> -
django: uploaded images won't be displayed
my uploaded images can't be displayed even though i'm not getting any errors: instead it looks like this and here are my settings and codes: settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static_cdn") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),"media") models: class Post (models.Model): title = models.CharField(max_length=200) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) cover = models.ImageField(null=True, blank=True, upload_to='media/') urls: if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views: def posts_create (request): form = PostForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request, "Successfully created") return HttpResponseRedirect(instance.get_absolute_url()) context = {'form': form} return render(request, 'post_form.html', context) template: {% extends "base.html" %} {% block title %} {{object.title}} | {{block.super}}{% endblock title%} {% block content %} <div class="center" style=" display: table; margin-right: auto; margin-left: auto;"> {% if object.cover %} <img src="{{object.cover.url}}" class="img-responsive"/> {% endif %} <h1>{{title}} <small style="font-size: small"> {{object.timestamp}}</small> </h1> {{object.content | linebreaks}}<br> <div/> {% endblock content%} -
How to make a Django FormSet accept m2m but store them as multiple FK records?
I need to provide a test for students, but some questions accept multiple answer. Can I make it create multiple records for storing multiple answers instead of using a M2M? e.g. if a student select A and B for a question, would act like the following: StudentAnwer.objects.create(question=question, answer=answer_a) StudentAnwer.objects.create(question=question, answer=answer_b) formsets.py from django import forms StudentAnswerFormSet = forms.inlineformset_factory( Student, StudentAnswer, fields=['question', 'answer', ], formset=forms.BaseInlineFormSet) models.py class Question(BaseModel): title = models.CharField(max_length=250) is_multiple = models.BooleanField(default=False) class StudentAnswer(BaseModel): student = models.ForeignKey(Student, related_name='answers') question = models.ForeignKey(Question, related_name='student_answers') answer = models.ForeignKey(Answer, related_name='student_answers') views.py from formtools.wizard.views import SessionWizardView class StudentWizardView(SessionWizardView): ... def get_answer_form(self, step=None, data=None, files=None): ... question_list = get_question_list() return forms.inlineformset_factory( Student, StudentAnswer, fields=['question', 'answer', ], extra=len(question_list), formset= forms.BaseInlineFormSet) def get_form(self, step=None, data=None, files=None): form = super(StudentWizardView, self).get_form(step, data, files) # determine the step if not given if step is None: step = self.steps.current if step == self.STEP_ANSWER: initial_dict = self.get_form_initial(step) prev_form_data = self.get_cleaned_data_for_step(self.STEP_PROFILE) form = self.get_answer_form(step, data, files) for form_index in range(len(initial_dict.keys())): question = initial_dict[form_index]['question'] answer_list = question.get_answer_list() if question.is_multiple: form.forms[form_index].fields['answer'] = ModelMultipleChoiceField(queryset=answer_list, widget=CheckboxSelectMultiple) else: form.forms[form_index].fields['answer'].widget.choices.queryset = answer_list I'm trying to avoid M2M for making it easier to display the possible answers per question on the template. {{ wizard.management_form }} {{ wizard.form.management_form }} {% …