Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Render Excel templates
I'd like to have the ability to render Excel template files: and not create Excel files programmatically. There is a lib Templated-docs. But the templates themselves must be in on of the OpenDocument formats: .odt, .ods, .odp or .odg. Those templates are rendered to excel futher. This fact affects on formatting features when rendering to Excel. Is there any possibility to render directly to Excel file template? -
how to set a default for multiselect field in django
I have an Account model that extends django's custom User model: class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) joined_groups = models.ManyToManyField(Group, related_name='joined_group', blank=True) created_groups = models.ManyToManyField(Group, blank=True) EMAIL_PREFERENCES = [ ('user_emails', 'User Emails'), ('group_emails', 'Group Emails'), ('leader_emails', 'Leader Emails'), ] email_preferences = MultiSelectField( verbose_name = 'Email Preferences', choices=EMAIL_PREFERENCES, blank=True, max_choices=3, max_length=255, ) When a User registers or signs up, as of now, they create a connected Account with the same id and pk with the fields of joined_groups and created_groups empty. However, they also have none of the email_preferences selected either. Here in lies my issue. I want a User who signs up to have the default for email_preferences true for all of them. Then, if they prefer to not receive any emails, they can edit their email_preferences on their Account page. Lastly, once the email_preferences have been selected, I need to add the conditional into the view to see whether or not this User should receive email notifications: For when a User creates a Group: class CreateGroup(CreateView): model = Group form_class = GroupForm template_name = 'create_group.html' def form_valid(self, form): group = form.save() group.joined.add(self.request.user) account = self.request.user.account account.created_chaburahs.add(group) account.joined_chaburahs.add(group) email = account.user.email # celery task to send email create_group_notification_task.delay(email) return HttpResponseRedirect(reverse('group_detail', … -
Adding condition to DeleteView in Django
I am learning basics of Django and trying to add a condition before deletion of Ingredient instance in a generic DeleteView. But it looks like DeleteView is just ignoring my condition. What am I doing wrong? Thank you in advance for looking at my question! class IngredientDelete(LoginRequiredMixin, DeleteView): model = Ingredient template_name = "inventory/ingredient_delete_form.html" success_url = "/ingredient/list" def delete(self, request, *args, **kwargs): object = self.get_object() if len(object.reciperequirement_set.all()) > 0: object.delete(save=False) messages.error("You can't delete an ingredient if it is used in Menu Items. Please update Menu items first. You can check related Menu items list on the Ingredient Details page") return render(request, "ingredient/<pk>", messages) else: return super().delete(request, *args, **kwargs) in python shell, for the instance object I try len(object.reciperequirement_set.all()) and get 1, so I suppose the query in my condition is set correctly. At local host page for the same Ingredient instance I get the error page: ProtectedError at /ingredient/23/delete ("Cannot delete some instances of model 'Ingredient' because they are referenced through protected foreign keys: 'RecipeRequirement.ingredient'.", {<RecipeRequirement: menu item: testdel, price: 34.00, ingredient: testingr: 22.00 tsp>}) Request Method: POST Request URL: http://127.0.0.1:8000/ingredient/23/delete Django Version: 4.0.4 Exception Type: ProtectedError -
implementing multi user types for hospital management system
so I am building a hospital management system as my pet project in Django, and one thing that I realized is that you need implement a 3 user multi system which includes the HR, staff(doctor) and patient. Been surfing through the internet for the best implementation and came up short. The best I saw was this tutorial blog on How to implement multi user system, but it doesn't cover on using more than 3 user like I want to. This is my current user/models.py from django.db import models from django.contrib.auth.models import AbstractUser USER_CHOICE = [ ('D', 'Doctor'), ('P', 'Patient'), ('R', 'Receptionist'), ('HR', 'HR') ] # Create your models here. class User(AbstractUser): """ user class for different users in the database """ user_type = models.CharField(choices=USER_CHOICE, max_length=3, default=None) def is_doctor(self): """ return True if the user is a doctor and False if not """ if self.user_type == 'D': return True return False def is_patient(self): """ return True if the user is a patient and False if not """ if self.user_type == 'P': return True return False def is_receptionist(self): """ return True if the user is a receptionist and False if not """ if self.user_type == 'R': return True return False def is_hr(self): … -
Make Django form choices depend on values submitted in a previous form
I'm using django-formtools to create a multi-step form wizard. I want to use data entered in the first step to call an API, then use the response data in the next step as a ChoiceField. This is what my code currently looks like: views.py from server.companies.models import Company from server.data_sources.models import DataDictionary, DataSource from django.shortcuts import render from formtools.wizard.views import SessionWizardView import json import logging from server.data_sources import ds from server.data_sources.models import SOURCE logger = logging.getLogger("server." + __name__) def create_records(data): if not data or data == {}: return name = data.get("company_name") is_sandbox = data.get("is_sandbox") city = data.get("city") state = data.get("state") username = data.get("username") password = data.get("password") data_source = DataSource.objects.create( name=name, source_type=SOURCE, ) ds.login(data_source, username, password) company = Company.objects.create( name=name, data_source=data_source, ) return company class Wizard(SessionWizardView): template_name = "wizard.html" def done(self, form_list, **kwargs): return render( self.request, "done.html", {"form_data": [form.cleaned_data for form in form_list]}, ) def get_form_step_data(self, form): return form.data def get_form(self, step=None, data=None, files=None): form = super().get_form(step, data, files) company = None # determine the step if not given if step is None: step = self.steps.current if step == "0": if form.is_valid(): step_zero_data = form.cleaned_data company = create_records(step_zero_data) source = company.data_source data_dict = {} for field in ds.select( company, "DATADICT", ["dd_dbf", … -
Heroku Django post-gis extension: Error "no attribute 'geo_db_type'" problem when migrating a new model that contains geo elements
I'm running into this issue when deploying my django app on heroku. It had be building and deploying fine before I edited my django model to include a geometry field: geom = models.PointField(verbose_name='geo',srid = 4326) Now it builds successfully, but then fails at this migration code in the Procfile `release: python manage.py migrate` The migration file is successfully in my git repo. And locally I was able to run python manage.py migrate successfully. When I go to migrate on heroku I get the below error. AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type' It seems to indicate that there is something "geo-related" missing, but I can't figure out what since I have created a postgis extension on the postgres db in heroku and I have the heroku-geo-buildpack along with the heroku/python buildpack. On heroku I have python 3.10 and locally it's Python 3.9.13. In my settings.py file I have: 'ENGINE':'django.contrib.gis.db.backends.postgis', in the DATABASES and 'django.contrib.gis', in INSTALLED_APPS Here's the post-gis extension on the heroku postgres database: And the two buildpacks set in heroku: Thank you for any help or guidance! -
"Invalid value." error while using django rest framework Serializer
I am trying save some information from a csv file into the DB using django rest framework, currently I am not sure where is the issue if it is in the view or something in the model, to test it out I am sending the data as it is arriving to the serializer Here there is my view.py import re import csv import codecs import pandas as pd from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.shortcuts import render from rest_framework.decorators import api_view # Create your views here. from rest_framework import viewsets,status from .serializer import tripSerializer #,DataSourceSerializer from .models import Trips from rest_framework.response import Response class TripViewSet(viewsets.ViewSet): def list(self, request): queryset = Trips.objects.all() serializer = tripSerializer(queryset, many=True) return Response(serializer.data) def insert(self, request): file=codecs.EncodedFile(request.FILES.get("file").open(),"utf-8") print(type(file)) reader = pd.read_csv(file, delimiter=";") reader.columns = ['region','origin_coord','destination_coord','datetime','datasource']; reader=reader.to_dict(orient = 'records')[0] print("--------------------------------------------------------") print("DATA inicial",reader) print("--------------------------------------------------------") data={'region': 'Prague', 'origin_coord': 'POINT (14.4973794438195 50.00136875782316)', 'destination_coord': 'POINT (14.43109483523328 50.04052930943246)', 'datetime': '28/05/2018 9:03', 'datasource': 'funny_car'} serializer = tripSerializer(data=reader) print("trying to validate") if serializer.is_valid(): serializer.save() return Response({"status":"success"}, status=status.HTTP_200_OK) else: return Response({"status":"Error!!","data":serializer.data,"Error:":serializer.errors,"message_error":serializer.error_messages}, status=status.HTTP_400_BAD_REQUEST) Serializer.py from django.shortcuts import render # Create your views here. from dataclasses import field, fields from rest_framework import serializers from .models import Datasources, Regions, Trips … -
how to serialize two classes have one to many relation in django
this is my models class Users(models.Model) : name = models.CharField(max_length=20 , blank=False , null=False) email = models.EmailField(max_length=50 , blank=True , null=True) password = models.CharField(max_length=30 , blank=False , null=False) birthday = models.DateField(null=False) photo = models.ImageField(upload_to = 'user_photos/%y/%m/%d') #friend = models.ManyToManyField('self',through='Notif',null=True,related_name='friend') class Product(models.Model): pub_date = models.DateTimeField(default=datetime.now) price = models.DecimalField(max_digits=100000,decimal_places=5,null=False,blank=False) size = models.IntegerField(null=True,blank=True,default='undefined') photo = models.ImageField(upload_to = 'product_photos/%y/%m/%d',null=True) #for 1--n relation with users user_id = models.ForeignKey(Users,on_delete=models.CASCADE,null=True,related_name='user') this is my serializers.py class ProductSerializer (serializers.ModelSerializer): class Meta : model = Product fields = '__all__' class UsersSerializer(serializers.ModelSerializer): class Meta: model = Users fields = '__all__' i want to send product object with the email of his user what i have to do in serializers and views to make it note i use function based views in my views -
How can I store images on server and serve them with nginx and django?
I've created a Django app and I'm using Gunicorn and Nginx with it on an Ubuntu server. Nginx serve my static files and it work great for css files and javascript, but I have problem with images. App is my personal blog site and I'm using Django ckeditor for uploading images and writing some text.Everything worked as it should while I was using local server, but when i deploy it on cloud server images are not displayed. here's my project/app/models.py from django.db import models import uuid from ckeditor_uploader.fields import RichTextUploadingField # Create your models here. class Category(models.Model): title = models.CharField(max_length=150) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.title class Article(models.Model): title = models.CharField(max_length=150) description = models.CharField(max_length=150, blank=True, null=True) body = RichTextUploadingField(blank=True, null=True) profile_image = models.ImageField(null=True, blank=True, default='default.png') category = models.ForeignKey(Category, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.title class Meta: ordering = ['-created'] The code below is in settings.py: STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] MEDIA_ROOT = '/var/www/my-website.com/media' STATIC_ROOT = '/var/www/my-website.com/static' CKEDITOR_UPLOAD_PATH = 'uploads/' In project urls.py I add: urlpatterns = [ . . . path('ckeditor', include('ckeditor_uploader.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) … -
How to configure data migration from one model to another . Django?
There is model Leads with fields : name, phone, email, address and I create model Contacts with the same fields but with processed data from Leads for example, combine all leads with the same names and phone numbers into one contact, etc. how to implement it? whether to create a migration or a . how it is better to implement it? -
accordion with for loop to only open one item at a time
I am trying to add an interactive id to my accordion, but something is off in my code and the accordion opens every accordion item, all I want is to be able to open one accordion item at a time when clicking on it. {% for study in studies %} <div class="accordion" id="accordionExample"> <div class="accordion-item"> <h2 class="accordion-header" id="heading{study.uid}"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs- target="#collapse{study.uid}" aria-expanded="true" aria- controls="collapse{study.uid}"> {{ study.uid }} </button> </h2> <div id="collapse{study.uid}" class="accordion-collapse collapse" aria- labelledby="heading{study.uid}" data-bs-parent="#accordionExample"> <div class="accordion-body"> text </div> </div> </div> {% endfor %} -
Python/Django - Best way to avoid UnboundLocalError when a list is empty
I'm using a list to get data from an API. This list is created with a code like this: mylist = [] for batch in stream: for row in batch.results: data = {} data["color"] = row.color data["count"] = row.count mylist.append(data) And the list end up being something like: mylist = [{'color':'red','count':5}, {'color':'blue','count':7}] And then I send it to the Django template using something like this: context = { 'mylist' : mylist, 'data' : data, } return render(request, 'page.html', context) This works OK most of the time. But sometimes there is no data to send, so the API doesn't send anything and mylist is empty. When that happens, I get an error: UnboundLocalError at /page local variable 'data' referenced before assignment I've "solved" it with the following code: if not mylist: data = {"error": "no data"} That removes the error, but seems very "hacky". I don't need that info in my list. If there is no data, I would probably prefer to have the list empty (so I can do an "if" to check if it's empty or not and stuff like that). Is there a better solution? Thanks! (I'm learning Python and Django, so maybe most of my code can … -
GCBV Generic Class Based View, Django Classes Issue
$ Hello, I was trying to use "GCBV Generic Class Based View" for edit a post, but it seems not working and event it django can't find my HTML and I don't know why , Hope I get some support …. $ edit button link {% if post.created_by == user %} <div class="mt-3"> <a class="btn btn-success float-end" href="{% url 'edit_post' post.topic.board.pk post.topic.pk post.pk %}">Edit</a> </div> {% endif %} $ edit HTML Page {% extends 'base.html' %} {% load static %} {% block title %}Edit Post{% endblock %}<!-- | Page-title--> {% block content %} <link rel="stylesheet" href="{% static 'css/boards.css' %}"> <div class="newtopic"> <div class="container container-newtopic w-50"> <h1>Edit Post</h1> <br> {% include 'parts/alerts.html' %} <div aria-label="breadcrumb"> <ol class="breadcrumb n1-head"> <li class="breadcrumb-item"><a href="{% url 'boards' %}">Boards</a></li> <li class="breadcrumb-item"><a href="{% url 'topics' post.topic.board.pk %}"> {{post.topic.board.name}}</a></li> <li class="breadcrumb-item active" aria-current="page"><a href="">Edit Post</a></li> </ol> </div> <form method="POST" action="" novalidate class="mb-4"> {% csrf_token %} {% include 'includes/form.html' %} <button type="submit" class="btn main-btn w-100 rounded-pill mt-5"> Save Changes </button> </form> </div> </div> {% endblock %} $ Views.py @method_decorator(login_required, name='dispatch') class PostUpdateView(UpdateView): model = Post fields = ('message',) template_name = 'edit_post.html' pk_url_kwarg = 'post_id' context_object_name = 'post' def form_valid(self, form): post = form.save(commit=False) post.updated_by = self.request.user post.updated_date = timezone.now() … -
Django Rest API Unit Testing returning 401 Unauthorized for endpoint tests
I created some unit tests with basic asserts checking for status codes to get a few tests done and working. The endpoints themselves work flawlessly when I test them individually outside of the Django unit tests using manage.py test test_file However, I am getting a 401 Unauthorized on all endpoints when I run the tests. I have tried writing in several auth methods to correct the issue but no matter what I try, a 401 is returned. I have tried adding a force auth function, changing TestCase to APITestCase, and creating a superuser manually in the setUp() for each of my test cases. All of the solutions I have found online for similar problems still yield the 401, unauthorized error. Using: Django 3.2.14 Python 3.10.4 I have also followed the Django Rest API documentation for test cases to the letter. I get 401 errors all the way through. -
how to implement depended dropdown lists in Django formset
The code below represents the scripts that are working well in the Django formset but only in the first formset. When I add another one it is showing me the list of components only from the first product. How can I make my dropdown list feature more dynamic so it changes for example form-0 into form-1 if it the second formset is created? I'd appreciate any help. my html file <body> <form id="form-container" method="POST" data-components-url="{% url 'ajax_load_components' %}"> {% csrf_token %} {{ce_request_formset.management_form}} {% for form in ce_request_formset %} <div class="ce-request-form"> {{ form|crispy }} </div> {% endfor %} <button id="add-form" type="button">Add component</button> <button type="submit">Send CE</button> </form> </body> <script> // Script to handle adding new forms in html file let CERequestForm = document.querySelectorAll(".ce-request-form") let container = document.querySelector("#form-container") let addButton = document.querySelector("#add-form") let totalForms = document.querySelector("#id_form-TOTAL_FORMS") let formNum = CERequestForm.length-1 addButton.addEventListener('click', addForm) function addForm(e){ e.preventDefault() let newForm = CERequestForm[0].cloneNode(true) let formRegex = RegExp(`form-(\\d){1}-`,'g') formNum++ newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form-${formNum}-`) container.insertBefore(newForm, addButton) totalForms.setAttribute('value', `${formNum+1}`) } // Script to handle dependent dropdown lists $("#id_form-0-related_product").change(function () { var url = $("#form-container").attr("data-components-url"); var related_product_id = $(this).val(); $.ajax({ url: url, data: { 'related_product': related_product_id }, success: function (data) { $("#id_form-0-related_component").html(data); } }); }); </script> -
Django-tables2 pagination
While using django-tables2 I couldn't find how I paginate the table. On the documentation It says enough to set the table for view but doesn't work. class TableView(SingleTableView): model = TableModel table_class = MyTable template_name = "table.html" -
Django Recursive Foreign Key for Serializer Getting not iterable errors
I followed a lot of answers regarding my questions, I tried all solutions given here Basically scenario is almost same I wanted recursive query in my serializer. Firstly I want to show my models class Policy(TimeStampedModel): product = models.ForeignKey(Product, related_name='policies', on_delete=models.PROTECT, null=True) name = models.CharField(max_length=32) slug = AutoSlugField(populate_from='name', editable=True, slugify_function=slugify) and I have Foreign Key from Policy to PolicyCondition here is policy condition model. class PolicyCondition(TimeStampedModel): policy = models.ForeignKey(Policy, on_delete=models.CASCADE) name = models.CharField(max_length=200) slug = AutoSlugField(populate_from='name', editable=True, slugify_function=slugify,null=True) text = models.TextField() parent = models.ForeignKey( 'self', on_delete=models.CASCADE, null=True, blank=True, related_name='children' ) On serializer I am fetching all my data from policy model. Here is my serializer. class PolicyListSerializer(serializers.ModelSerializer): conditions = PolicyConditionSerializer(source='policycondition_set', many=True) class Meta: model = Policy fields = ['conditions'] Here is my policy condition serializer class PolicyConditionSerializer(serializers.ModelSerializer): class Meta: model = PolicyCondition fields = [ 'id', 'policy', 'name', 'text', 'slug', 'parent' ] def to_representation(self, instance): self.fields['parent'] = PolicyConditionSerializer(read_only=True) return super(PolicyConditionSerializer, self).to_representation(instance) I am getting error as PolicyCondition' object is not iterable any soluton what I am missing here. -
is there's a better way than saving user data in session?
When the user register and he enter his phone number, i don't save the data into the database untill the user verify his phone number by entering the code sent to his phone (OTP) the problem is that i save this data in the session untill he enter the OTP, then i save it into the DB is there's a better way? As it's not safe to save the user password in the session i thought about saving directly in the DB and i will use Corns.py to check every day if there's any user didn't verify his phone number, then it will delete it.. i also thought about saving normal info in the session like name, phone number, email, then i'll send him the OTP and after, he will continue registeration and he will type his password and it will be saved in the DB directly But i still think that there's a better solution what can it be? -
Empty fields on update commands
When using an update command there is no way to validate when a field is None by default or None due to a new value. Thanks in advance in you can help :) # views.py class UpdateCustomerView(APIErrorsMixin, APIView): class InputSerializer(serializers.Serializer): name = serializers.CharField(required=False) password = serializers.CharField(required=False) document = serializers.CharField(required=False) def put(self, request, id): input_serializer = self.InputSerializer(data=request.data) input_serializer.is_valid(raise_exception=True) cmd = commands.UpdateCustomer(id=id, **input_serializer.validated_data) bus = bootstrap.bootstrap() bus.handle(cmd) return Response(status=status.HTTP_204_NO_CONTENT) # commands.py @dataclass class UpdateCustomer(Command): id: UUID document: Optional[str] = None name: Optional[str] = None # handlers.py def update_customer( cmd: commands.UpdateCustomer, uow: AbstractCustomerUnitOfWork ) -> None: # So here comes the issue cmd.name is None because the view didn't receive it or because the dataclass of the command set its value to default? -
PyPi does not grab templates directory on a Django app
What is my goal I want to publish a PyPI package where the code within this package will be a Django application (migrations + templates folder, views, models, etc...) I created the project with setup.py which includes the necessary data so that the build module of python will build the PyPI package smoothly, with version management. This is the repository for further look: github-repo What is the problem The python -m build command does not take the templates directory within the package. It leads to a broken package of a Django application, because when you attempt to install the (package), it does not bring the templates. It is testable with pip install rlocker-expiryaddon What did I try I know that mentioning a file inside MANIFEST.in will be responsible to grab the files in the build process. (?) So I tried to inject the following line: recursive-include templates *.html schema.js Yet, no luck. I know that there are a lot of open-source libraries like the djangorestframework that is easy downloadable via pip and it brings it's templates directory to the system interpreter as expected. But for me, I am not sure what is wrong. Thanks for your help! -
Why Django admin custom modelform field is not saving data
I've got 2 models: Room and Roomgroup. My goal is to represent models in admin in both ways - Roomgroup in Room admin and Rooms in Roomgroup admin so I tweaked Roomgroup admin modelform in AdminModelforms but it's not working as I expected and I'd like to know where am I doing things wrong. And do I overcomplicate it? When I save Roomgroup in admin, it doesn't save roomgroup instance to Room model even for a new Roomgroup instance even for an existing one, it seems like data is cleared before save(). What's wrong? Models examples here are shortened but it correlates with my code. models.py: class Room(models.Model): name = models.CharField(max_length=200, verbose_name=_('Name'), unique=True, null=False) roomgroup = models.ForeignKey(Roomgroup, on_delete=models.SET_NULL, verbose_name=_('Room group'), null=True, blank=True) class Roomgroup(models.Model): name = models.CharField(max_length=200, verbose_name=_('Name'), unique=True, null=False) admin_forms.py: class RoomgroupAdminForm(forms.ModelForm): rooms = forms.ModelMultipleChoiceField( Room.objects.all(), widget=FilteredSelectMultiple(verbose_name=_('Rooms'), is_stacked=False), required=False, ) def __init__(self, *args, **kwargs): super(RoomgroupAdminForm, self).__init__(*args, **kwargs) # show just rooms without group self.fields['rooms'].queryset = Room.objects.filter(roomgroup=None) if self.instance.pk: # show rooms without roomgroup and the ones already assigned to this roomgroup self.fields['rooms'].queryset = Room.objects.filter(roomgroup=None) | Room.objects.filter(roomgroup=self.instance) # preselect rooms already assigned for the roomgroup self.initial['rooms'] = self.instance.room_set.all() def save(self, commit=True): instance = super(RoomgroupAdminForm, self).save(commit=False) if not instance.pk: for room … -
how to automatically reload Django project when backend files updated?
I have a Django rest project that its view reads from output a Matlab code. my file, 'output. mat' is updated at such times of the day; But when I make a request, Django does not show the expected values. my Django project does not show my updated value. I have to manually run 'python manage.py runserver' in the terminal to Django show the updated files (expected values). There is an idea to reload Django automatically when the Matlab outputs files are changed?? -
problem with exporting items from current formset(s) in Django 3.2
I have a view where the user inserts a number of units and once submit button is clicked the excel file is exported as xlsx file. I am using Django import-export to do that BUT I don't know how to filter the CERequests model so the user sees only what (s)he has just inserted. I have implemented the filtering by the user but when clicking submits button it filters all items by the current user but it shows all of them (also items from the past). What I want is to export only values from the current formset or formsets. What I tried is to put created=created in filter method but it gives me an empty Excel file. When I remove it gives me a list of all CERquests that the user inserted. What do I need to do to get only data from the current formset(s)? views.py class CostCalculator(LoginRequiredMixin, TemplateView): template_name = 'calculator/cost_calculator.html' def get(self, *args, **kwargs): # Create an instance of the formset formset = CalculatorForm(initial=[{ 'author': self.request.user.email, }]) return self.render_to_response({'ce_request_formset': formset}) # Define method to handle POST request def post(self, *args, **kwargs): formset = CalculatorForm(data=self.request.POST) # Check if submitted forms are valid if formset.is_valid(): for form in … -
How to replace ID in one table with corresponding value from another table without make any change to the database
I am trying to add a column to my website without making any changes to my database -
In a FilterView, how can I keep track of "selected" items when paginating
I'm learning Django. I'd like to display a list of products, select some and send them to be processed by a method (that will generate pdf price tags for each of them). I want to be able to browse the list and filter it. The selected products, should be "extracted" of the main list and appear in another list. So far I'm able to filter and paginate. For the selecting par thought I'm kind of stuck. I use checkbox to select the products. The problem is that every time I modify a filter, all the checkboxes are reset. I'm using a FilterView. In my template, the filters buttons are just links with "href=" containing the values for the filters as url parameters. The view take parameters via request.GET.get in the get_context_data method I suppose I could add a filter button that would add the product pk as a url parameter, but it doesn't sound very clean to me. What would be the most djangoic way to achieve this?