简体   繁体   中英

Django Create a number of child objects in a create view with parent object

I have two models that are related by a foreign key. I am trying to add logic to a form field in the create view where the user fills out a number n and it generates n items in the database.

Model.py

class Environment(models.Model):
    name = models.CharField(max_length=50)

class Item(models.Model):
    environment = models.ForeignKey(Environment, on_delete=models.CASCADE)
    uid = models.CharField(max_length=50, unique=True, null=True, blank=True)
    def __init__(self):
        super(Item, self).__init__()
        self.uid = str(uuid.uuid4())

view.py

class EnvironmentCreateView(CreateView):
    '''View for creating Environments'''
    model = Environment
    form_class = EnvironmentCreateForm
    template_name = 'Environment_create.html'
    success_url = reverse_lazy('main:Environment list')

forms.py

If the items field is filled by the user it should generate n items in the database. The current approach I took has an issue overriding the save function. Not really sure if I need to use inline_formeset

 class EnvironmentCreateForm(forms.ModelForm):
        name =forms.CharField(max_length=50, required=True, label='Product Name')
        items =forms.IntegerField(min_value =0, max_value = 100,required=False, label='Number of Items')
        class Meta:
            model = Environment
            fields = ['name',]

        def save(self):
            if Environment.is_valid(): 
                Environment.save() 
            if self.items >= 0:
                for i in range(self.items):
                   Item.objects.create(Environment, uid =str(uuid.uuid4()) )

I figured the answer for this but it is in function based views:

forms.py Get rid of the bottom part

 class EnvironmentCreateForm(forms.ModelForm):
        name =forms.CharField(max_length=50, required=True, label='Product Name')
        items =forms.IntegerField(min_value =0, max_value = 100,required=False, label='Number of Items')
        class Meta:
            model = Environment
            fields = ['name',]

views.py

def EnvironmentCreateView(request):

    if request.method == 'POST':
        form =  EnvironmentCreateForm(request.POST)
        if form.is_valid():
            name =form.cleaned_data['name']
            items =form.cleaned_data['items']
            env = form.save(commit = False) # this item must be saved first before using the id for the second item
            env.save()
            if units is not None:
                for i in items:
                    Item.objects.create(environment =env)
    else:
            form =  EnvironmentCreateForm()
        return render(request, 'HTMLPAGE.html', {'form': form})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM