V.Subramani Raju
V.Subramani Raju

Reputation: 55

django modelform foreignkey update

I have my model as this:

class Event(models.Model):
    EventId = models.UUIDField(primary_key=True)
    Winner = models.ForeignKey('Participant', on_delete=None)

class Participant(models.Model):
    ID = models.UUIDField(primary_key=True)
    Name = models.CharField()

I am trying to update an existing instance of the Event object using this in form.py

class UpdateWinner(ModelForm):
    def __init__(self, *args, **kwargs):
        e = kwargs.pop('e', '')
        super(UpdateWinner, self).__init__(*args, **kwargs)
        self.fields['Winner'] = forms.ModelChoiceField(queryset=e))

    class Meta:
        model = Event
        fields = '__all__'

and in views.py

def update_winner(request, event_id):
        if request.method == 'POST':
            form = UpdateWinner(request.POST, instance=Event.objects.get(EventId=event_id))
            if form.is_valid():

       else:
          event_par = Participant.objects.filter(some query)
          form = UpdateWinner(instance=event, e=event_par)

I did check by printing the eventid, correct value is getting passed. but for some reason Winner field is causing some error with the form.is_valid() function and I am getting an error "'str' object has no attribute 'model'". Can anyone help me out here

Upvotes: 1

Views: 1102

Answers (2)

scharette
scharette

Reputation: 9977

The error comes from using that line:

e = kwargs.pop('e', '')

This means if the key e is not in kwargs return ' '. Then you use it there:

 self.fields['Winner'] = forms.ModelChoiceField(queryset=e))

Which result in an empty queryset.

Upvotes: 0

souldeux
souldeux

Reputation: 3755

Since you don't provide an e kwarg when handling POST requests in your view, your custom __init__ function sets e = ''. This causes the error when you go to define the queryset - that empty string has no attribute model. Try:

class UpdateWinner(ModelForm):
    def __init__(self, *args, **kwargs):
        e = kwargs.pop('e', None)
        super(UpdateWinner, self).__init__(*args, **kwargs)
        if e is not None:
            self.fields['Winner'] = forms.ModelChoiceField(queryset=e))

Upvotes: 1

Related Questions