A
A
Alexander2018-04-18 14:21:14
Django
Alexander, 2018-04-18 14:21:14

How to display the same field multiple times in a form?

Hello, I have been thinking about the task for several days now, how to display the categories field several times in the form?
I have a model

#models.py
class СategoryPrice(models.Model)
    performer = ForeignKey(Performer)
    category = ForeignKey(Category)
    price = Charfield(max_length=5)
 
class Category(models.Model):
    name = models.CharField(max_length=64)
 
    def __str__(self):
        return self.name
 
 
class Performer(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        blank=True,
        unique=True
    )
    company_name = models.CharField(max_length=30)
    categories = models.ManyToManyField(Category, throught=CategoryPrice)

And form
class AddPerformerForm(ModelForm):

    class Meta:
        model = Performer
        fields = '__all__'
        exclude = ['user']

How to make it so that the company_name fields are displayed on the page, and 3 categories (category, price)?
Here's what I want to get as an output https://jsfiddle.net/bgsq9Lr9/
And question number 2: Did I choose the right relationship for Performer.categories many to many when solving this problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Vorobyov, 2018-04-21
@AlexMine

In question 2, the doubt is correctly noted, if you only need to save the prices of the artist for a certain category, it is easier to
use
: situations are overkill. This is from what is seen from the presented example. Perhaps the full project imposes other requirements. Well, if, nevertheless, the first option: 1. Display one model field several times in the form - it means that the form needs to be customized and concise fields = '__all__' is indispensable:

class AddPerformerForm(ModelForm):
   category1 = прописываем обычное поле формы, дублирует поле модели (max_length, и т.п.)
   category2 = прописываем обычное поле формы еще раз

    class Meta:
        model = Performer
        fields = ('performer`, 'price`) # вместо "все", пишем остальные нужные поля кроме категорий
        # exclude тогда не требуется

2. Since the form is custom, the view also needs to be written with code, where the data of category1 and category2, or however many of them there are (after all, this is many-to-many, and you decided to manually add them to html in an arbitrary amount) are processed in this order :
- (1) save the form with the save(commit-false) option,
- (2) add all the necessary categories to the performer model and, finally
- (3) save the model/form to the database via save().
But rebuilding model relationships could make things a lot easier and would allow using concise form declarations and built-in CreateView and so on.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question