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())
Related
I wanted to create simple datepicker that does not accept back dates. Within my models.py I have defined MealDay class and standalone functionvalidate_pub_date.
The logic behin works just fine, but I do not understand the way Django is showing up the ValidationError("Date can't be past!").
Why this is where it is, and why it seems to be within <li> tag? Is there any possibilty to handle the error within the HTML template or any other way to add some html/css to it? There is how the error looks now:
models.py:
def validate_pub_date(value):
if value < timezone.now() - datetime.timedelta(days=1):
raise ValidationError("Date can't be past!")
return value
class MealDay(models.Model):
day = models.DateTimeField(default=timezone.now().day, validators = [validate_pub_date])
breakfast = models.TextField(max_length=100, blank=True)
lunch = models.TextField(max_length=100)
dinner = models.TextField(max_length=100, blank=True)
views.py
class MealdayCreateView(CreateView):
model = MealDay
template_name = "mealplanner/mealday_new.html"
form_class = CreateMealdayForm
forms.py
class CreateMealdayForm(ModelForm):
class Meta:
model = MealDay
fields = '__all__'
widgets = {
'day': forms.DateInput(attrs={'type':'date'}),
}
mealday_new.html
{% extends "mealplanner/base.html" %}
{% block content %}
<h1>Plan your meals!</h1>
<form action="" method="post"> {% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save">
</form>
{% endblock content %}
{% endblock content %}
in django model (validate_field_name) method is connected with .is_valid() method so when all fields of modelform not get correct input till it's raise a validation error.
In my simple Django App, I've implemented django-select2. I have a form with 2 fields: product and category. When I create a new product I first give it a title and than tab to the category-field, but the dropdown does not open automatically. Only when I press Space-Bar or Enter the dropdown opens.
What can I do so that the dropdown opens automatically, when it is reached?
Here my code:
forms.py
from django import forms
from django_select2.forms import Select2Widget, ModelSelect2Widget, Select2MultipleWidget
from .models import Product, Category
class MyForm(forms.ModelForm):
category = ModelSelect2Widget(queryset=Category.objects.all())
class Meta:
model = Product
fields = ['name', 'category']
widgets = {
'category': Select2Widget,
}
models.py
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=120)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
def __str__(self):
return self.name
product.html
{% extends 'base.html' %}
{% block content %}
{{ form.media.css }}
<br>
<form action="" method="POST">
{% csrf_token %}
{{ form}}
<button type="submit">Save</button>
</form>
{{ form.media.js }}
{% endblock content %}
I wish for one of a parent's variables to be pre-populated in a child's model form specifically a serial number. I have managed to get the serial number as part of the URL but would like to figure out how it can be implemented as a variable on the form page.
Models.py
class Product(models.Model):
serial_number = models.CharField(unique=True, max_length=15)
class ProductInstance(models.Model):
serial_number = models.ForeignKey('Product', on_delete=models.SET_NULL, null=True)
Views.py
class ProductInstanceCreate(CreateView):
model = ProductInstance
template_name = 'myapp/edit_productinstance.html'
form_class = GunInstanceForm
def get_success_url(self):
return reverse_lazy ('product-detail', kwargs={'pk': self.object.serial_number.pk})
Forms.py
class ProductInstanceForm(forms.ModelForm):
class Meta:
model = ProductInstance
fields = '__all__'
templates/myapp/product_detail.html
...
New
...
urls.py
urlpatterns += [
url(r'^productinstance/(?P<serial_number>[-\w]+)/create/$', views.ProductInstanceCreate.as_view(), name='productinstance_create'),]
templates/myapp/edit_productinstance_form.html
{% extends "base_generic.html" %}
{% block content %}
<h2>Serial Number: {{ serial_number }}</h2>
</br>
<form action="" method="post">
{% csrf_token %}
<table>
{{ form }}
</table>
<input type="submit" value="Submit" />
</form>
</br>
Back
{% endblock %}
So currently I can create a URL such as: productinstance/D1430913/create/
I now need to know:
How to use it as a variable for the title?
How to set the the forms default value to it?
For the title:
<h2>Serial Number: {{ form.serial_number.value }}</h2>
I believe if you modify your CreateView like so and implement the serial_number_func() with whatever you need to get the serial number, this will do what you want:
class ProductInstanceCreate(CreateView):
model = ProductInstance
template_name = 'myapp/edit_productinstance.html'
form_class = GunInstanceForm
def get_form_kwargs(self):
kwargs = super(ProductInstanceCreate, self).get_form_kwargs()
kwargs['serial_number'] = serial_number_func()
return kwargs
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
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