Answers for "pre filled from django"

0

pre filled from django

# =======================================================
# Non-Model Forms - use 'initial' and supply a dictionary

# views.py
form = YourForm(initial={'charfield1': 'foo', 'charfield2': 'bar'})

# forms.py
class YourForm(forms.Form):
  charfield1 = forms.CharField(max_length=3)
  charfield2 = forms.CharField(max_length=3)
  choicefield = forms.ModelChoiceField(MyModel.objects.all())

# ======================================================================
# Model Forms - use 'instance' and supply with an instance of your model

# models.py - Create Model
class Office(models.Model):
  location = models.CharField(max_length=30)

# forms.py - Create Model Form
class OfficeForm(forms.ModelForm):
  class Meta:
    model = Office
    fields = '__all__'

# views.py - 
def offices(request):
  office = Office.objects.get(pk=request.user.office.id)
  form = OfficeForm(instance=office)
  return render(request, '.../index.html', {'form':form})
Posted by: Guest on June-14-2021

Python Answers by Framework

Browse Popular Code Answers by Language