When two tables with foreign key (FOREIGN KEY) restrictions are prepared in Model, Form wants to display the registration data associated with the user (login user). I stumbled upon the way I used the class-based generic view, so make a note of it.
For example, create the following Todo list.
At this time, there are multiple categories that can be selected for one Todo Item.

Suppose you have two Categories registered as logged-in users, as shown below.

At this time (as a matter of course), I want to select only the Category registered by the logged-in user in the registration and edit form.

Python 3.8.0 Django 3.0.4 Bootstrap 4.1.3 Plugin: django-bootstrap-modal-forms
I referred to this page.
# mypeoject/myapp/models.py
import datetime
from django.db import models
class Category(models.Model):
    category_name = models.CharField(max_length=20, unique=True)
    user = models.ForeignKey(
        'auth.User',
        on_delete=models.CASCADE
    )
    def __str__(self):
        return self.category_name
class TodoItem(models.Model):
    item = models.CharField(max_length=50)
    item_date = models.DateField(default=datetime.date.today)
    categories = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL)
    user = models.ForeignKey(
        'auth.User',
        on_delete=models.CASCADE
    )
    def __str__(self):
        return self.item
In the case of the above example, the Model used has two tables, a TodoItem table and a Category table with a foreign key (FOREIGN KEY) constraint.
# mypeoject/myapp/forms.py
from bootstrap_modal_forms.forms import BSModalForm
from django import forms
from queryset_filtering_app.models import TodoItem, Category
class CreateUpdateTodoItemForm(BSModalForm):
    class Meta:
        model = TodoItem
        fields = ['item', 'item_date', 'categories']
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(CreateUpdateTodoItemForm, self).__init__(*args, **kwargs)
        self.fields['categories'].queryset = Category.objects.filter(user=user)
class CreateCategoryForm(forms.ModelForm):
    class Meta:
        model = Category
        fields = ["category_name"]
forms.py adds the description of def \ _ \ _ init \ _ \ _ () as above.
# mypeoject/myapp/views.py
class CreateTodoItemFormView(BSModalCreateView):
    template_name = 'template_name.html'
    form_class = CreateUpdateTodoItemForm
    success_message = 'Success: Item was created.'
    success_url = reverse_lazy('redirect_name')
    def get_form_kwargs(self):
        kwargs = super(CreateTodoItemFormView, self).get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs
    def form_valid(self, form):
        form.instance.user_id = self.request.user.id
        return super(CreateTodoItemFormView, self).form_valid(form)
class UpdateTodoItemFormView(BSModalUpdateView):
    model = TodoItem
    template_name = 'template_name.html'
    form_class = CreateUpdateTodoItemForm
    success_message = 'Success: Item was updated.'
    success_url = reverse_lazy('redirect_name')
    def get_form_kwargs(self):
        kwargs = super(UpdateTodoItemFormView, self).get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs
In views.py, add the description of def get \ _form \ _kwargs () as above. The def form \ _valid () part of CreateView is the code to register the login user as user at the time of registration.
Described how to display the registration data associated with the user on the registration / edit form. I think it's a basic point, but if you're a beginner like me, you may not be able to find a suitable article and you may not be able to solve it immediately, so I hope you can refer to it.
Recommended Posts