[Django] Display registration data associated with users on the registration / edit form (Form)

Thing you want to do

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. todo_2.png

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

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.

todo_1.png

environment

Python 3.8.0 Django 3.0.4 Bootstrap 4.1.3 Plugin: django-bootstrap-modal-forms

manner

I referred to this page.

Model to use


# 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.

Editing forms.py


# 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.

Edit views.py


# 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.

in conclusion

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

[Django] Display registration data associated with users on the registration / edit form (Form)
Recreate the django staff registration screen with class
Display the image after Data Augmentation with Pytorch
How to register the same data multiple times with one input on the Django management screen
Until the start of the django tutorial with pycharm on Windows
Display the time in Django according to the user's region (UTC)
Get started with the Python framework Django on Mac OS X
[Django] Correct the plural form of the model name on the management screen
Try Ajax on the Django page
Display the absolute path on the Finder
Get the value from the [Django] Form
Edit the file of the SSH connection destination server on the server with VS Code
How to make only one data register on the Django admin screen