Re: How do I add a Foreign Key Field to a ModelForm in Django?

Add the following method in your class Mobile to make it return the name of mobile object.

def __unicode__(self):
    return self.name

This will return the name whenever a mobile object is created.




On Tue, Jul 8, 2014 at 7:46 PM, Ram Ganesh <ramganesh7k@gmail.com> wrote:


it shows a drop down menu which is have mobile objects.
How to get mobile name?
confused about - self.queryset = forms.ModelChoiceField(queryset=Mobile.objects.all(label="select mob")

models.py

class Mobile(models.Model):
    name = models.CharField(max_length=50)
    price = models.DecimalField(max_digits=7,decimal_places=2)

class Agent(models.Model):
    mobile = models.ForeignKey(Mobile)
    agent_name = models.CharField(max_length=50)
........

forms.py

class MobileForm(ModelForm):
    class Meta:
        model = Mobile
   
class AgentForm(ModelForm):
    class Meta:
        model = Agent

    def __init__(self,  *args, **kwargs):
        super(AgentForm, self).__init__(*args, **kwargs)
        self.queryset = forms.ModelChoiceField(queryset=Mobile.objects.all(label="select mob")
........

views.py   

def add_agent(request):
    if request.method == 'GET':
        agent_form = AgentForm()
        return  render(request,'agentForm.html', {'agent_form':agent_form,})
 ........


in addAgentForm.html

{% if not agents_details %}
        <form action="" method="POST" enctype="multipart/form-data">
            {% csrf_token %}
            <table> {{ agent_form }} </table>
            <input type="submit" value="insert">
        </form>
    {% endif %}
........

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/446e0adf-1766-43db-b5e9-3f68597abbbb%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAOdEGu2N8c%3Dhi3yoAYzm%2BVFyx-W3r06YoLiTPKiV1VRVC7Y4TA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.