Coming soon - Get a detailed view of why an account is flagged as spam!
view details

This post has been de-listed

It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.

1
Rendering specific fields multiple times in Django model form
Post Body

I have a model in which I want to render specific fields multiple times depending on how much the user wants to fill in, while rest of the model fields remain the same. Below is an example model. I want to render the model form in such a way that the fields 'building' and 'tour_date' can be repeated as many times as required while 'name' and 'email' remain the same. I looked at inlineformset_factory but I think it needs a parent model. I don't think it serves my purpose although I would love to have some of its features like 'extra' and 'can_delete'. The saved records have to be saved as new rows in the 'Tour' table. Another challenge I am facing with the below example is that the 'building' field has to be a drop-down. I have provided the forms.py below for reference.

How can I write a view for such a requirement in Django 3.0? Requesting some assistance and guidance.

models.py:

class Tour(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(max_length=100)
    building = models.CharField(max_length=255)
    tour_date = models.DateField()
    ...

    class Meta:
        managed = True
        unique_together = ('name', 'building')

forms.py:

class TourForm(forms.ModelForm):
    building = forms.ModelChoiceField(
        widget=forms.Select,
        queryset=Country.objects.filter(city='ABC'),
        required=True
    )

    class Meta:
        model = Tour
        fields = ['name', 'email', 'building','tour_date']

views.py:

def add_tours(request):
    if request.method == 'POST':
        form = TourForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('tours-browse')
    else:
        form = TourForm()
    template = 'data/tours_add.html'
    context = {'form': form}
    return render(request, template, context)

Author
User Disabled
Account Strength
0%
Disabled 4 months ago
Account Age
5 years
Verified Email
Yes
Verified Flair
No
Total Karma
6,531
Link Karma
663
Comment Karma
5,737
Profile updated: 4 days ago
Posts updated: 1 year ago

Subreddit

Post Details

We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
4 years ago