-1

I have 2 models

class A(models.Model):
    id=models.AutoField(primary_key=True)
    name=models.CharField(max_length=200)


class B(models.Model):
   id=models.AutoField(primary_key=True)
   user=models.ForeignKey(A)
   name=models.CharField(max_length=200)


#forms.py
class BForm(ModelForm):
    class Meta:
        model=B
        fields=('name','user')
    def __init__(self,user_name,*args,**kwargs):
       super(BForm,self).__init__(*args,**kwargs)
       if user_name:
          self.field['user']=forms.ModelChoiceField(queryset=A.objects.filter(name__icontains=user_name)


#views.py

def myview(request,user_name):
    formset=formset_factory(BForm(user_name=user_name),extra=10)

I am getting following error

'BForm' object has no attribute 'name'

Actually i only want only selective value of class A to shown in my formset

ha22109
  • 8,036
  • 13
  • 44
  • 48

1 Answers1

0

There are a few issues here:

Firstly, the __init__ method form the BForm class looks wrong. user_name is a keyword argument, but below you have the condition if user, without defining user anywhere.

Secondly, you can't initialise the form with the user_name argument when defining the formset. It looks like you are trying to do the same as in the stack overflow question Passing Custom Form Parameters to Formset.

Thirdly, please supply the entire traceback. Only including one line of the traceback,

'BForm' object has no attribute 'name'

makes it harder to track down where the problem is.

Community
  • 1
  • 1
Alasdair
  • 298,606
  • 55
  • 578
  • 516