Home > front end >  Is it possible to user this code like the first one instead of second?
Is it possible to user this code like the first one instead of second?

Time:02-02

def create_new(request):
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        form.id_author = request.user.id
        if form.is_valid():
            form.save()
            return redirect('home')
    return render(request, 'main/create_new.html')
def create_new(request):
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        if form.is_valid():
             article = form.save(commit=False)
             article.author = request.user
            article.save()
            return redirect('home')
    return render(request, 'main/create_new.html')

Is it possible to change the 2nd code into the first code?? it shows some kind of error

CodePudding user response:

No, at first you always need to check whether the form is valid or not, then after you can save the form with commit=False which creates a temporary instance, then you should assign any value in that instance.

The second approach is correct.

  • Related