forms.py
Date_Format = (
('0', ' dd / mm / yyyy'),
('1', 'mm / dd / yyyy'),
)
Time_Format = (
('0', ' 12 hour AM / PM '),
('1', ' 24 hour '),
)
class SettingsForm(forms.ModelForm):
date_format = forms.ChoiceField(widget=forms.RadioSelect(), choices=Date_Format)
time_format = forms.ChoiceField(widget=forms.RadioSelect(), choices=Time_Format)
class Meta:
model = Settings
fields = ['date_format','time_format']
views.py
def date_format(request):
# settingsForm = SettingsForm({'user':request.user})
settings = Settings.objects.get(user=2)
settingsForm = SettingsForm(instance=settings)
# dateformatForm = DateFormatForm()
# timeformatForm = TimeFormatForm()
settingsForm = SettingsForm()
if request.method =='POST':
# dateformatForm = DateFormatForm(request.POST)
# timeformatForm = TimeFormatForm(request.POST)
settingsForm = SettingsForm(request.POST,instance=settings)
if (settingsForm.is_valid()):
settings=settingsForm.save()
# timeformatForm.save()
return redirect('/member/follow-up/')
return render_to_response( 'incident/date_format.html',
{
'about_menu': True,
'SettingsForm':settingsForm,
},
context_instance=RequestContext(request))
models.py
class Settings(models.Model):
user = models.ForeignKey(User, null=True)
date_format = models.CharField('Date format', max_length=100)
time_format = models.CharField('Time format', max_length=100)
template is
<form action="/member/date-format/" method="POST"> {% csrf_token %}
{{ SettingsForm.date_format }}
{{ SettingsForm.time_format }}
</form>
I am using models form here to store the form value in database.
If i select the radio button choice.the corresponding values are saving in database.But the checked radio button will uncheck if the page is reloaded.I don't know what logic to use to do this.
Moreover,is any way to save the values of radio button in template without using modelsForm.
Thanks
In your view:
def date_format(request):
# settingsForm = SettingsForm({'user':request.user})
settings = Settings.objects.get(user=2)
settingsForm = SettingsForm(instance=settings)
# dateformatForm = DateFormatForm()
# timeformatForm = TimeFormatForm()
settingsForm = SettingsForm()
....
You are resetting the settingsForm with empty form, which will show the form without any values from instance settings. You may want to remove that line.
Related
Please help me to solve this problem! I have form for job application and I have this in my
models.py:
class Vacancy(models.Model):
vacancy_title = models.CharField(max_length=100)
vacancy_description = models.TextField()
data = models.DateTimeField(default=timezone.now)
contact_person = models.CharField(max_length=50)
phone_number = models.CharField(max_length=30)
mail = models.EmailField();
def __str__(self):
return self.vacancy_title
A user must choose one of the vacancies
<select name="job_field" id="job_field">
{% for vacancy in vacancies %}
<option value="">{{ vacancy.vacancy_title }}</option>
{% endfor %}
</select>
Here is the forms.py:
from django import forms
from .models import Vacancy
CHOICES = (Vacancy.objects.all().values_list('vacancy_title', flat=True))
class ApplicantForm(forms.Form):
name = forms.CharField(max_length=50)
surname = forms.CharField(max_length=50)
email = forms.EmailField()
selected_position = forms.ChoiceField(choices=CHOICES)
And the views.py:
def send_resume(request):
vacancies = Vacancy.objects.all();
if request.method == 'POST':
form = ApplicantForm(request.POST)
if form.is_valid():
name = form.cleaned_data['applicant_name']
surname = form.cleaned_data['applicant_surname']
passport_number = form.cleaned_data['passport_number']
from_mail = form.cleaned_data['mail']
position = form.cleaned_data['position']
else:
form = ApplicantForm()
context = {'vacancies': vacancies}
return render(request, 'interactive/send_resume.html', context)
Now in the forms.py I cannot connect vacancy_title to the choice of the select group(Choice Field). How to do it?
You can just use ModelChoiceField.
selected_position = forms.ModelChoiceField(queryset=Vacancy.objects.all(), empty_label='(Nothing)')
It's more generic way
Use django-model-utils module. Your model code can look as below.
from model_utils import Choices
VACANCY_CHOICE = Choices(
('MANAGER', 'MANAGER', _('Development Manager')),
('SALES', 'SALES', _('Sales VP')),
)
class Vacancy(models.Model):
vacancy_title = models.CharField(choices=VACANCY_CHOICE, default=VACANCY_CHOICE.MANAGER,max_length=100)
Try to use {{form}} in your template.
I'm building the 'edit' page of my form. This page is supposed to show form with the data that was saved, so the form is pre populated with saved data.
It works fine for most if the fields, but I have a problem with MultipleChoiceField / CheckboxSelectMultiple values that don't get restored. So instead of having the corresponding checkboxes checked with data from the saved form, they are all unchecked. Why is that ?
forms.py
class MemberForm( forms.ModelForm ):
# ......
MODEL_CATEGORIES = (
('advisor', 'advisor'),
('member', 'member'),
('admin', 'admin'),
)
model_categories = forms.MultipleChoiceField(
widget = forms.CheckboxSelectMultiple,
choices = MODEL_CATEGORIES
)
class Meta:
model = Member
fields = [ 'model_categories' ]
model
class Member( models.Model ):
model_categories = models.CharField(
max_length = 255,
null = True,
blank = True )
Controller
def profile_edit_form( request ):
user = request.user or None
# Get user member profile instance
instance = get_object_or_404( Member, author = user )
form = MemberForm( request.POST or None, instance = instance )
context = {
"form" : form,
"instance": instance
}
if form.is_valid():
# ...
return redirect( 'profile_display' )
else:
# Initial form display, and redisplay of invalid form
return render( request, 'profile_edit_form_view.html', context )
Template
<form action="/accounts/profile-edit-form/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit"/>
</form>
You can try using initial in the form
form = MemberForm( request.POST or None, instance = instance,
initial={'model_categories': 'advisor'})
It looks as a 'feature' of Django, and won't get fixed:
https://code.djangoproject.com/ticket/28531
Solution is simple if you are using Postgres db, in your model, use an ARRAY field instead of a simple charfield:
model_categories = ArrayField( models.CharField( max_length = 200 ), blank = True, null = True )
Multi select values are properly stored and restored from this type of model field, without the need of any data processing.
I am trying to render my django forms in the template using bootstrap and I keep getting an error:
BoundField' object has no attribute 'fields'
This is what I try:
{% for field in layer_form %}
{{ field | as_bootstrap }}
{% endfor %}
If I try this:
{{ layer_form|as_bootstrap }}
then it works. But I need to loop through the form fields and append some if statements in between.
Any idea what's going on here?
The above works with another form but not with this one:
lass ResourceBaseForm(TranslationModelForm):
"""Base form for metadata, should be inherited by childres classes of ResourceBase"""
owner = forms.ModelChoiceField(
empty_label="Owner",
label="Owner",
required=False,
queryset=Profile.objects.exclude(
username='AnonymousUser'),
widget=autocomplete_light.ChoiceWidget('ProfileAutocomplete'))
_date_widget_options = {
"icon_attrs": {"class": "fa fa-calendar"},
"attrs": {"class": "form-control input-sm"},
"format": "%Y-%m-%d %H:%M",
# Options for the datetimepickers are not set here on purpose.
# They are set in the metadata_form_js.html template because
# bootstrap-datetimepicker uses jquery for its initialization
# and we need to ensure it is available before trying to
# instantiate a new datetimepicker. This could probably be improved.
"options": False,
}
date = forms.DateTimeField(
localize=True,
widget=DateTimePicker(**_date_widget_options)
)
temporal_extent_start = forms.DateTimeField(
required=False,
localize=True,
widget=DateTimePicker(**_date_widget_options)
)
temporal_extent_end = forms.DateTimeField(
required=False,
localize=True,
widget=DateTimePicker(**_date_widget_options)
)
poc = forms.ModelChoiceField(
empty_label="Person (fill form)",
label="Point Of Contact",
required=False,
queryset=Profile.objects.exclude(
username='AnonymousUser'),
widget=autocomplete_light.ChoiceWidget('ProfileAutocomplete'))
metadata_author = forms.ModelChoiceField(
empty_label="Person (fill form)",
label="Metadata Author",
required=False,
queryset=Profile.objects.exclude(
username='AnonymousUser'),
widget=autocomplete_light.ChoiceWidget('ProfileAutocomplete'))
keywords = TaggitField(
required=False,
help_text=_("A space or comma-separated list of keywords"),
widget=TaggitWidget('TagAutocomplete'))
regions = TreeNodeMultipleChoiceField(
required=False,
queryset=Region.objects.all(),
level_indicator=u'___')
regions.widget.attrs = {"size": 20}
With this simple form it works:
class UploadCSVForm(forms.Form):
def __init__(self, *args, **kwargs):
super(UploadCSVForm, self).__init__(*args, **kwargs)
self.fields['selected_country'] = forms.MultipleChoiceField(choices=get_country_names(), required=True)
title = forms.CharField(max_length=80, required=True)
LAYER_TYPE = (
('1', 'Global Layer'),
('2', 'Layer by Region'),
('3', 'Layer by Province'),
)
layer_type = forms.ChoiceField(choices=LAYER_TYPE, required=True)
csv = forms.FileField(required=True)
permissions_json = forms.CharField(max_length=500, widget=forms.HiddenInput())
views.py
def when(request):
user = request.user
report = Report.objects.get(user=request.user)
reportform = ReportForm(instance=report)
settings = Settings.objects.get(user=request.user)
settingsForm = SettingsForm(instance=settings)
settings=Settings.objects.get(user=2)
if settings.date_format == '0':
date=datetime.datetime.strptime('10/31/2012','%m/%d/%Y').strftime('%d/%m/%Y')
else:
date=datetime.datetime.strptime('31/10/2012','%d/%m/%Y').strftime('%m/%d/%Y')
if request.method == 'POST':
reportform = ReportForm(instance=report,data=request.POST)
if reportform.is_valid():
report = reportform.save(commit=False)
report.user = request.user
report.save()
return redirect('/member/media/')
return render_to_response('incident/when.html',{
'newreport_menu': True,
'form': reportform,
'date':date,
},
context_instance=RequestContext(request))
models.py
class Report(models.Model):
user = models.ForeignKey(User, null=False)
manual_date = models.DateField('Another date', null=True, blank=True)
template.html
{{ form.manual_date }}{{ form.manual_date.errors }}{{ date }}
The above views rendering the hardcoded date values in template as variable.Instead of hardcode is it possible to show the date from manual_date field in models.And how to pass it in reportform.
I think you want this, instead of using hardcoded date use report.manual_date:
if settings.date_format == '0':
date = report.manual_date.strftime('%d/%m/%Y')
else:
date = report.manual_date.strftime('%m/%d/%Y')
I am trying to validate a User Profiling form in django and I can't. It seems that there is something wrong with forms.dateField(). It does not validate (ie. is_valid() return false)
this is my forms dateField entry:
date_of_birth = forms.DateField(label=u'date of birth', input_formats='%d/%m/%Y', required=False, widget=forms.DateInput(format = '%d/%m/%Y'))
I noticed that request.POST.get('date_of_birth', '') returns the correct date (ie. the date I have typed in the html form field).
I also noticed that in this function:
def clean_date_of_birth(self):
date = self.cleaned_data['date_of_birth']
date object is always None.
What am I doing wrong?
EDIT:
This is what I am trying to enter:
29/07/1974 (July 29th, 1974)
This is the output of 'submit' (various requests)
29/07/1974
profile form is *NOT* valid
[23/Feb/2012 12:16:27] "POST /profile/chris/ HTTP/1.1" 200 16289
29/7/1974
profile form is *NOT* valid
[23/Feb/2012 12:16:33] "POST /profile/chris/ HTTP/1.1" 200 16289
1974-07-29
profile form is *NOT* valid
[23/Feb/2012 12:18:15] "POST /profile/chris/ HTTP/1.1" 200 16289
This is my template
<div class="input_area">
<form id="profile_form" method="post" action="/profile/{{ user.username }}/">{% csrf_token %}
{{ form.as_p }}
<input type="submit" id="submit" value="save" class="submitButton idle" style="width:70px" />
</form>
</div>
this is my views.py
def profile(request, username):
form = ProfileForm(request.POST)
print request.POST.get('date_of_birth', 'None')
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
raise Http404(u'User not Found')
if form.is_valid():
print 'profile form is valid'
else:
print 'profile form is *NOT* valid'
and finally this is my forms.py (do not use clean_data functions at the moment)
class ProfileForm(forms.Form):
tz = []
timezones = Timezone.objects.all()
for timezone in timezones:
val = str(timezone.hour)
v = val.split(':')
tuple = (timezone.id, '('+timezone.sign+''+v[0]+':'+v[1]+') '+timezone.name)
tz.append(tuple)
sex = [('male','male'),('female', 'female'),('unknown', 'prefer not to say')]
real_name = forms.CharField(label=u'real name', widget=forms.TextInput, required=False)
date_of_birth = forms.DateField(label=u'date of birth', input_formats='%d/%m/%Y', required=False, widget=forms.DateInput(format = '%d/%m/%Y'))
pp_email = forms.EmailField(label=u'Paypal Email', widget=forms.TextInput, required=False)
gender = forms.ChoiceField(label=u'sex', choices=sex, widget=forms.Select(), required=False)
timezone = forms.ChoiceField(label=u'time zone', choices=tz, widget=forms.Select())
address = forms.CharField(label=u'street address', widget=forms.Textarea, required=False)
postal = forms.CharField(label=u'postal code', widget=forms.TextInput, required=False)
input formats in DateField must be list or tuple https://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.DateField.input_formats
With Django 1.6 and up you can use the localized_fields in your form's Meta or localize=True in your form. See https://docs.djangoproject.com/en/1.9/topics/i18n/formatting/#format-localization.
When using USE_L10N = True, Django will use the formats.py file for your locale (part of LANGUAGE_CODE).
You can end up with something DRY like this (as the fields specified in models.py do not need to be repeated in forms.py):
class SomeForm(forms.Form):
class Meta:
model = SomeModel
fields = ('first_name', 'dob',)
localized_fields = ('dob',)