I am really new to django, and I have some questions about how django's M2M works and also how it works with the modelForm or the forms.Form am currently working on an application that contains the following models:
class Agent(models.Model):
user = models.ForeignKey(User)
assigned_by = models.ForeignKey('self')
date = models.DateField(auto_now_add=True)
def __str__(self):
return str(self.user)
class Region(models.Model):
name = models.CharField(max_length=50)
# Agent to Region many-to-many
class ARM2M(models.Model):
agent = models.ForeignKey(Agent)
region = models.ForeignKey(Region)
is_manager = models.BooleanField(default=False)
Constraints: an agent can be in multiple regions, and he/she can be one of the managers in any of those regions that he/she is in.
Question#1: is there a way to present such logic with the many-to-many feature in django model?
-end-of-question#1-
So I have this AgentForm for an agent manager to add an new agent in his/her regions. But I know this form is not working: because in the MultipleChoiceField, I have no way to get the current loggedin agent, to present the available regions. In other words, I am stuck.
class AgentForm(forms.Form):
agent = forms.IntegerField(widget=forms.HiddenInput())
regions = forms.MultipleChoiceField(choices=RAM2M.objects.filter(agent=agent, is_manager=True))
def save(self):
agent_id = self.cleaned_data['assigned_by']
agent = Agent.objects.get(pk=int(agent_id))
self.instance.assigned_by = agent
super(AgentForm, self).save()
class Meta:
model=Agent
exclude = ('assigned_by')
Question#2: How do I construct a form for an existing agent to add a new agent to the regions where he/she is a manager.
Thanks,
Maxim