My decimal ModelForm fields are being displayed with an "up/down arrows" within the field that increases/descrease the field's values.
Any feedback on how I could remove/hide those arrows?
Form:
class PriceAssessment1Form(forms.ModelForm):
class Meta:
model = Component
fields = ['size_height','size_width','size_length','weight','base_material_price']
Model
class Component(models.Model):
name = models.CharField(max_length=255)
created_date= models.DateTimeField(default=datetime.now)
user = models.ForeignKey(User)
price_assessment_started = models.BooleanField(default=False)
size_height = models.DecimalField(null=True,blank=True, max_digits=9, decimal_places=2)
size_width = models.DecimalField(null=True,blank=True, max_digits=9, decimal_places=2)
size_length = models.DecimalField(null=True,blank=True, max_digits=9, decimal_places=2)
weight = models.DecimalField(null=True,blank=True, max_digits=9, decimal_places=2)
base_material_price = models.DecimalField(null=True,blank=True, max_digits=9, decimal_places=2)
Template
<form action="{% url 'portal_price_assessment' component_id %}" method="post"> {% csrf_token %}
<div>
<div>size_height {{ form.size_height }}</div>
<div>size_width {{ form.size_width }}</div>
<div>size_length {{ form.size_length }}</div>
<div>weight {{ form.weight }}</div>
<div>base_material_price {{ form.base_material_price }}</div>
</div>
<div style="margin-top:18px;">
Cancel
<button class="btn" type="submit" > Save & Close</button>
</div>
</form>
You can override the ModelForm field to use whatever widget you would prefer like so:
class AuthorForm(ModelForm):
class Meta:
model = Author
fields = ('name', 'title', 'birth_date')
widgets = {
'name': TextInput(attrs={'placeholder': 'That dude cray'}),
}
Example got from the django docs Overriding ModelForm fields
I found the answer here: Can I hide the HTML5 number input’s spin box?
The "arrows" are called "spinners"
Related
I want to choose only a car_model related to the selected vehicle_brand. Is it possible to do in django? Or need to use JS?
Template rendering Vehicle model objects, that contains vehicle_brand and car_model fields. What did I expect? When selecting a vehicle brand in the form field filter car_model queryset that related to the vehicle brand.
The code example below:
forms.py
vehicle_brand = forms.ModelChoiceField(label='Бренд', queryset=VehicleBrand.objects.all(),
widget=forms.Select(attrs={'class': 'select form-select'}))
car_model = forms.ModelChoiceField(label='Модель', queryset=CarModel.objects.all(),
widget=forms.Select(attrs={'class': 'select form-select'}))
models.py
class Vehicle(models.Model):
vehicle_brand = models.ForeignKey('VehicleBrand', on_delete=models.CASCADE)
car_model = models.ForeignKey('CarModel', on_delete=models.DO_NOTHING)
class CarModel(models.Model):
car_brand = models.ForeignKey(VehicleBrand, on_delete=models.DO_NOTHING)
year_production = models.DateField()
template:
<div class="mb-3">
{{ form.vehicle_brand|label_with_classes:"form-label" }}
{{ form.vehicle_brand }}
</div>
<div class="mb-3">
{{ form.car_model|label_with_classes:"form-label" }}
{{ form.car_model }}
</div>
I have the model, serializer, viewset and html as follows:
GENDER = (
('MALE', 'Male'),
('FEMALE', 'Female'),
('OTHERS', 'Others'),
)
class Client(BaseModel):
first_name = models.CharField(max_length=256)
last_name = models.CharField(max_length=256, default="", blank=True, null=True)
designation = models.CharField(max_length=256, default="", blank=True, null=True)
gender = models.CharField(max_length=20, choices=GENDER, null=True, blank=True)
class ClientSerializer(QueryFieldsMixin, DynamicFieldsModelSerializer):
name = serializers.SerializerMethodField()
def get_name(self, obj):
return getattr(obj, "first_name", "") + " " + getattr(obj, "last_name", "")
class Meta:
model = Client
fields = '__all__'
#method_decorator(login_required, name='dispatch')
class ClientViewSet(viewsets.ModelViewSet):
model = Client
queryset = model.objects.all()
serializer_class = ClientSerializer
#action(detail=True, methods=['post','get'], renderer_classes=[renderers.TemplateHTMLRenderer])
def update_client(self, request, *args, **kwargs):
object = self.get_object()
context = {"operation": "Update",
"object_id": object.id,
"events": Event.GetEventsForObject(object)}
template_name = 'contact-client.html'
response = Response(context, template_name=template_name)
<form id="client-form" method="" action="" enctype="multipart/form-data" operation="{{operation}}">
{% csrf_token %}
<div class="row">
<div class="columns medium-5 medium-text-left">
<div class="select2-full select-2-full--sm input-rounded">
<label for = "gender" style="text-align: left;" >Gender</label>
<select id="gender" class="js-select2 input-height-sm element-contact" name="gender" validated="false"></select>
<option></option>
</div>
<div id="gender_error" style="display:none">
<p class="help-text"> <span class="form-action-icon error-icon"></span>Please select gender.</p>
</div>
</div>
<div class="columns medium-5 medium-text-left">
</div>
</div>
</form>
When I instantiate the ClientSerializer in shell like this ClientSerializer() then that gender field is shown along with its choices. But I am not able to show it in the template. All the other fields are being passed correctly.
How can I populate the dropdown with the values of choices in template? What should I pass in the option tag to display the choices and send the data to the view?
Use a ChoiceField instead of CharField
Replace this line
gender = models.CharField(max_length=20, choices=GENDER, null=True, blank=True)
with this one
gender = models.ChoiceField(max_length=20, choices=GENDER, null=True, blank=True)
To show all the choices in your template you can do something like this
from my_app.models import gender
context = {"choices" : gender}
response = Response(context,template_name)
And in template
{% for choice in choices %}
<option value="{{ choice }}">{{ choice }}</option>
{% endfor %}
If you are using the django-template then you can create a model form and pass that form as render context and then render that inside a form.
More on model form: https://docs.djangoproject.com/en/3.1/topics/forms/modelforms/
I am trying to show a drop-down menu in a Django Template but it does not appear. Here is my code:
Post Model:
class Post(models.Model):
category_choices = (
('technology', 'Technology'),
('personal', 'Personal'),
('poetry', 'Poetry'),
('rants', 'Rants'),
('random', 'Random'),
)
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=70)
body = models.TextField()
summary = models.CharField(max_length=100)
created_date = models.DateTimeField(default=timezone.now())
published_date = models.DateTimeField(blank=True, null=True)
slug = models.SlugField(max_length=40, unique=True)
category = models.CharField(max_length=10, choices=category_choices, default='technology')
Form:
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'category', 'body')
Template:
<h1>New post</h1>
<div class="row">
<form method="POST" action="{% url 'post_new' %}" class="col s12 m12 l12"> {% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn">Save</button>
</form>
</div>
And this is how it looks in a browser:
Can you try {{ form.category }} in form tag? Just to test.
I was able to render the form onto the html, input data and submit it but i got a NOT NULL constraint failure. Isn't the owner assigned to its respective owners when as i have indicated in my views? i do not know what is wrong here please help!
Models
class Car(models.Model):
owner = models.ForeignKey('auth.User', on_delete=models.CASCADE)
name = models.CharField(max_length=100)
model = models.CharField(max_length=100)
description = models.TextField()
image = models.ImageField(upload_to=upload_image_path, null=True, blank=True)
created = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now_add=False)
mileage = models.IntegerField()
open_market_value = models.DecimalField(max_digits=12, decimal_places=2)
depreciation = models.DecimalField(max_digits=10, decimal_places=2)
down_payment = models.DecimalField(max_digits=10, decimal_places=2)
road_tax = models.DecimalField(max_digits=8, decimal_places=2)
installment = models.DecimalField(max_digits=8, decimal_places=2)
objects = models.Manager()
def __str__(self):
return self.name
Views
class CarCreate(CreateView):
model = Car
fields = [
'name', 'model',
'description', 'image',
'updated', 'mileage',
'open_market_value', 'depreciation',
'down_payment', 'road_tax',
'installment']
template_name = 'cars/create_car.html'
def form_valid(self, form):
form.instance.created_by = self.request.user
return super().form_valid(form)
HTML
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<!-- Default form contact -->
<form action="{% url 'cars:create' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form | crispy}}
<input type="submit" value="save">
</form>
<!-- Default form contact -->
{% endblock %}
Your model has a foreign key to the User model from 'django.auth'. While you are trying to save the object of 'Car' model as there was no object mentioned for the 'owner' field of the model, it is showing the error. So, you might want to explicitly mention it.
You can do something like this. Assuming that you have 'CarForm', a model form for you 'Car' model.
user = request.user
car_form = CarForm(request.POST)
if car_form.is_valid():
car = car_form.save(False)
car.owner = user
car.save()
This is most likely because owner is a required field in your model Car but you have not included it in the fields in your CreateView.
I have the following model in models.py
class TProfiles(models.Model):
id = models.IntegerField(primary_key=True) # AutoField?
first_name = models.CharField(max_length=45, blank=True)
surname = models.CharField(max_length=45, blank=True)
email = models.CharField(max_length=45, blank=True)
class Meta:
managed = False
db_table = 'profiles'
And in my template I want to produce a form based on the model attributes. Is there a way of looping through them dynamically?
register.html
{% block content %}
<form enctype="multipart/form-data" action="" method="post">
<!-- Loop through model attributes here -->
</form>
{% endblock %}
in models.py add:
class TProfilesForm(ModelForm):
class Meta:
model = TProfiles
fields = ['first_name', 'surname', 'email']
And in views.py create form like this:
form = TProfilesForm()
Then pass it to template like this:
return render_to_response("register.html", {
"form": form,
})
And in template:
{% for field in form %}
{{ field.label_tag }} {{ field }}
{% endfor %}
Also you can find all about ModelForm here