0

I'm trying to learn some django basics following one turorial from youtube and have got strange result when I try to create some model instances using forms. Django implicitly creates two duplicate instances. This is my view:

from django.shortcuts import render
from .forms import ProductModelForm
from .models import Product

def create(request):
    form = ProductModelForm(request.POST or None)
    if form.is_valid():
        obj = form.save(commit=False)
        data = form.cleaned_data
        Product.objects.create(title_text=data.get("title_text"))
        obj.save()
    return render(request, "test_app/create.html", {"form": form})

Form:

from django import forms
from .models import Product

class ProductModelForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = [
            "title_text",
        ]

And a template:

{% block content %}

<form action="." method="post">{% csrf_token %}

    {{ form }}
    <button type="submit">Save Model</button>

</form>

{% endblock %}

Thanks in advance.

Alex
  • 153
  • 7

2 Answers2

0
obj = form.save(commit=False)

this create one instance first.

obj.save()

And then this creates another instance.

pullidea-dev
  • 1,768
  • 1
  • 7
  • 23
  • 1
    `obj = form.save(commit=False` and `obj.save()` create ONE object together. The second object is being created by `Product.objects.create(title_text=data.get("title_text"))` – DilIsPickle May 20 '21 at 22:35
  • Thanks. Hope to see you again. – pullidea-dev May 20 '21 at 22:39
  • 1
    @AlexStelmakh Yeah, this is no the correct answer. The one accepted should be the one from DilIsPickle – gdef_ May 21 '21 at 00:18
  • @gdef_ This is a first one and it do the job for me. Maybe not so comprehensive, but anyway. – Alex May 21 '21 at 07:23
0

This creates an object

obj = form.save(commit=False) 
obj.save()

And this creates an object

data = form.cleaned_data
Product.objects.create(title_text=data.get("title_text"))

Try this

obj = form.save(commit=False)
data = form.cleaned_data
obj.title_text = data.get("title_Text")
obj.save()
DilIsPickle
  • 113
  • 1
  • 6