Question:
How to create forms in Django with multiple Many-to-Many fields in Models

Problem

I have these three models with two many-to-many fields in BlogPost models like


class Category(models.Model):

    name = models.CharField(max_length=150)

    

    def __str__(self) -> str:

        return self.name


class Tag(models.Model):

    name = models.CharField(max_length=150)

    def __str__(self) -> str:

        return self.name


class BlogPost(models.Model):

    title = models.CharField(max_length=200)

    author = models.ForeignKey(User , on_delete=models.CASCADE)

    categories = models.ManyToManyField(Category)

    tags = models.ManyToManyField(Tag)

    content = models.TextField()

    created_at = models.DateTimeField(auto_now_add=True)

    updated_at = models.DateTimeField(auto_now=True)

    

    def __str__(self):

        return self.title


and form on the client side as follows


{% extends 'blog_project/base.html' %}

{% load widget_tweaks %}


{% block content %}

    <div class='login-container'>

        <h2 class='login-heading'> Create New Post </h2>

        <form class='login-form' method='post'>

            {% csrf_token %}

            {% for field in form.visible_fields %}

                <div class="form-group pb-3">

                    <label for="{{ field.id_for_label }}">{{ field.label }}</label>

                    {{ field|add_class:'form-control' }}

                        {% for error in field.errors %}

                        <span class="help-block">{{ error }}</span>

                        {% endfor %}

                </div>

            {% endfor %}

            <div class='form-group'>

                <button type = 'submit'>Post</button>

                <a href="{% url 'blog:blog_list' %}">Go Back</a>

            </div>

        </form>

    </div>

    

{% endblock%}


It allows me to select from the existing categories but not allow me to add other categories.

I want to create a form in Django that allows a user to select from the categories on the client side as well as create new categories or tags and save them to the database so that other users can select from these or search them at least.


Solution

For that, you will need to manually render a field the user can enter the name of the Category they want to create. You can access the entered value in your view, save it to the database, and add it to the Blog Post object.

Inside your HTML form tag, include:


<input type="text" name="new-category">


Then in your view, you can access and save the entered value:


def add_blog(request) :

    ... 

    new_category = request.GET("new-category")

    if new_category:

        category = Category.objects.create(name=new_category)

    ... 

    # if you want to immediately add the new category to the instance of a BlogPost

    blog_post = blog_post_form.save() 

    blog_post.categories.add(category)


Answered by: >McPherson

Credit: >StackOverflow


Blog Links

>How to manage the Text in the container in Django?

>Fix webapp stops working issue in Django- Python webapp

>Creating a form in Django to upload a picture from the website

>Sending Audio file from Django to Vue

>How to keep all query parameters intact when changing page in Django?

>Solved: TaskList View in Django

>Implement nested serializers in the Django rest framework

>How to filter events by month in Django?

>Sorting the restframework in Django

>Ways to access instances of models in view in order to save both forms at once in Django

>What makes index.html have such kind of name in Django?

>Fix Module Not Found during Deployment- Django

>Creating a Django with existing directories, files, etc.?

>How to Read a CSV file with PHP using cURL?


Nisha Patel

Nisha Patel

Submit
0 Answers