How to show ManyToMany fields using CreateView in Django 1.8 - django

I'm doing a basic application in Django 1.8 and I'm using Create-View, I don't know why the create form doesn't have manyTOmany fields neither foreign-key field previously defined in my model. This is my code:
My Model:
class Autor(models.Model):
nombre = models.CharField(max_length=30)
....
class Editor(models.Model):
nombre = models.CharField(max_length=30)
...
class Libro(models.Model):
titulo = models.CharField(max_length=100)
autores = models.ManyToManyField(Autor) #MANY2MANY FIELD
editor = models.ForeignKey(Editor) #FOREIGN KEY FIELD
fecha_publicacion = models.DateField()
portada = models.ImageField(upload_to = 'portadas/')
def __unicode__(self):
return self.titulo
My View:
class LibroCreateView(CreateView):
model = Libro
template_name = 'biblioteca/crear.html'
fields = ['titulo', 'autores', 'editor', 'fecha_publicacion', 'portada']
My template:
{% block main %}
<form action="" enctype="multipart/form-data" method="POST">{% csrf_token %}
<table>
{{form.as_table}}
</table>
<input type="submit" name="crear" value="Crear">
</form> <br>
{% endblock main %}
My result
Why isn't my fields "Autores"(many2many) and "Editor"(foreign-key) correctly shown?. Thanks.

Try giving form to the view that is CreateView. Make a ModelForm using your model
There you can do query for you foreign key and many to many field.
You can present them as you like

Related

model form not rendering in django template

My models.py and this is my model for photos.
# home photo page
class Photos(models.Model):
photo_title = models.CharField(max_length=50, blank=False)
photo_description = models.CharField(max_length=50, blank=False)
photo_date = models.DateField(blank=False)
photo_location = models.CharField(max_length=50, blank=False)
photo_file = models.FileField(upload_to='photos', blank=False)
def __str__(self):
return self.photo_title
My forms.py this is the model form I made to render it as a form.
class UploadPhotosForm(forms.Form):
class Meta:
model = Photos
fields = '__all__'
my views.py these are my relavent imports and section I coded in view file.
from .forms import CampForm, ProjectForm, HikeForm, UploadPostsForm, UploadPhotosForm
posts = UploadPostsForm()
photo = UploadPhotosForm()
print(photo.as_p())
here this code should print the form as text into console isn't it?
But I don't have any console output. It seems like the nothing has been initialized to the photo variable isn't it?
I do not have any clue what happened.
context = {
'title': 'manage_wall',
'posts': posts,
'photo': photo,
}
return render(request, 'manager/manage_wall.html', context)
My template
{% block content %}
<div class="container">
<div class="row">
<div class="col">
<form action="" method="post">
{% csrf_token %}
{{photo.as_p}}
<input type="submit" value="Add">
</form>
</div>
<div class="col">
<form action="" method="post">
{% csrf_token %}
{{posts.as_p}}
<input type="submit" value=" Add">
</form>
</div>
</div>
</div>
{%endblock %}
As you can see here my photoForm is not rendering in the frontend can someone point out the mistake I have made not to render that form only while other forms are successfully rendering in the frontend. My Question is all other model forms rendered successfully why this is not displaying properly.
Your UploadPhotosForm is inherited from forms.Form(...)
class which does not contain model in Meta class so instead of inheriting from forms.Form class inherit from form.ModelForm(...)
here is final version of your code
class UploadPhotosForm(forms.ModelForm):
class Meta:
model = Photos
fields = '__all__'
I found the answer in models.py it should be forms.ModelForm
class UploadPhotosForm(forms.ModelForm):
class Meta:
model = Photos
fields = '__all__'
it is not rendering unless it is a ModelForm

Url not being resolved in, 404 error django

I am not able to create an detail and update view using the <pk> and <pk>/update/, this is my url paths.
urlpatterns = [
path('',views.IndexView.as_view(), name='index'),
path('form/',views.CompanyView.as_view(),name='company'),
path('toy/',views.ToyView.as_view(),name='toy'),
path('int:pk>/',views.CompanyDetailView.as_view()),
path('int:pk>/update/',views.CompanyUpdateView.as_view())
]
my views looks like this,
class CompanyUpdateView(generic.UpdateView):
model = Company
fields = '__all__'
success_url = '/company'
class CompanyDetailView(generic.DetailView):
model = Company
fields = '__all__'
class CompanyView(generic.CreateView):
model = Company
template_name = 'company/company.html'
fields = '__all__'
success_url = '/company'
models.py is
class Company(models.Model):
company_name = models.CharField(max_length=50)
location = models.CharField(max_length=50)
email_id = models.EmailField()
def __str__(self):
return self.company_name
class Toys(models.Model):
toy_name = models.CharField(max_length=50)
company = models.ForeignKey(Company,on_delete=models.CASCADE,blank=True,null=True)
price = models.IntegerField()
This is the template used to in the CreateView and UpdateView since I am using a ModelForm
<form method="post">
{% csrf_token %}
<fieldset>
<legend>
<h2> Company Form </h2>
</legend>
{{ form.as_p }}
</fieldset>
<input type="submit" value="Submit" />
</form>
Create view is working. When I got to a url company/1/ or company/1/update I get a 404 error. What would be the reason for it and how to solve this

Django admin filters in custom template

I want to implement django admin filters in my custom template can any body from you help me in resolving this issue i will appreciate. i am getting this error ...... name 'AddFilter' is not defined...
models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=255)
price = models.DecimalField()
description = models.TextField()
release_date = models.DateField()
filters.py
import django_filters
class ProductFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='iexact')
class Meta:
model = Product
fields = ['price', 'release_date']
views.py
def filt_page(request):
filter = AddFilter(request.GET, queryset=Add.objects.all())
print (filter)
return render_to_response('filt_page.html',{'filter':filter})
template
<form action="" method="get"> {% csrf_token %}
{{ filter.form.as_p }}
<input type="submit" />
</form>
{% for obj in filter %}
{{ obj.name }}<br />
{% endfor %}
You've called an undefined class in your views.py
class name in filters.py is 'ProductFilter' but you've called 'AddFilter' in views.py
Also the model name in your filter is undefined, you've used 'Add' instead of 'Product'
Try
filter = ProductFilter(request.GET, queryset=Product.objects.all())

Django - Display imagefield in ManytoMany form instead of title

I am working on a Django project with crispy forms.
I want to use images instead of the the default Models title/label to select a instance in a Many to Many relation form.
Content models.py:
class Cloth(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL)
title = models.CharField(max_length=200)
picture = ImageCropField(upload_to='cloth_pics/%Y-%m-%d/',
blank=True)
def __str__(self):
return self.title
class Outfit(models.Model):
owner = models.ForeignKey('profiles.Profile')
title = models.CharField(max_length=200)
cloths=models.ManyToManyField(Cloth)
Content forms.py
class ClothForm(forms.ModelForm):
class Meta:
model = Cloth
fields = ('title','type','picture')
class OutfitForm(forms.ModelForm):
class Meta:
model = Outfit
exclude= ["owner"]
Content views.py
def outfits_new(request):
if request.method == "POST":
form = OutfitForm(request.POST)
if form.is_valid():
outfit = form.save(commit=False)
outfit.owner = get_user(request)
outfit.created_date = timezone.now()
outfit.save()
pk=outfit.id
return HttpResponseRedirect(reverse('outfit_edit_delete', args=[pk]))
else:
cloths = Cloth.objects.filter(owner=request.user.id)
form = OutfitForm()
return render(request, '../templates/outfits_new.html', {'form': form, "cloths":cloths})
Content outfits_new.html
<form enctype="multipart/form-data" method="post">
{% csrf_token %}
{{ form|crispy }}
<div class="btn-group" role="group" aria-label="Basic example">
<input type="submit" value="Submit" name="edit" class="btn btn-success">
</div>
This code produces a Outfit form where I can select different cloths( displaying the cloths title). I want to select different cloths using a image from the cloths.picture field.
Thank you very much,
Patrick
Have a look at select2 at https://select2.github.io/examples.html. It allows you to do images in comboboxes
There is a Django package at https://github.com/applegrew/django-select2

Building dynamic forms from models

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