[Django memo] I want to set the login user information in the form in advance

Thing you want to do

When posting a new post on the posting site, instead of typing in your own name, you want to set the logged-in user's information (such as your name) in the form in advance and save the trouble of typing in your name.

1. Prepare the model

app/models.py


from django.db import models
from django.contrib.auth import get_user_model


class Post(models.Model):
    author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    content = models.TextField()

    def __str__(self):
        return self.title

Prepare a Post model and set up three fields [Poster, Title, Content]. ʻAuthor = models.ForeignKey (get_user_model (), on_delete = models.CASCADE)get_user_model ()calls the entire class of the currently logged-in user, and this one line calls the ʻauthor` field and the logged-in user. Is linked. There are several ways to refer to the user model, but it is not good to refer to the user model directly. Reference: https://djangobrothers.com/blogs/referencing_the_user_model/

2. Prepare the form.

app/forms.py


from django import forms
from .models import Post

class PostForm(forms.ModelForm):
    class Meta():
        model = Post
        fields = (
            'title',
            'content',
        )

This time, I used a model form. Create a PostForm class by inheriting the ModelForm included in forms.py provided by Django. Specify the model to be inherited by model = Post, and specify two fields except author. There is no need to bother to specify the author here.

3. Set the login user in the view

app/views.py


from django.shortcuts import render, redirect
from .models import Post
from . import forms

def form_view(request):
    if request.method == 'POST':
        form = forms.PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save()
            return redirect('sns:index')
    else:
       form = forms.PostForm()
    return render(request, 'sns/form_view.html', {'form': form})

In the form_view function, it is necessary to change the behavior depending on whether POST is received as request (ʻif request.method =='POST': ) or GET (ʻelse:). For example, when the button "New Post" is pressed and the form_view function is called by the URL dispatcher, the request becomes'GET', so the process of simply displaying the form is executed as shown below.

    else:
        form = forms.PostForm()
    return render(request, 'app/form_view.html', {'form': form})

When something is entered in the displayed form, the submit button is pressed, and the form_view function is called by the URL dispatcher, the request becomes'POST', so the code shown below is executed.

    if request.method == 'POST':
        form = forms.PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save()
            return redirect('app:index')
  1. Store the information entered by form = forms.PostForm (request.POST) in form.
  2. ʻif form.is_valid (): Check if the information entered with is correct, and save formwithpost = form.save (commit = False). At this time, set commit = False` in the argument and tell that it will be modified a little more before saving completely.
  3. In post.author = request.user, specify the request ʻuser` (that is, the logged-in user) in the author field of post.
  4. Save the contents entered in the form with post.save () and the logged-in user name.
  5. Specify the redirect destination with return redirect ('app: index').

Recommended Posts

[Django memo] I want to set the login user information in the form in advance
Pass login user information to view in Django
Set the form DateField to type = date in Django
[Linux] I want to know the date when the user logged in
I want to use the Django Debug Toolbar in my Ajax application
I want to pin Datetime.now in Django tests
I want to store DB information in list
I want to display the progress in Python!
I want to set a life cycle in the task definition of ECS
I want to scroll the Django shift table, but ...
I want to write in Python! (3) Utilize the mock
I want to use the R dataset in python
I want to get an error message in Japanese with django Password Change Form
How to update user information when logging in to Django RemoteUserMiddleware
I want to get the operation information of yahoo route
[Django] I want to log in automatically after new registration
I can't log in to the admin page with Django3
I want to make the Dictionary type in the List unique
I want to align the significant figures in the Numpy array
I didn't want to write the AWS key in the program
LINEbot development, I want to check the operation in the local environment
I want to make the second line the column name in pandas
I want to pass the G test in one month Day 1
I want to know the population of each country in the world.
I want to pin Spyder to the taskbar
A note that you want to manually decorate the parameters passed in the Django template form item by item
I want to output to the console coolly
I want to print in a comprehension
I want to handle the rhyme part1
Information recording memo using session in Django
[C language] I want to generate random numbers in the specified range
I want to handle the rhyme part3
I want to batch convert the result of "string" .split () in Python
I want to explain the abstract class (ABCmeta) of Python in detail.
I want to sort a list in the order of other lists
I want to use complicated four arithmetic operations in the IF statement of the Django template! → Use a custom template
I want to display the progress bar
I want to leave an arbitrary command in the command history of Shell
I want to embed Matplotlib in PySimpleGUI
Output user information etc. to Django log
I want to handle the rhyme part2
I want to handle the rhyme part5
I want to handle the rhyme part4
I want to create an API that returns a model with a recursive relationship in the Django REST Framework
I want to visualize where and how many people are in the factory
[Python] I want to know the variables in the function when an error occurs!
I want to use Python in the environment of pyenv + pipenv on Windows 10
I want to see a list of WebDAV files in the Requests module
I want to store the result of% time, %% time, etc. in an object (variable)
I want to get the file name, line number, and function name in Python 3.4
I referred to it when I got stuck in the django geodjango tutorial (editing)
I want to do Dunnett's test in Python
I want to create a window in Python
I want to handle the rhyme part7 (BOW)
I want to merge nested dicts in Python
I implemented Google's Speech to text in Django
I want to customize the appearance of zabbix
I want to use the activation function Mish
I want to upload a Django app to heroku
I want to plot the location information of GTFS Realtime on Jupyter! (With balloon)
I want to set up a mock server for python-flask in seconds using swagger-codegen.