Initialize Dropdown Keys

I want to fill out two foreign key fields in one of my forms. The corresponding bit of code is as follows:

if request.method == 'POST':
    form = IssuesForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        form.save()
else:
    form = IssuesForm(initial={'vehicle': stock_number, 'addedBy': request.user, })

vehicleindicates a class vehicle. addedBymust contain the current user.

However, the drop-down lists are not initialized as I want ... I still need to select the car and user. From this, I have two questions:

  • What could be the problem?
  • What is the best way to make these forms read-only?

EDIT 1 Class IssueFormlooks like this:

class Issues(models.Model):
   vehicle = models.ForeignKey(Vehicle)
   description = models.CharField('Issue Description', max_length=30,)
   type = models.CharField(max_length=10, default='Other', choices=ISSUE_CHOICES)
   status = models.CharField(max_length=12, default='Pending', 
     choices=ISSUE_STATUS_CHOICES)
   priority = models.IntegerField(default='8', editable=False)
   addedBy = models.ForeignKey(User, related_name='added_by')
   assignedTo = models.CharField(max_length=30, default='Unassigned')
   dateTimeAdded = models.DateTimeField('Added On', default=datetime.today, 
     editable=False)
   def __unicode__(self):    
    return self.description

Form class

class IssuesForm(ModelForm):   
  class Meta:
    model = Issues
    exclude = ('assignedTo')
+3
source share
2 answers

, addedBy ? , ( , , Firebug). .

if request.method == 'POST':
    form = IssuesForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        issue = form.save(commit=False)
        issue.addedBy = request.user
        # any other read only data goes here
        issue.save()
else:
    form = IssuesForm(initial={'vehicle': stock_number}) # this is related to your first question, which I'm not sure about until seeing the form code
+1

: __init__method, html-:

def __init__(self, *args, **kwargs):
    super(IssuesForm, self).__init__(*args, **kwargs)
    for key in self.fields.keys():
        self.fields[key].widget.attrs = {'disabled': 'disabled'}

, POST-, , . __init__method, super.

0

Source: https://habr.com/ru/post/1735091/


All Articles