简体   繁体   中英

Django: Limit choices in a models.Charfield by PrimaryKey

Another question from me tonight and I hope I can explain it adequately:

I got three classes in my "models.py":

class Customer(models.Model):
    full_name = models.CharField(max_length=100, null=True, unique=True)
    short_name = models.CharField(max_length=8, null=True, unique=True)

class Project(models.Model):
    customer = models.ForeignKey(Customer, null=False, on_delete=models.CASCADE)
    name = models.CharField(max_length=255, null=True, unique=True)
    ...

class Entry(models.Model):
    user = models.ForeignKey(User, null=True, blank=False, on_delete=models.CASCADE)
    customer = models.ForeignKey(Customer, null=True, blank=False, on_delete=models.CASCADE)
    project = models.ForeignKey(Project, null=True, blank=False, on_delete=models.CASCADE)
    date = models.DateField()
    shortText = models.CharField(max_length=100, null=False, blank=False)
    ...

Note: One Customer can have multiple Projects.

On one of my sites there's a table with buttons beside each "Customer". The plan is, that it should lead me to another page, were the user can write and save his "Entry". Right now, the PrimaryKey inside the Button/Link contains the ID of the "Customer".

My question is: is it possible to limit the choices of the "Project" (inside a Drop-Down-Menu) to the "Customer" that has been clicked on? And is creating a ModelForm the right thing to do?

Thanks to all of you and a good night!

Well, don't know if this is the right way, but I found a solution for my problem:

  1. Wrote a "forms.ModelForm" for my view-function...

     class EntryForm(ModelForm): class Meta: model = Entry fields = '__all__' def __init__(self, *args, pk, **kwargs): super().__init__(*args, **kwargs) self.fields['project'].queryset = Project.objects.filter(customer_id=pk)
  2. Insert my ModelForm into the view-function...

     def WriteEntry(request, pk): form = EntryForm(pk=pk) if request.method =='POST': form = EntryForm(request.POST, pk) if form.is_valid(): form.save()... context = {'form': form} return render(request, '...html', context)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM