I was wondering how to auto populate fields in a form like in this picture http://prntscr.com/lkn7x . Here is what I have so far for my forms.
class PIREPForm(ModelForm):
class Meta:
model = PIREP
In the model form you can pass the instance which will be mapped to the form fields
form = TestForm(instance = test_instance)
Otherwise, if you want to populate some fields you could pass the initial argument
form = TestForm(initial = {'field_name':field_value,...})
Related
I have two models.
class Order(..):
...
class OrderImage(..):
order = ForeignKey('Order...)
And I have a form with dropzone.js.
This form returns data suitable for creating an order using just ViewSet but it obviously doesn't create OrderImage objects, even there are image[0], image[1] etc. data in the POST request.
What's the best way to create OrderImages alongside with the Order in DRF?
modify dropzone output (didn't find the way)
Modify request.data inside ViewSet (how?)
Modify OrderSerializer to create OrderImage objects?
How would you do that?
EDIT
class SubOfferImageSerializer(serializers.ModelSerializer):
class Meta:
model = SubOfferImage
fields = ['file']
class SubOfferSerializer(serializers.ModelSerializer):
images = SubOfferImageSerializer(many=True, required=False)
client_status_display = serializers.CharField(source='get_client_status_display', read_only=True)
system_status_display = serializers.CharField(source='get_system_status_display', read_only=True)
class Meta:
model = SubOffer
fields = [field.name for field in model._meta.fields] + ['client_approve_url',
'system_decline_url',
'client_status_display',
'system_status_display','images']
Now the problem is that I have raw images in the data, not serialized SubOrderImage objects.
I'm trying to change the input overriding perform_create but it doesn't seem to be a best option. The better would be to do that inside serializer.
I have a model Customer, which inherits from a User model, and adds a new field.
class Customer(User):
customer_since: models.Datefield()
I then want to use use a generic view to create customers:
class CustomerCreate(CreateView):
model = Customer
form_class = CustomerForm
When I create a new customer, I want to use the data from request.user to autofill the form with the inherited fields. How can I do that?
I know that if I was creating the record manually, I would do it like this:
Customer.objects.create(user_ptr=request.user, customer_since=datetime.date.today())
but with a generic view, the form is generated automatically and saved by the form_valid method of the CreateView, how do I tell the form to include the proper user reference?
After switching to inline formset I ended up with:
def dns_view(request, domain):
dnszone = get_object_or_404(DNSSQL, zone = domain)
form1 = EditDNSZone(instance = dnszone)
forms = EditDNSEntry(instance = dnszone, prefix = 'entries')
formsmx = EditDNSEntryMX(instance = dnszone, prefix = 'mxentries')
After trying to save all forms I managed to save only form1.
How do I save all forms?
Django's formset is for multiple instances of the same form. You are trying to save multiple form classes, which is not what formset for.
One way is to build a form contains all the fields in the form your want to include, and when processing the form, create each individual form you want to process. The following is an simple illustration. You do something fancy too, by introspecting the models and create model forms automatically, but that's a long story...
class Form1(forms.Form):
a_field = forms.CharField()
class Form2(forms.Form):
b_field = forms.CharField()
class MainForm(forms.Form):
a_field = forms.CharField()
b_field = forms.CharField()
def __init__(self, **kwargs):
super(MainForm, self).__init__(**kwargs)
# This will work because the field name matches that of the small forms, data unknow to
# a form will just be ignored. If you have something more complex, you need to append
# prefix, and converting the field name here.
form1 = Form1(**kwargs)
form2 = Form2(**kwargs)
I have a model with 5 entities and intend to create a form (on the same page) but do not know how to integrate more than one form.
In my main, i can play very well with the forms and write to database, but I need to put more fields on the page.
These fields are of different models.
**
My models:
Teacher, Account(ReferenceProperty), Experience (ReferenceProperty), ServiceDistribution(ReferenceProperty), Experience(ReferenceProperty)
My forms:
class TeacherForm(djangoforms.ModelForm):
class Meta:
model =models.Teacher
exclude = ['user']
and the same for other models
My Main:
class CreateCvHandler(webapp.RequestHandler):
def post(self):
if self.request.get('EscTeacher'):
id = int(self.request.get('EscTeacher'))
teacher=models.teacher.get(db.Key.from_path('Teacher', id))
else:
teacher= models.teacher()
data = forms.TeacherForm(data = self.request.POST)
if data.is_valid():
userList= models.Account.all()
userList.filter('user =', users.get_current_user())
for user in userList:
teacher.user=user.key()
teacher.unity=self.request.get('unity')
teacher.category=self.request.get('category')
teacher.regime=self.request.get('regime')
teacher.put()
self.redirect('/academy')
else:
self.redirect('/createCv')**
Help Please...
If I understood you correctly what you can do is create forms for each model and display them in the template having a single save button. Now when submitted, in your view you can validate each form and add or update the db as required.
Here is a link to an answer to a question similar to what you have asked..
Django: multiple models in one template using forms
Say I have the following simple models for some tagging application (this is simplified from the actual code):
# Model of tag templates
class TagTemplate(models.Model):
name = models.CharField()
content_type = models.ForeignKey(ContentType)
class Tag(models.Model):
template = models.ForeignKey(TagTemplate)
object_id = models.PositiveIntegerField()
* content_object = generic.GenericForeignKey('template__content_type', 'object_id')
# Each tag may display the
class TagTemplateItemDisplay(models.Model):
template = models.ForeignKey(TagTemplate)
content_type_field = models.CharField()
font_size = models.IntegerField()
I have two questions:
1) In the line marked with the *, I understand from the documentation that I need to pass the two field names as per the contenttype framework. In my case the content_type field is specified within the template model. I'd like to avoind a duplicate content_type field within the 'tag' model to get the GenericForeignKey working. Is this possible? Or do I need some custom manager to implement a duplicate content_type within the tag model?
2) I'd like to use the admin site with these models. Is it possible to dynamically create a choice dropdown for the 'content_type_field' field where the contents corresponds to a list of fields from the chosen content_type of the parent model (ie. tagTemplate) when using Tabularinline layout?
eg. in the admin site I pick a model (content_type field) for a new tagTemplate record that contains the fields ('name', 'age', 'dob'), I'd like the TabularInline forms to dynamically update the 'content_type_field' to contain the choices name, age and dob. If i then pick a different model in the parent tagTemplate content_type field, the choices in the child tagTemplateItemDisplay content_type_field of the inline are updated again.
You can subclass the form for that model
class TagTemplateForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TagTemplateForm, self).__init__(*args, **kwargs)
if self.instance.content_type == SomeContentType:
**dynamically create your fields here**
elif self.instance.content_type == SomeOtherContentType:
**dynamically create your other fields here**
Then in your TagAdmin model you need to have:
form = TagTemplateForm
to override the default form created for the admin site.
Not a complete solution but should get you started.
For the dynamic form generation, you might start by reading over this