I want to pass a dropdown variable from the template to a function when i click submit button
#models.py :-
class donnee(models.Model):
name = models.CharField(_('name'), max_length= 150)
def __unicode__(self):
return self.name
class Meta:
verbose_name = _('donnee')
verbose_name_plural = _('donnees filtrage')
ordering = ['name']
class Property(models.Model):
name = models.CharField(_('name'), max_length=50)
description = models.TextField(_('description'), blank=True)
def __unicode__(self):
return self.name
class Meta:
verbose_name = _('property')
verbose_name_plural = _('properties')
ordering = ['name']
class Physic2(models.Model):
name = models.ForeignKey(Property, verbose_name=_('name'), null=True, blank=True)
lapropriete = models.ForeignKey(donnee, verbose_name=_('lapropriete'), blank=True)
#lapropriete = models.CharField(_('property'), max_length=100)
description = models.TextField(_('description'), blank=True)
def __unicode__(self):
return self.lapropriete
class Meta:
verbose_name = _('physic2')
verbose_name_plural = _('physics2')
ordering = ['name']
#forms.py:-
class Physic2Form(forms.ModelForm):
class Meta:
model = Physic2
#views.py:-
def get_materials_one(request, category_slug=None):
if category_slug is None:
lafamille= 'general'
propriete= Physic2Form()
return render_to_response('material/critere1.html',
{'unefamille': lafamille,
'propriete': propriete},
context_instance=RequestContext(request))
#template:-
<form id= "testjson" action="{% url chercher_filtre1 %}" method= "get" onsubmit = "">
{{ propriete.lapropriete }}
<td><input type="submit" style="background-color:#D7D8D4;" value="Search" id= "chercher"/></td>
</div>
</form>
#function:-
valT1 = request.GET['lapropriete']
this don't work
when i click on a field in the dropdown list
valT1 = 1 or 2... it's just the id of the field
i have the fields
Vickers hardness (GPa)
Shear Modulus (GPa)
Young Modulus (GPa)
what to put for request.GET[ ??]
You can write like this and try.
if request.method == 'GET':
form = Physic2Form(request, data=request.GET)
if form.is_valid():
data = form.cleaned_data
valT1 = data['lapropriete']
my function
def search_filter1(request):
try:
val_min1 = float(request.GET['Vmin1'])
val_max1 = float(request.GET['Vmax1'])
T_min1 = float(request.GET['Tmin1'])
T_max1 = float(request.GET['Tmax1'])
if request.method == 'GET':
form = Physic2Form(request.GET)
if form.is_valid():
valT1 = form['lapropriete']
print 'val_min1:',val_min1
print 'val_max1:',val_max1
print 'Tmin1:', T_min1
print 'Tmax1:', T_max1
print 'valT1:',valT1
If i select the property 'Shear Modulus (GPa)' when i click on submit button,
i get this :
val_min1: 44.0
val_max1: 99.0
Tmin1: 44.0
Tmax1: 99.0
valT1: <select name="lapropriete" id="id_lapropriete">
<option value="">---------</option>
<option value="2">Elasticity Modulus (GPa)</option>
<option value="4" selected="selected">Shear Modulus (GPa)</option>
<option value="1">Vickers Hardness (GPa)</option>
<option value="3">Young Modulus (GPa)</option>
</select>
why that ?
Related
class Album(TimeStampedModel):
name = models.CharField(default='New Album' , max_length = 80)
release_datetime = models.DateTimeField(blank = False)
cost = models.DecimalField(blank = False, decimal_places = 2,max_digits = 15)
artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
is_approved = models.BooleanField(default=False)
def __str__(self):
return (f"id: {self.id} \n name: {self.name} cost: {self.cost} \n approved : {self.is_approved}")
class Song(models.Model):
album = models.ForeignKey(Album, on_delete=models.CASCADE)
name = models.CharField(blank = True , max_length = 80)
image = models.ImageField(blank = False)
thumbnail = ImageSpecField(format='JPEG')
I want to make Song.name = album.name if supplied name from form is = "" (empty)
how can I do this
thanks in advance
class Song(models.Model):
# album = models.ForeignKey(Album, on_delete=models.CASCADE)
name = models.CharField(blank?album.name)
# image = models.ImageField(blank = False)
# thumbnail = ImageSpecField(format='JPEG')
something like that
Made a form based on the model. In which it is checked if the name field is empty, then it is filled with the name from the album. I deliberately left a printout so that you can see what kind of data is inside. You can read more about validation here.
Replace bboard with the name of the folder where your templates are placed (view row: template_name = 'bboard/tam_form.html').
In the view, I leave get_context_data, if you want to add something to the context (if you remove the function, then everything will work).
forms.py
from .models import Song
class MySong(ModelForm):
class Meta:
model = Song
fields = ('album', 'name', 'image')
def clean(self):
cleaned_data = super().clean()
field_name = cleaned_data.get('name')
if len(field_name) <= 0 or field_name == '':
aaa = cleaned_data['album'].name
cleaned_data['name'] = aaa
print('cleaned_data', cleaned_data)
views.py
class MyFormSong(CreateView):
template_name = 'bboard/tam_form.html'
form_class = MySong
success_url = reverse_lazy('song')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
tam_form.html
<h2>form</h2>
<form method="post" action="{% url 'song' %}">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="adding">
</form>
urls.py
urlpatterns = [
path('song/', MyFormSong.as_view(), name='song'),
]
I have a "project" model that has a "status" field. The status can be active, paused, or complete. I want to be able to update the field via form on the project detail view.
I have read a few solutions to this problem but, as a newbie, I haven't been able to get this to work. When I submit the form I get an http 405 error and the instance is not updated.
the model:
class Project(models.Model):
title = models.CharField(max_length= 200)
description = tinymce_models.HTMLField()
status = models.CharField(max_length=20, choices=PROJECT_CHOICES, default="active")
date = models.DateTimeField(auto_now_add=True, null=True)
created_by = models.ForeignKey(CustomUser, editable=False, null=True, blank=True, on_delete=models.RESTRICT)
objects = ProjectManager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('company_project:project_detail', args=[str(self.id)])
the view
class CompanyProjectsDetailView(DetailBreadcrumbMixin, FormMixin, DetailView):
model = Project
id = Project.objects.only('id')
template_name = 'company_accounts/project_detail.html'
context_object_name = 'project'
form_class = ProjectStatusForm
notescount = Project.objects.annotate(num_notes=Count('notes'))
documentscount = Project.objects.annotate(num_documents=Count('project_documents'))
todoscount = Project.objects.annotate(num_documents=Count('todo_group'))
def form_valid(self, form):
project = get_object_or_404(Project, id=self.kwargs.get('pk'))
theform = form.save(commit=False)
theform.project = project
form.save()
return super(CompanyProjectsDetailView, self).form_valid(form)
the form
class ProjectStatusForm(forms.ModelForm):
class Meta:
model = Project
fields = ['status']
labels = {'status': 'project status'}
widgets = {
'status': forms.Select(attrs={'id':'PROJECT_CHOICES'}),
}
On the page I use this code to add the form
<form action="" method="post">
{% csrf_token %}
{{ form.media }}
{{ form|crispy }}
</br>
<input type="submit" value="save">
</form>
I have a simple form to add a website to database. This is my site model:
class Site(models.Model):
category = models.ForeignKey('Category')
category1 = models.ForeignKey('Category', related_name='+',)
subcategory = ChainedForeignKey(
'Subcategory',
chained_field='category',
chained_model_field='category',
show_all=False,
auto_choose=True)
name = models.CharField(max_length=70)
description = models.TextField()
# importuje zmienione TextFields widgets.py
keywords = MyTextField()
date = models.DateTimeField(default=datetime.now, editable=False)
url = models.URLField()
is_active = models.BooleanField(default=False)
group = models.CharField(max_length=2, choices=(('Basic',
'Basic'), ('Premium', 'Premium')))
subcategory1 = ChainedForeignKey(
'Subcategory',
chained_field='category1',
chained_model_field='category1',
related_name='subcategory1',
show_all=False,
auto_choose=True)
def get_absolute_url(self):
return "%s/%i" % (self.subcategory.slug, self.id)
class Meta:
verbose_name_plural = "Sites"
def __str__(self):
return self.name
Forms.py
class SiteAddFormFull(forms.ModelForm):
url = forms.URLField(widget=forms.TextInput(attrs={'readonly': 'readonly'}))
class Meta:
model = Site
fields = ('url', 'name', 'description', 'keywords', 'group', 'category1','subcategory1')
I would like to change my form by adding fields 'Category1', 'Subcategory1' after user choose value in group field ('Premium'). Form should reload itself and show those fields. Before choosing 'Premium' fields 'Category1', 'Subcategory1' should be invisible. How can I achieve that?
In my forms.py I added:
widgets = {'category1': forms.HiddenInput(), 'subcategory1':
forms.HiddenInput()}
In my .js file I try to show those fields but it doesn't work:
$(":hidden").show();
// $("#id_category1".show() and other posibilities
In my page soure I have
<input id="id_category1" name="category1" type="hidden" /><input id="id_subcategory1" name="subcategory1" type="hidden" />
Why it doesn't work?
You don't need HiddenInput for categories. Just hide it with jquery and show it on select change event.
<select id="group">
<option value="First">First</option>
<option value="Premium">Premium</option>
<option value="Second">second</option>
</select>
<select id="category1">
<option value="First">First</option>
<option value="Second">second</option>
</select>
Jquery
$(document).ready(function(){
$('#category1').hide();
$('#group').change(function(e) {
var group = $(this).val();
if (group == 'Premium'){
$('#category1').show();
} else {
$('#category1').hide();
}
});
});
https://jsfiddle.net/fwfm9byy/1/
I have validation errors in my django formset. Two drop down lists, populated from the database, do not pass the validation, and I don't understand what's my mistake.
model:
class Country(models.Model):
country_code=models.CharField(max_length=2, primary_key=True)
country=models.CharField(max_length=20, unique=True)
def __unicode__(self):
return u"%s" % self.country
class Status(models.Model):
verbatim = models.ForeignKey(Verbatim)
country = models.ForeignKey(Country)
status = models.CharField(max_length=5, db_index=True)
def __unicode__(self):
return u"%s" % self.status
class Meta:
unique_together=(("verbatim", "country"), )
class ImportMinAttend(models.Model):
country=models.CharField(max_length=2, blank=False, null=False)
verbatim=models.CharField(max_length=250, blank=False, null=False)
status=models.CharField(max_length=5, blank=True, null=True, default=None)
form:
class MinAttendForm(forms.ModelForm):
country=forms.ModelChoiceField(queryset=Country.objects.all(), empty_label="Select a country")
status=forms.ModelChoiceField(queryset=Status.objects.values_list('status', flat = True).distinct(), empty_label="Select a status")
class Meta:
model=ImportMinAttend
#fields used for the validation
fields = ('country', 'verbatim', 'status')
view:
class MinAttendUpdate(UpdateView):
model = ImportMinAttend
fields = ['country', 'verbatim', 'status']
form_class=MinAttendForm
def post(self, request, *args, **kwargs):
...
MinAttendFormSet = modelformset_factory(self.model, form=self.form_class, fields=self.fields, extra=len(attendances), max_num=len(attendances)+self.nb_extra_forms)
formset=MinAttendFormSet(request.POST, queryset=attendances)
...
Source code of the first country select:
<select name="form-0-country" id="id_form-0-country">
<option value="">Select a country</option>
<option value="AT" selected="selected">Austria</option>
<option value="BE">Belgium</option>
<option value="BG">Bulgaria</option>
...
Source code of the first status select:
<select name="form-0-status" id="id_form-0-status">
<option value="">Select a status</option>
<option value="AB">AB</option>
<option value="CS">CS</option>
<option value="M" selected="selected">M</option>
</select>
About the country select: the value displayed has more than two characters but the key used has exactly 2 characters. Why this validation error?
About the status, I don't even understand the problem...
Many thanks.
EDIT: SOLVED:
I have found "dirty" workarounds.
For the country select, I use the key of the select, not the value:
def clean_country(self):
data = self.cleaned_data['country'].pk
return data
For the status select, I delete the validation error if a value is selected:
def clean(self):
#call status clean method
self.cleaned_data["status"]=self.clean_status()
return self.cleaned_data
def clean_status(self):
#valid if a value has been selected
if self["status"].value()!="":
del self._errors["status"]
return self["status"].value()
It works, but why do I have to do this? :(
I think you are doing it the hard way. There is a lot easier way to do it, taking advantage of ModelForm. Here is a full example. Read it and adapt it to your models:
from django.db import models
from django.forms import ModelForm
TITLE_CHOICES = (
('MR', 'Mr.'),
('MRS', 'Mrs.'),
('MS', 'Ms.'),
)
class Author(models.Model):
name = models.CharField(max_length=100)
title = models.CharField(max_length=3, choices=TITLE_CHOICES)
birth_date = models.DateField(blank=True, null=True)
def __str__(self): # __unicode__ on Python 2
return self.name
class Book(models.Model):
name = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
class AuthorForm(ModelForm):
class Meta:
model = Author
fields = ['name', 'title', 'birth_date']
class BookForm(ModelForm):
class Meta:
model = Book
fields = ['name', 'authors']
I'm using inlineformset_factory to create a formset. The parent object is a featured set and the child objects are featured items. I'm using the 'django-dynamic-formset' jQuery plugin on the front end to add/remove formset forms dynamically.
While each form in the formset is getting submitted with the proper data as expected, cleaned_data only contains the form's id.
View:
#login_required
#csrf_protect
def edit_featured_set(request, fset_id):
'''
Edit a featured set and its items
'''
c = {}
c.update(csrf(request))
# get existing featured set for this id (if exists)
if fset_id and int(fset_id) > 0:
try:
fset_obj = Featureditemset.objects.get(id=fset_id)
except Featureditemset.DoesNotExist:
# bad or no id passed
return HttpResponse('ObjectDoesNotExist')
else:
# get new featured set object
fset_obj = Featureditemset(id = get_next_auto_inc(Featureditemset))
# define formset to work with featured items
FeaturedItemFormSet = inlineformset_factory(Featureditemset, Featureditem, extra=1, form=FeatureditemEditForm)
if request.method == 'POST':
form = FeatureditemsetEditForm(request.POST, request.FILES, instance=fset_obj, prefix='set')
if form.is_valid():
featured_item_formset = FeaturedItemFormSet(request.POST, request.FILES, instance=fset_obj, prefix='item')
if featured_item_formset.is_valid():
# save form
form.save()
# save formset
print 'Formset: %s' % str(featured_item_formset)
print 'cleaned_data: %s' % featured_item_formset.cleaned_data
featured_item_formset.save()
return HttpResponse('valid')
else:
form = FeatureditemsetEditForm(instance=fset_obj, prefix='set')
featured_item_formset = FeaturedItemFormSet(instance=fset_obj, prefix='item')
c['form'] = form
c['formset'] = featured_item_formset
return render_to_response('admin/edit_featured.html', c, context_instance = RequestContext(request))
Forms:
class FeatureditemEditForm(ModelForm):
class Meta:
model = Featureditem
fields = ('id','img', 'name', 'folio')
class FeatureditemsetEditForm(ModelForm):
class Meta:
model = Featureditemset
fields = ('name', 'application')
Models:
class Featureditemset(models.Model):
id = models.BigIntegerField(primary_key=True, db_column='FEATUREDITEMSET_ID')
application = models.ForeignKey(Application, null=True, db_column='FEATUREDITEMSET_APPLICATION_ID', blank=True)
htmlcontent = models.TextField(db_column='FEATUREDITEMSET_HTMLCONTENT', blank=True)
modified = models.DateTimeField(db_column='FEATUREDITEMSET_MODIFIED', auto_now=True)
viewer = models.ForeignKey(Viewer, null=True, db_column='FEATUREDITEMSET_VIEWER', blank=True)
name = models.CharField(max_length=192, db_column='FEATUREDITEMSET_NAME', blank=True)
class Meta:
db_table = u'featureditemset'
def __unicode__(self):
return str(self.name)
class Featureditem(models.Model):
id = models.BigIntegerField(db_column='FEATURED_ITEM_ID', primary_key=True)
img = models.FileField(upload_to='featured', db_column='FEATURED_ITEM_IMG_URL', blank=True)
alt_title = models.CharField(max_length=768, db_column='FEATURED_ITEM_ALT_TITLE', blank=True)
modified = models.DateTimeField(db_column='FEATURED_ITEM_MODIFIED', auto_now=True)
folio = models.ForeignKey(Folio, db_column='FEATURED_ITEM_FOLIO_ID', blank=False)
app = models.ForeignKey(Application, null=True, db_column='FEATURED_ITEM_APP_ID', blank=True)
name = models.CharField(max_length=192, db_column='FEATURED_ITEM_NAME', blank=True)
featureditemset = models.ForeignKey(Featureditemset, null=True, db_column='FEATUREDITEM_FEATUREDITEMSET_ID', blank=True)
def __unicode__(self):
return self.name
class Meta:
db_table = u'featureditem'
Output to console:
Formset: <input type="hidden" name="item-TOTAL_FORMS" value="1" id="id_item-TOTAL_FORMS" /><input type="hidden" name="item-INITIAL_FORMS" value="1" id="id_item-INITIAL_FORMS" /><input type="hidden" name="item-MAX_NUM_FORMS" id="id_item-MAX_NUM_FORMS" />
<tr><th><label for="id_item-0-id">Id:</label></th><td><input type="text" name="item-0-id" value="5" id="id_item-0-id" /></td></tr>
<tr><th><label for="id_item-0-img">Featured Image:</label></th><td><input type="file" name="item-0-img" id="id_item-0-img" /></td></tr>
<tr><th><label for="id_item-0-name">Name:</label></th><td><input id="id_item-0-name" type="text" name="item-0-name" value="item1" maxlength="192" /></td></tr>
<tr><th><label for="id_item-0-folio">Folio:</label></th><td><select name="item-0-folio" id="id_item-0-folio">
<option value="1" selected="selected">0000054220110900000025</option>
<option value="2">com.maned.kwmultitest</option>
</select></td></tr>
<tr><th><label for="id_item-0-DELETE">Delete:</label></th><td><input type="checkbox" name="item-0-DELETE" id="id_item-0-DELETE" /><input type="hidden" name="item-0-featureditemset" id="id_item-0-featureditemset" /></td></tr>
cleaned_data: [{'id': 5}]
I figured it out. This line in my form constructor was (only sometimes?) throwing an IOError and screwing up my formset form validation/cleaning:
self.fields['img'] = forms.ImageField(label='Featured Image') # gets rid of 'clear' checkbox
When I posted my code, I took out some of the (what I thought was superfluous) form code, but what I took out turned out to be the source of the problem.