match string with database values in django - django

I have a database table 'travel'.There is a column called travelclasss and it contains values 'economy,business,firstclass'.I have a form
<form id="search-form">
FROM<input type="text" name="f"><br>
TO<input type="text" name="t"><br>
CLASS<input type="text" name="c"><br>
<input type="submit" value="Search">
</form>
If I enter in my form CLASS field either economy 'or' business 'or' firstclass I want to check these names are in my database travelclasss column.
I need implement it in django. How to check particular name is present in database using django.

You can do like this:
models.py
from django.db import models
class Travel(models.Model):
TRAVEL_CHOICES = (
('EC', 'economy'),
('BS', 'business'),
('FC', 'firstclass'),
)
travelclasss = models.CharField(max_length=2,
choices=TRAVEL_CHOICES,
default='EC')
forms.py
from django.forms import ModelForm
from yourapp.models import Travel
class TravelForm(ModelForm):
class Meta:
model = Travel
fields = ['travelclasss']
Then, you will have a drop-down box to choose from.
Here is more doc on ModelForms.
Here is more doc on Choices.

Related

Django Model Field for html5 Range Slider

I'm looking for a Django Model Field to render a HTML5 range slider like:
<input type="range" min="1" max="100" value="50">
This question comes close to Which Django Form Field can provide me a HTML output of <input type="range" />? but it asks for a form where I would search for an admin field for Django Admin.
Further this discussion shows as well how to use an IntegerField as range slider in forms:
https://code.djangoproject.com/ticket/20674
Long story short, can I use forms in Django Admin, or is there already a specific range field?
You can implement a widget, just like Django implements widgets. For example the NumberInput widget [GitHub] looks like:
class NumberInput(Input):
input_type = 'number'
template_name = 'django/forms/widgets/number.html'
We can do this ourselves, for example with a:
# app_name/widgets.py
from django.forms.widgets import NumberInput
class RangeInput(NumberInput):
input_type = 'range'
then you can use this widget with:
# app_name/forms.py
from app_name.widgets import RangeInput
class MyForm(forms.Form):
myint = forms.IntegerField(widget=RangeInput)

How to create Django_filter in Checkbox view on my website front panel?

I am using django_fiter package for filter data, but it's displaying filter in the input box or some filter in the dropdowns, but I want all filters in the checkbox (like as Django default admin panel filter), please let me know how I can convert it in checkbox filter on my website front panel.
Here is my code for filter view form...
<form method="get">
{{ filter.form|bootstrap }}
<input type="submit" />
</form>
and here is my views.py file code...
class ProductFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='icontains')
class Meta:
model = Product
fields = ['saleprice', 'title','veg_non','brand','supplement']
it's looking like this...
and I want in this format, please let me know how I can customize it.

Django OneToOneField show up on ModelForm of other entity?

I have the following classes:
class Account(models.Model):
instance = models.OneToOneField(Instance, blank=True, null=True)
class Instance(models.Model):
is_ready = models.BooleanField(default=False, verbose_name=_('Ready?'))
Right now the relationship between Account and Instance is set by a ModelForm for Account via Account.instance.
I would like to be able to set Account.instance via a ModelForm on Instance. Is that possible?
A ModelForm is:
a helper class that lets you create a Form class from a Django model.
An idea would be to write a custom model Field to address this issue. However, according to the relevant chapter of Writing Custom Model Fields
Fields in a model must somehow be converted to fit into an existing database column type.
Trying to spot the available postgreSQL column types I found this page which does not seem to provide a solution.
On the other hand, there is an old but updated SO post, which gives a solution that actually renders both forms in an HTML page and -this way- you gather all the needed fields in one form.
forms.py
class AccountForm(forms.ModelForm):
... Do stuff if necessary ...
class Meta:
model = Account
fields = ('the_fields', 'you_want')
class InstanceForm (forms.ModelForm):
... Do other stuff if necessary ...
class Meta:
model = Instance
fields = ('the_fields', 'you_want')
views.py
...
def register(request):
if request.method == 'POST':
account_form = AccountForm(request.POST)
instance_form = InstanceForm(request.POST)
if account_form.is_valid() and instance_form.is_valid():
account_form.save()
instance_form.save()
...
the_template.html
<form action="." method="post">
{% csrf_token %}
{{ account_form.as_p }}
{{ instance_form.as_p }}
<input type="submit" value="Submit">
</form>
This is also the idea of the admin's class InlineModelAdmin.
In the admin, for example, Account will become an inline model to Instance (which is a bad name for a django class).
admin.py:
from django.contrib import admin
class InstanceInline(admin.TabularInline):
model = Instance
class AccountAdmin(admin.ModelAdmin):
inlines = [
InstanceInline,
]

How to replace form field with custom layout in Django?

I have a model form field which is a choice field. Instead of having the default widget:
I would like to have a grid of cards like so:
With each of the choices that would have been in the default widget in a card.
How do I edit the python form to achieve this?
Here is my form:
from django import forms
from . import models
class PostJobForm(forms.ModelForm):
class Meta:
model = models.Job
fields = [
'title',
'description',
'pay',
'category'
]
You will have to move away from default django forms and create the forms using html, css and js the way you want.
When using django forms, it uses default templates.
<form method="post" action"">
<input type="text" id="id_title" name="title">
<!--this input is for title field of your model form-->
</form>
as shown above you can do it for any field that you want
IMP keep the name attribute of input and that of model field same

Internationalizing a Django class-based generic view (CreateView)?

I am using Django 1.9 class-based generic views, for example CreateView. When I visit the "create" page, some parts are translated (into French in my example), so I know my config and wiring is correct, but the form fields (auto-named by the view) are not (i.e. form.as_p).
How can I get form fields to be used from my translations file? (For example, "Name" is a field, already translated, but not picked up by the form.as_p).
One answer is to list out the fields individually in the template with {% trans %} tags. I was hoping to avoid that.
My example is similar to the one in the docs, so let me repeat that example here. First, code:
from django.views.generic.edit import CreateView
from myapp.models import Author
class AuthorCreate(CreateView):
model = Author
fields = ['name']
Then display template:
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save" />
</form>
Have a look at the Lazy Translation:
This is essential when calls to these functions are located in code paths that are executed at module load time.
This is something that can easily happen when defining models, forms and model forms, because Django implements these such that their fields are actually class-level attributes.
So, if you have a form, you can use ugettext_lazy to translate:
from django.db import models
from django.utils.translation import ugettext_lazy as _
class MyThing(models.Model):
name = models.CharField(help_text=_('This is the help text'))
You can mark names of ForeignKey, ManyToManyField or OneToOneField relationship as translatable by using their verbose_name options:
class MyThing(models.Model):
kind = models.ForeignKey(
ThingKind,
on_delete=models.CASCADE,
related_name='kinds',
verbose_name=_('kind'),
)