Django - why don't my radio buttons render? - django

models.py
class Trip(models.Model):
location_name = models.CharField(max_length=60)
trip_date = models.DateField()
trip_rating = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)])
fishing_vehicle = models.ForeignKey(FishingVehicle)
water_body = models.ForeignKey(WaterBody)
user = models.ForeignKey(User)
def __unicode__(self):
return self.location_name
forms.py
class TripForm(ModelForm):
class Meta:
model = Trip
exclude = ['user']
CHOICES = (('1', 'First',), ('2', 'Second',))
trip_rating = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)
logtrip.html
{% extends "base.html" %}
{% block content %}
<div class="container">
<!-- Example row of columns -->
<div class="row">
<div class="col-md-4">
<form action="/logtrip/" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
</div>
</div>
</div>
{% endblock %}
My form renders without error, but instead of getting a pair of radio buttons for the trip_rating field, a number field is rendered,
<input id="id_trip_rating" name="trip_rating" type="number">
How can I get those radio buttons?

The form field in the modelform is a class level property, and not a Meta property
class TripForm(ModelForm):
CHOICES = (('1', 'First',), ('2', 'Second',))
trip_rating = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)
class Meta:
model = Trip
exclude = ['user']
should do the trick.

Related

Adding image for blog posts

Coding some kind of blog with django, and I can't make homepage to contain images of the articles... It just doesn't upload a image...
my Views.py :
class AddPostView(CreateView):
model = Post
form_class = PostForm
template_name = 'add_post.html'
my Models.py:
class Post(models.Model):
title = models.CharField(max_length=255)
title_tag = models.CharField(max_length=255, default="YNTN")
#author = models.ForeignKey(User, on_delete=models.CASCADE)
body = RichTextField(blank=True, null=True)
image = models.ImageField(upload_to="profile_pics", blank=True, null=True)
#body = models.TextField()
post_date = models.DateField(auto_now_add=True)
likes = models.ManyToManyField(User, related_name="blog_posts")
def total_likes(self):
return self.likes.count()
def __str__(self):
return (self.title + " | " + str(self.author))
def get_absolute_url(self):
return reverse("home")
My Forms.py:
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'title_tag', 'body', 'image')
widgets = {
'title': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Title of the Blog'}),
'title_tag': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Copy the title with no space and a hyphen in between'}),
'body': forms.Textarea(attrs={'class':'form-control', 'placeholder':'Content of the Blog'}),
}
and my add_post.html :
{% extends 'base.html' %}
{% block title %}Make an article{% endblock %}
{% block content %}
{% if user.is_authenticated %}
<h1>Make an article</h1>
<div class="form-group">
<form method="POST">
<br/>
{% csrf_token %}
{{ form.media }}
{{ form.as_p }}
<button class="btn btn-dark">POST</button>
</div>
{% else %}
<h1>You are not allowed to post! You need to Log in or Register</h1>
{% endif %}
{% endblock %}
I tried on many ways but never worked..
You are missing enctype="multipart/form-data" (as mentioned in the documentation) in the form tag inside the html template. Update the html file like this:
<form method="POST" enctype="multipart/form-data">
<br/>
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-dark">POST</button>
</form>

DJANGO: Save two forms within one class-based view

I have difficulties saving 2 forms within one view the only first one is saving but I cant figure out how to save the second one. Here is my code and issue :
models.py
class Office(models.Model):
name = models.CharField(max_length=100,null=True)
Address = models.ForeignKey(Address, on_delete=models.CASCADE, related_name='officeAddress',blank=True,null=True)
def __str__(self):
return self.name
class Address(models.Model):
address_line = models.CharField(max_length=60, blank=True)
address_line2 = models.CharField(max_length=60, blank=True)
country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='District')
province=ChainedForeignKey(Province,chained_field="country",chained_model_field=
"country",show_all=False,auto_choose=True,sort=True)
district=ChainedForeignKey(District,chained_field="province",
chained_model_field="province",show_all=False,auto_choose=True,sort=True)
class Meta:
verbose_name = "Address"
verbose_name_plural = "Addresses"
forms.py
class OfficeModelForm(BSModalModelForm):
class Meta:
model = Office
fields = ['name']
class AddressForm(forms.ModelForm):
class Meta:
model = Address
fields = ['address_line','address_line2','country','province','district']
views.py
class OfficeCreateView(BSModalCreateView):
form_class = OfficeModelForm
second_form_class = AddressForm
template_name = 'settings/create_office.html'
success_message = 'Success: Office was created.'
success_url = reverse_lazy('company:office-list')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['address'] = self.second_form_class
return context
create_office.html
{% load static i18n %}
{% load widget_tweaks %}
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
{{ address.media.js }}
<div class="modal-body">
<div class="form-group">{% render_field form.name %}</div>
<div class="form-group">{% render_field address.address_line %}</div>
<div class="form-group">{% render_field address.address_line2 %}</div>
<div class="form-group">{% render_field address.country %}</div>
<div class="form-group">{% render_field address.province %}</div>
<div class="form-group">{% render_field address.district %}</div>
<button class="btn btn-primary ms-auto" type="submit">{% trans "Create new office" %}</button>
</div>
</form>
I think I need first to save the address then use the address.id as a foreign key for office but I don't know how to do this in CBV.
Thanks for your help...
You should change models base names. Example:
class OfficeCreateView(CreateView) instead class OfficeCreateView(BSModalCreateView)
or
class OfficeModelForm(form.ModelForm) instead class OfficeModelForm(BSModalModelForm)

My form keep saying "This(image) field is required!" Django 3.0

I made a project with net-ninja on youtube now I am adding "uploading media" feature in my own project but it is not working although every thing is set just tell me where i m going wrong.
My form is keep asking me to upload image file even though i had already done, every time i send a post request it renders the page again with no value in image field. what is wrong here, why it is not taking image input?Don't comment set the required to false that is not the solution i don't know why some people said this to others on stackoverflow when they asked the same question as me.
My model class looks like this
class Products(models.Model):
name = models.CharField(max_length=500, unique=True, )
price = models.IntegerField()
stock = models.IntegerField()
date_added = models.DateTimeField(verbose_name="date added", auto_now_add=True, )
thumb = models.ImageField(default='default.png', blank=True)
profile = models.ForeignKey(Profile, on_delete=models.CASCADE, default=None,)
def __str__(self):
return self.name
class Meta():
verbose_name_plural = "Products"
My form looks like this
class AddProduct(forms.ModelForm):
name = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Product Name', 'required':'True', 'class': 'form-control'}))
price = forms.IntegerField(widget=forms.NumberInput(attrs={'placeholder':'Set Price', 'required':'True', 'class': 'form-control'}))
stock = forms.IntegerField(widget=forms.NumberInput(attrs={'placeholder':'Number of items', 'required':'True', 'class': 'form-control'}))
thumb = forms.ImageField(required=False, widget=forms.ClearableFileInput(attrs={'placeholder':'Upload Picture', 'enctype' : 'multipart/form-data'}))
class Meta():
model = Products
fields = ('name', 'price', 'stock','thumb', )
HTML looks like this
<form class="row contact_form" action="/shop/add_products" method="post">
{% csrf_token %}
{% for field in form %}
<div class="col-md-12 form-group p_star">
{{ field }}
{{ field.errors }}
</div>
{% endfor %}
<!-- {% for field in form %}
{% for error in field.errors %}
<div class="col-md-12 form-group p_star">
{{ error }}
</div>
{% endfor %}
{% endfor %} -->
{% if form.non_field_errors %}
<div class="col-md-12 form-group p_star">
{{ form.non_field_errors }}
</div>
{% endif %}
<div class="col-md-12 form-group">
<button type="submit" value="submit" class="btn_3">
Add Product
</button>
</div>
</form>
My views file looks like this
#login_required(login_url='/shop/login')
def shop_add_products(request):
if request.method == 'POST':
form = AddProduct(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.profile = request.user
instance.save()
return redirect("/shop/products")
else:
form = AddProduct()
return render(request, "pillow_site_html/add_product.html", { 'form':form })
Oh sorry i didn't understood the question here, you are getting that because in fact you are not sending the picture inside your form as you have to add this to your form so it can accept files handling
<form class="row contact_form" action="/shop/add_products" method="post" enctype="multipart/form-data">

Django 'unicode' object has no attribute 'field'

I recently added crispy_forms to my django project and it caused me to get the 'unicode' object has no attribute 'field' error. Can't figure out why.
models.py
class Trip(models.Model):
location_name = models.CharField(max_length=60)
trip_date = models.DateField()
trip_rating = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)])
fishing_vehicle = models.ForeignKey(FishingVehicle)
water_body = models.ForeignKey(WaterBody)
user = models.ForeignKey(User)
def __unicode__(self):
return self.location_name
views.py
#login_required
def logtrip(request):
if request.method == 'POST':
form = forms.TripForm(request.POST)
if form.is_valid():
trip = form.save(commit=False)
trip.user = request.user
trip.save()
return redirect('home')
else:
print form.errors
else:
form = forms.TripForm()
return render_to_response('logtrip.html', {'form': form}, context_instance=RequestContext(request))
forms.py
class TripForm(ModelForm):
CHOICES = (('1', 'None',), ('2', 'Below Average Amount',), ('3', 'Average Amount',), ('4', 'Above Average Amount',), ('5', 'A Lot/Limited Out',))
trip_rating = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES, label='Fish Caught')
class Meta:
model = Trip
exclude = ['user']
widgets = {'trip_date': forms.DateInput(attrs={'class':'datepicker'})}
logtrip.html
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container">
<!-- Example row of columns -->
<div class="row">
<div class="col-md-4">
<form action="/logtrip/" method="post">
{% csrf_token %}
{{ form.as_p|crispy }}
<input type="submit" value="Submit" />
</form>
</div>
</div>
</div>
{% endblock %}
Everything works correctly when I remove the |crispy filter.
For anyone else getting this error, my problem was solved by changing {{ form.as_p|crispy }} to {{ form|crispy }}.

How to split render django's ModelMultipleChoiceField in template file?

I want to make (ordered) Song list form.
models.py
class Song(models.Model):
title = models.CharField(max_length=60)
class List(models.Model):
title = models.CharField(max_length=100)
songs = models.ManyToManyField(Song, through='Order')
class Order(models.Model):
list = models.ForeignKey(List)
song = models.ForeignKey(Song)
order = models.IntegerField(unique=True)
and,
forms.py
class ListEditForm(forms.Form):
title = forms.CharField(
label='List Title',
widget=forms.TextInput(attrs={'size':100})
)
songs = forms.ModelMultipleChoiceField(
label= 'Song Order',
required= False,
widget=forms.CheckboxSelectMultiple,
queryset= Song.objects.none()
)
and then,
ListEditForm.py
<form id="edit-form" method="post" action="/list/edit/">
<p>
{{ form.title.errors }}
{{ form.title.label_tag }}
{{ form.title }}
</p>
<p>
{% for song in form.songs %}
{{ song.label_tag }}
{{ song }}
{% endfor %}
</p>
<input type="submit" value="save" />
</form>
This template raises following error:
Caught an exception while rendering: 'BoundField' object is not iterable
How do I split render each form field in 'form.songs'?
You're getting a not iterable error because ListEditForm.songs is a single field that contains a list of song choices, rather than a list of individual song fields. From your description I'm not sure how you wanted the list to be rendered.
I would suggest looking into using a Django formset. http://docs.djangoproject.com/en/dev/topics/forms/formsets/