Questions tagged [modelform]

0

votes
1

answer
16

Views

Django ModelForm widgets and labels

When I have a regular ModelForm field, setting up its widgets and/or labels will look like this: class MyModelForm(models.ModelForm): class Meta: model = MyModel fields = ['field_x', 'field_y'] widgets = { 'field_x': Forms.TextInput(attrs={'class': 'myclass', 'readonly': 'readonly'}), 'field_y': For...
Gonzalo D'ambra
0

votes
0

answer
6

Views

How can I get the data of the modelform?

I am building a user model and wanna attach it to a modelform as below shown. How can I get the email of each user by shell accessing the mysql database? I have tried these to get the data by shell, but the previous one said the object has no email attribute and the latter one said the forms.py has...
WILLIAM
0

votes
0

answer
5

Views

Creating a form wizard / formset to answer questions from a table and saving them into another (Survey)

I am new to Django. I apologize if I don't make much sense. I have an EU project to create a survey tool for adult educators who are assisting migrants and refugees. I would like to use a WizardView/SessionView together with formset to answer a set of 24 questions from a matrix based on Max-Neef's H...
Fatih
1

votes
2

answer
634

Views

Django form save - update boolean field

I have the following model: class Survey(models.Model): is_published = models.BooleanField() which is set to "False" as the default. I am using modelForm to add this into a form. When I call the save() method on the form, I want to change "False" to "True" and save this to the db. How do I do that?...
user1970728
1

votes
1

answer
2.7k

Views

Django throws ValueError

When I type form.is_valid() (being form a modelForm of a model I made) django throws me the following exception: ValueError: Cannot assign None: "Membership.member" does not allow null values. But when I validate again, I get that the form is true. >>> User.objects.get(id=2L) >>> data={'member': 2L,...
Axel
3

votes
1

answer
2.1k

Views

Model formsets and Date fields

I have a model formset on a model with a couple of date fields - which again is a DateTimeField in the model. But when it displays in the template, it is shown as a text field. How can I show it as a drop down box ? WFormSet = inlineformset_factory(UserProfile, W, can_delete=False,exclude=[], extra...
crashekar
2

votes
2

answer
802

Views

Localization of Django application only applies to forms.py and not to models.py

I have a problem when trying to localize my application. It is available in two languages: english and german. The problem appears when the browser has the language set english(United States) and in my settings file is set to 'de' and vice-versa. Some fields appear in english, others in german. My m...
Seitaridis
17

votes
5

answer
19k

Views

Django: Make certain fields in a ModelForm required=False

How do I make certain fields in a ModelForm required=False? If I have: class ThatForm(ModelForm): class Meta: widgets = {"text": Textarea(required=False)} Or if I have: class ThatForm(ModelForm): text = Textarea(required=False) Django returns: __init__() got an unexpected keyword argument 'required'
Synthead
18

votes
2

answer
15.8k

Views

Django ModelForm Imagefield Upload

I am pretty new to Django and I met a problem in handling image upload using ModelForm. My model is as following: class Project(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=2000) startDate = models.DateField(auto_now_add=True) photo = models.ImageF...
Wei Xu
2

votes
1

answer
1.4k

Views

Django duplicate key value violates unique constraint error model form

I have a legacy DB on PostgreSQL with a simple products table with 2 columns (productid, productname) with 70 products. I am trying to start using Django as a frontend and I have the model as below and a model form. The save process is failing with the error below. duplicate key value violates uniq...
Avagut
6

votes
2

answer
3.5k

Views

Django ModelForm is_valid saves the instance automatically

I found the ModelForm in Django is very easy to use and it saves great time of development. However, I was stuck when I realize the is_valid actually saves the ModelForm! I would like to know if this is expected behavior, or am I doing something wrong? What happens to me is form=SOME_MODEL_FORM(......
zhaocong
5

votes
1

answer
2.8k

Views

Getting a foreign key into a form

I'm new to Django and Python, and have spent a couple days trying to solve this problem. I've tried several approaches in other threads here, but I think I'm missing some basic concept because none of them have worked for me. Here's what I'm trying to do: I'm using ModelForm, and I have created a fo...
Jonathan Rickard
20

votes
4

answer
23.8k

Views

Django ModelForm has no model class specified

I am trying to use ModelForm: from django.db import models from django.forms import ModelForm class Car(models.Model): carnumber = models.CharField(max_length=5) def __unicode__(self): return self.carnumber class PickForm(ModelForm): class Meta: Model = Car` I have checked this and I cannot find my...
dpbklyn
2

votes
1

answer
759

Views

Created a modelform in django, primary key is missing

I created a modelform in django, but the primary key field is missing in the browser. Where is it? How can I get it to appear. Let me know if you need more code than what I have below. view.py import autocomplete_light import datetime from django.shortcuts import render, render_to_response, RequestC...
user1807271
2

votes
2

answer
465

Views

Django : ModelForm Pre-populate Checkbox with Custom Query

I am working on my first Django Project. I have a Many-to-Many Relation between two models: User and Project. While Updating a Project, I want to show form with Add New members and remove Existing members field with correct Choices based on current Project Users. Here is what I tried so far: Get...
Kush Jain
5

votes
1

answer
5.2k

Views

Uploading Profile Image using Django ModelForm

I've looked around at related questions, but none of the answers seem to work. I'm trying to upload a profile image for a user and have it replace (overwrite) the current image. Upon saving the image I want to change the filename to the user id. In it's current form the image will upload, but it won...
dvw
11

votes
2

answer
21.2k

Views

field choices() as queryset?

I need to make a form, which have 1 select and 1 text input. Select must be taken from database. model looks like this: class Province(models.Model): name = models.CharField(max_length=30) slug = models.SlugField(max_length=30) def __unicode__(self): return self.name It's rows to this are added only...
robos85
2

votes
1

answer
3.7k

Views

“Select a valid choice. <choice> is not one of the available choices” error when submitting ManyToMany ModelForm

I want to limit the choices of a ManyToManyField to those matching a ForeignKey. The form displays properly, but upon saving results in an error "Select a valid choice. is not one of the available choices". Before I was trying to limit the queryset by passing a parameter in the view to the form, an...
wasabigeek
5

votes
2

answer
14.3k

Views

Hide a field from a django modelform

The django documentation suggests I can identify hidden / visible fields from within my template. I have two models, AddressInfo and PharmacyInfo. I need to enter data for both tables from a single page. I want to hide the address_id field (from the PharmacyInfo model). I currently have: {% for form...
Aidan Ewen
11

votes
4

answer
3.6k

Views

Django, adding excluded properties to the submitted modelform

I've a modelform and I excluded two fields, the create_date and the created_by fields. Now I get the "Not Null" error when using the save() method because the created_by is empty. I've tried to add the user id to the form before the save() method like this: form.cleaned_data['created_by'] = 1 and fo...
Sven van Zoelen
11

votes
4

answer
7.1k

Views

How do I update an already existing row when using ModelForms?

I have a question on how to update an existing row in my database when one of the fields is my primary key. I am using ModelForm and Django-Piston - my main goal here is to have RESTful Post send to my webservice. I am able to have initial Posts be sent correctly (i.e. that Primary key value doesn't...
letsgofast
2

votes
3

answer
106

Views

Is the word start a usable field name in a Django model?

I have a model called Order with a datetime field called start. I can read and write from/to that field no problem. However, I just created a ModelForm and specified start as one of the fields=() in Meta and I get: Unknown field(s) (start) specified for Order I've made sure it is not a typo by copyi...
mhost
5

votes
2

answer
3.3k

Views

How add a 'Star *' after a django ModelForm CharField?

i have some necessary fields in my django ModelForm. How can i add a red star (*) after the required fields ?
Kozet
2

votes
1

answer
407

Views

Saving data from ModelForm

I am new to Django and I'm trying to save data using ModelForm. Template 'Vlozit' has a ModelForm and when submitted, I want the data saved in the DB and the redirect to base.html that actually loads the data from the DB and lists the output. The problem is that all works fine but the data is not sa...
Martin
3

votes
1

answer
1.6k

Views

confused about self.instance in save() of child of ModelForm()

The save() documentation explains that: A subclass of ModelForm can accept an existing model instance as the keyword argument instance; if this is supplied, save() will update that instance. If it's not supplied, save() will create a new instance of the specified model However, self.instance in save...
Gezim
2

votes
1

answer
136

Views

Django Forms: possible to update only some parameters?

Lets say I have a very simple Model, class Entity(models.Model): foo = models.TextField(blank=True, default='') bar = models.TextField(blank=True, default='') a ModelForm class EntityForm(forms.ModelForm): class Meta: model = models.Entity and I am executing the following code: #preparation entity =...
kev
3

votes
3

answer
219

Views

Enforcing values for some fields when using ModelForm

I have a Django app where users submit orders for payment. Clearly, security is important. I want to minimise the amount of code that I have to write, to avoid introducing any security holes, and ease maintenance. The model is simple: class Order(models.Model): user = models.ForeignKey(User) created...
qris
6

votes
1

answer
4k

Views

Django model form using forms.ModelMultipleChoiceField

I have a ModelForm in my Django app that uses a forms.ModelMultipleChoiceField, which displays as a forms.CheckboxSelectMultiple widget on the form. This ModelForm is used to select/de-select values for a many-to-many relation. Here's the problem: when you uncheck all of the checkboxes and save the...
Rob
2

votes
3

answer
53

Views

ModelForm right approach for editing database record?

Can someone help me with fixing Django ModelForm? This particular code can add new item to database as expected, but when I'm trying to edit db record - It just add new record, instead of updating old. I'm quite new in Django framework. views.py: def manage(request, item_id = None): t = get_object_...
DzLL
2

votes
0

answer
448

Views

Django ModelMultipleChoiceField: passing attributes unique to each choice

I have a ModelMultipleChoiceField on a form that I'd like to pass an attribute to each item in the QuerySet. I need this attribute to be determined dynamically. So for example if Item objects with the names `item1' and 'item2': Item.object.create(name='item1') Item.object.create(name='item2') items...
Steve
2

votes
0

answer
321

Views

django-autocomplete-light modelform ValidationError

I have an autocomplete fields in 2 diferent forms. One is with forms.Form and works ok. Other one is with ModelForm and this doesn't work If I try with: class FacturaForm(ModelForm): class Meta: widgets = autocomplete_light.get_widgets_dict(Factura) model = Factura throws: ValidationError at /factur...
Omarbeat
13

votes
1

answer
14k

Views

modelform: override clean method

I have two questions concerning the clean method on a modelform. Here is my example: class AddProfileForm(ModelForm): ... password = forms.CharField(max_length=30,widget=forms.PasswordInput(attrs={'class':'form2'})) password_verify = forms.CharField(max_length=30,widget=forms.PasswordInput(attrs={'c...
rom
2

votes
4

answer
672

Views

Dynamically update ModelForm’s Meta class model field

def SiteAdminForm(model_cls, *args, **kwargs): class MerchantAdminForm(forms.ModelForm): class Meta: exclude = ('external_links', 'published', 'logo','image_zip_file',) model = model_cls def __init__(self, *args, **kwargs): super(MerchantAdminForm, self).__init__(*args, **kwargs) return MerchantAdmi...
Mike
2

votes
2

answer
2k

Views

How can I exclude a declared field in ModelForm in form's subclass?

In Django, I am trying to derive (subclass) a new form from ModelForm form where I would like to remove some fields (or to have only some fields, to be more correct). Of course obvious way would be to do (base form is from django.contrib.auth.forms): class MyUserChangeForm(UserChangeForm): class Met...
Mitar
23

votes
3

answer
26.8k

Views

Django ModelForm instance with custom queryset for a specific field

I have a model not unlike the following: class Bike(models.Model): made_at = models.ForeignKey(Factory) added_on = models.DateField(auto_add_now=True) All users may work at a number of factories and therefore their user profiles all have a ManyToManyField to Factory. Now I want to construct a ModelF...
Deniz Dogan
2

votes
2

answer
799

Views

Saving to ManyToManyFields using ModelForm and ModelMultipleChoiceField

I've created a basic Django app that contains books/authors/publishers as per the Django Book - trying to use a ModelForm to create a means to modify existing books - the problem is that the 'authors' field is a ManyToManyField and when I choose a choice on the ModelForm it simply wipes the existing...
jonseager
3

votes
2

answer
2k

Views

How to save Django ModelFormSet?

I'm quite desperate now and I cannot figure this out. To me it should be easy to do, but I have not come across any answers that explains this. Two models with no foreign keys between them: class Employee(models.Model): surname = models.CharField(max_length=100) name = models.CharField(max_length=1...
wernerfeuer
2

votes
1

answer
1.8k

Views

Django: Save Modelform with Foreignkey using to_field and ModelChoiceForm

I have a problem saving a ModelForm when using a foreign key that doesn't "point" to the primary key of it's related table (legacy schema woes) I am using to_field= for my Foregin Key so that it will be related to a key that is not exactly a key. My ModelForm foreignkey uses a ModelChoiceField with...
geraldcor
12

votes
5

answer
23.4k

Views

Django: how to hide/overwrite default label with ModelForm?

i have the following, but why does this not hide the label for book comment? I get the error 'textfield' is not defined: from django.db import models from django.forms import ModelForm, Textarea class Booklog(models.Model): Author = models.ForeignKey(Author) Book_comment = models.TextField() Bookcom...
thedeepfield
23

votes
4

answer
10.6k

Views

Dynamically update ModelForm's Meta class

I am hoping to dynamically update a ModelForm's inline Meta class from my view. Although this code seems to update the exclude list in the Meta class, the output from as_p(), as_ul(), etc does not reflect the updated Meta exclude. I assume then that the html is generated when the ModelForm is create...
ashchristopher

View additional questions