2

So i created simple models (pasted below) and passed forms based on those models to template view. Now i want to add button which will allow user to add more fields of Ingrediends class and there I have few questions. Is it somehow possible to do without using JS only in django? If not what is the best way to do it? And one more question about the way I am dealing with forms. Is it ok or should I put both models in one form? Thank you for answers.

MODELS:

class Recipe(models.Model):
    title       = models.CharField(max_length=254)
    author      = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL)
    description = models.CharField(max_length=200)
    add_date    = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

class Ingrediends(models.Model):
    name    = models.CharField(max_length=254)
    recipe  = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name="ingredient")

FORMS:

class RecipeForm(forms.ModelForm):
    class Meta:
        model = Recipe
        fields = ('title',)

class IngrediendForm(forms.ModelForm):
    class Meta:
        model = Ingrediends
        fields = ('name', )

Template:

{% extends 'recipes/base.html' %}
{% block body_block %}
  <form class="" method="post">
    {% csrf_token %}
    {{form.as_p}}
    {{ingredient_form.as_p}}
    <input type="submit" value="Add recipe">
  </form>
{% endblock %}

In case I didn't explain well what I want:

Before:

Title: [_______]

Ingredient: [________] [+]<-click

After:

Title: [_______]

Ingredient: [________]

Ingredient: [________] [+]<-click

tucki
  • 119
  • 1
  • 10
  • Here are a couple of resources that should help: https://stackoverflow.com/questions/6142025/dynamically-add-field-to-a-form and https://www.caktusgroup.com/blog/2018/05/07/creating-dynamic-forms-django/ – Dan Swain Nov 18 '18 at 00:19
  • 1
    Without JS this will require a lot of unnecessary code. – Reez0 Nov 18 '18 at 09:25

0 Answers0