Rk..
Rk..

Reputation: 753

Populating Django ManyToManyField with custom data from another django model

I have the Model1 of app1

class Event(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(max_length=500)
    eventdate = models.DateField()
    created = models.DateTimeField(auto_now_add=True)

Model 1 of app2

class Register(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    select_the_event = models.ManyToManyField(Event)
    created = models.DateTimeField(auto_now_add=True)

Event database contain event information for one complete year.

How to populate the "select_the_event" with list of selected events that are valid for next 60 days?

Upvotes: 0

Views: 75

Answers (2)

Raj Subit
Raj Subit

Reputation: 1557

If you are have forms.py for the Register model, then inside the RegisterForm class you can add attribute

class RegisterForm(forms.ModelForm):
    ....
    ....
    select_the_event = forms.ModelMultipleChoiceField(queryset=Event.objects.filter(
        event_date__range=[datetime.datetime.now().date(), datetime.datetime.now().date() + datetime.timedelta(60)])
)

Upvotes: 2

Leticia
Leticia

Reputation: 171

In your ModelForm, assign a custom queryset to the ModelMultipleChoiceField for select_the_event:

select_the_event = forms.ModelMultipleChoiceField(
                     queryset=Event.objects.filter(...))

Upvotes: 0

Related Questions