How To style a Django formset for fileField - python

I have this formset.
instance = get_object_or_404(Post, user = request.user, slug = slug )
files = file.objects.all().filter(Post=instance)
FormSet = modelformset_factory(file, fields=('file',), can_delete=True)
formset=FormSet(request.POST or None, request.FILES or None, queryset=files)
models.py:
class file(models.Model):
file = models.FileField(upload_to = upload_location, blank = True, null = True)
Post = models.ForeignKey(Post, blank = True, null = True)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True, blank = True, null = True)
def filename(self):
f = self.file.name
f1 = f.split('/', 3)[-1]
return f1
def __unicode__(self):
return self.file.name
def __str__(self):
return self.file.name
thats how i used it in my template:
{{ formset.management_form }}
{% for form in formset %}
{{form.file}}
{{form.DELETE.label}}
{{form.DELETE}}
{% endfor %}
and it shows like this in my browser:
i tried every this but i could not able to to get rid of currently and i literally do not know how to style this. please help me guys.

Related

How can i call a list in django template?

Here is my models.py file.
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
from django.utils.text import slugify
import misaka
from django.contrib.auth import get_user_model
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=255, unique=True)
slug = models.SlugField(allow_unicode=True, unique=True)
description = models.TextField(blank=True, default='')
description_html = models.TextField(editable=False, default='',blank=True)
members = models.ManyToManyField(User, through="CategoryMember")
category_pic = models.ImageField(upload_to = 'category_pics', blank=True)
def __str__(self):
return self.name
# WE are saving the model. But before that we are converting
# the name using slugify and description using misaka.
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
self.description_html = misaka.html(self.description)
super().save(*args, **kwargs)
#get_absolute_url is used because it tell the template
# CreateView to go to the page it is directing.
# for this example it is directing to go to single page of a category.
def get_absolute_url(self):
return reverse("categories:single", kwargs={"slug":self.slug})
class Meta:
ordering = ['name']
class CategoryMember(models.Model):
category = models.ForeignKey(Category, related_name = "memberships", on_delete=models.CASCADE)
user = models.ForeignKey(User, related_name="user_categories", on_delete=models.CASCADE)
def __str__(self):
return self.user.username
class Meta:
unique_together= ("category", "user")
This is some part of views.py file
from django.contrib.auth.models import User
from categories.models import CategoryMember, Category
class UserPosts(ListView):
model = Post
template_name = 'posts/user_post_list.html'
def get_queryset(self):
try:
self.post_user = User.objects.prefetch_related("user_of_post_model").get(
username__iexact=self.kwargs.get("username")
)
except User.DoesNotExist:
raise Http404
else:
return self.post_user.user_of_post_model.all()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
current_user = UserProfileInfo.objects.filter(
user__id__iexact = self.post_user.id
).get()
i=1
user_categories={}
for member in CategoryMember.objects.all():
if member.user == self.post_user:
user_categories.update({i:member.category.name})
i=i+1
else:
print('not found')
print(user_categories)
if current_user.profile_pic:
profile_pic = True
picture = current_user.profile_pic
edited_picture = get_thumbnail(picture, '350x350', quality=99, format='PNG')
else:
profile_pic = False
root = settings.MEDIA_ROOT
import os
root1 = os.path.join(root, 'profile_pics/no-image.png')
picture = root1
edited_picture = get_thumbnail(picture, '350x350', quality=99, format='PNG')
# resizeimage.resize_cover(picture, [200, 100], validate=False)
# rescale_image(picture,width=100,height=100)
current_user1 = current_user
user_info = {
'current_user':current_user,
'user_categories':user_categories,
'picture':edited_picture,
'profile_pic':profile_pic,
'post_user':self.post_user,
}
context['user_info'] = user_info
return context
After rendering the html page i can see that dictionary has values inside. Here is the values printed in terminal.
not found
not found
not found
not found
not found
{1: 'Regression', 2: 'Classification'}
Now, i want to get user_categories in my django template. i have tried in different approaches but can't get user_categories .
this is some part of my django html file.
<h3>Member of Categories</h3>
{# this line shows error #}
{# {{ userinfo[{{user_categories}}] }} #}
{{ userinfo.user_categories.1 }}
{% for categories in userinfo.user_categories %}
{{categories}}
{% endfor %}
<h5 class="techfont">Post written by {{user_info.post_user.username}} : {{post_list.count}} </h5>
This section only renders user_info.post_user.username but not user_info.user_categories.1
see the text below.
Member of categories.
Post written by abc: 1
user_categories is a dictionary, not a list. So try like this:
{% for idx, categories in userinfo.user_categories.items %}
{{idx}}. {{categories}}
{% endfor %}

Django Formsets with ModelBase Not rendering the Checkbox default but a drop down list instead

I need to create a required checkbox option if no_new_item exists. I am using the model.NullBoolean field. According to Django docs the Boolean field should render the checkbox widget but NullBoolean renders Select. The reason for the switch to NullBoolean was due to the null error when migrating. So now I am getting a drop down list with 'Yes' and 'No.'
How would I go about creating the checkbox in the Base model.Models with NullBoolean or is there a better way?
(this is an edit as I miss spoke about the Django Docs. Thanks #Alasdair)
/models.py
class StoreNightlyReport(models.Model):
store_number = models.ForeignKey('Stores', verbose_name='Store Number', max_length=20, null=True)
date = models.DateField(null=True)
#managers = models.ManyToManyField('auth.User', blank=True, null=True)
def __str__(self):
return self.store_number.store_number
class StoreNightlyReportsBase(models.Model):
store_nightly_report = models.ForeignKey(StoreNightlyReport)
no_new_item = models.NullBooleanField(verbose_name='No New Items', default=True)
customer = models.CharField(verbose_name='Customer Name', max_length=20, null=True)
class Meta:
abstract = True
/forms.py
class StoreNightlyReportsForm(ModelForm):
class Meta:
model = StoreNightlyReport
widgets = {'date': SelectDateWidget()}
exclude = ()
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
super(StoreNightlyReportsForm, self).__init__(*args, **kwargs)
if 'store_number' in self.fields:
if not user.is_superuser:
self.fields['store_number'].queryset = Stores.objects.filter(managers=user)
/views.py
class StoresNightlyReportsNewLoansCreate(CreateView):
template_name = 'reports/storenightlyreport_form.html'
model = StoreNightlyReport
form_class = forms.StoreNightlyReportsForm
success_url = reverse_lazy('reports:storenightlyreports')
def get_form(self, form_class=None):
form_class = self.get_form_class()
form = form_class(self.request.POST or None, user=self.request.user)
self.formsets = {}
StoreNightlyReportsNewLoanFormSet = inlineformset_factory(StoreNightlyReport,
StoreNightlyReportsNewLoan,
exclude=[],
extra=1)
self.formsets['new_loan'] = StoreNightlyReportsNewLoanFormSet(self.request.POST or None)
def get_context_data(self, **kwargs):
data = super(StoresNightlyReportsNewLoansCreate, self).get_context_data(**kwargs)
data['formset_new_loan'] = self.formsets['new_loan']
return data
def get_context_data(self, **kwargs):
data = super(StoresNightlyReportsNewLoansCreate, self).get_context_data(**kwargs)
#formset_renewal = StoreNightlyReportsRenewalFormSet()
data['formset_new_loan'] = self.formsets['new_loan']
return super(StoresNightlyReportsNewLoansCreate, self).form_invalid(form)
/template.html
{% extends "reports/base.html" %}
{% load static %}
{% block body_block %}
<div class="container-fluid">
<form class="form-inline" action="" method="post">
{% csrf_token %}
{{ form }}
<table class="table">
{{ formset_new_loan.management_form }}
<div>
<br><h4><strong>New Loans</strong></h4><br>
{% include "reports/formsets.html" with formset=formset_new_loan formset_class_name='new_loan' %}
</div>
</table>
Fixed
After some thought I just went back to the model.Base and changed it to the BooleanField type and added a default value. This cleared the null error on migration and rendered a checkbox option.
class StoreNightlyReportsBase(models.Model):
store_nightly_report = models.ForeignKey(StoreNightlyReport)
no_new_item = models.BooleanField(verbose_name="Check if No New Items", default=False)
customer = models.CharField(verbose_name='Customer Name', max_length=20, null=True)

Cannot resole keyword 'carmodel' into field. Choices are: exterior_color, id, interior_color

As I want to filter on foreign key, I used carmodel with __ in the method dropdownlistsearch() of views.py. When run the code, it tells it must be a field. I don't understand this part. Why do I get this error. And I am using django 1.6.5.
models.py
from django.db import models
class CarInfo(models.Model):0
vin_number = models.CharField(max_length = 17)
model = models.ForeignKey(CarModel)
timestamp = models.DateTimeField(auto_now_add = True, auto_now = False)
updated = models.DateTimeField(auto_now_add = False, auto_now = True)
def __unicode__(self):
return self.vin_number
class CarModel(models.Model):
model = models.CharField(max_length = 60)
def __unicode__(self):
return self.model
views.py
def dropdownsearch(request):
try:
q = request.GET.get('q')
except:
q = None
if q:
cars = CarInfo.objects.filter(carmodel__model__contains=q)
template ='productions/resultstwo.html'
else:
template = 'prodcutions/cars.html'
context = {}
return render(request,template,context)
cars.html
<form action="/cars/s/" method="get">
<select name="q">
{% for info in modelinfos %}
<option value="{{info.model}}">{{info.model}}</option>
{% endfor %}
</select>
</form>
You are filtering on the forward relationship, so you use the actual field you have defined, model.
CarInfo.objects.filter(model__model__contains=q)
def testform(request):
form = CarInfo(request.POST or None)
if form.is_valid():
save_it = form.save(commit = False)
save_it.save()
return render_to_response("productions/testform.html",locals(),context_instance = RequestContext(request))

Multiple search criteria django form

Im following the Django docs in order to build a multiple search criteria form. My first question is if this should be the correct method of filtering values in the query and also how can i add the foreignkeys and m2m displayed as selects and multipleselects in the search criteria.. This is my code so far. Thanks
Forms
class SearchPropertyForm(forms.Form):
name = forms.CharField(max_length = 100, widget = forms.TextInput(attrs = {'class':'form-control', 'placeholder':'Nombre'}))
activity = forms.ModelChoiceField(queryset = Activity.objects.all(), widget = forms.Select(attrs = {'class':'form-control', 'placeholder':'Actividad'}))
currency = forms.ModelChoiceField(queryset = Currency.objects.all(), widget = forms.Select(attrs = {'class':'form-control', 'placeholder':'Moneda'}))
price_from = forms.IntegerField(widget = forms.TextInput(attrs = {'class':'form-control', 'placeholder':'Precio-Desde'}))
price_to = forms.IntegerField(widget = forms.TextInput(attrs = {'class':'form-control', 'placeholder':'Precio-Hasta'}))
categories = forms.ModelMultipleChoiceField(queryset = Category.objects.all(), widget = forms.SelectMultiple(attrs = {'class':'form-control', 'placeholder':'Categorias'}))
Model
class Property(models.Model):
class Meta:
verbose_name_plural = "properties"
name = models.CharField(max_length = 200)
description = models.TextField(max_length = 500)
address = models.CharField(max_length = 200)
sqft = models.DecimalField(max_digits = 6, decimal_places = 2)
beds = models.IntegerField()
baths = models.IntegerField()
status = models.BooleanField(default = True)
price = models.DecimalField(max_digits = 6, decimal_places = 2)
likes = models.IntegerField()
categories = models.ManyToManyField(Category, null = True, blank = True)
currency_type = models.ForeignKey(Currency)
activity_type = models.ForeignKey(Activity)
creation_date = models.DateTimeField(auto_now_add = True)
edition_date = models.DateTimeField(default = timezone.now)
def __unicode__(self):
return self.name
View
def search_properties(request):
if request.method == 'POST':
form = SearchPropertyForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
activity = form.cleaned_data['activity']
currency = form.cleaned_data['currency']
price_from = form.cleaned_data['price_from']
price_to = form.cleaned_data['price_to']
categories = form.cleaned_data['categories']
properties = Property.objects.filter(name__icontains = name).filter(
activity_type__exact = int(activity)).filter(
currency_type__exact = int(currency)).filter(
price_from__gte = int(price_from)).filter(
price_from__lte = int(price_to)).filter(
categories__exact = int(categories))
return render(request, 'properties/search_properties.html', {
'properties': properties,
'media_url': settings.MEDIA_URL,
'form':form,
})
else:
form = SearchPropertyForm()
properties = Property.objects.filter(status = True)
return render(request, 'properties/search_properties.html', {
'properties': properties,
'media_url': settings.MEDIA_URL,
'form':form,
})
You can use the Q object in case you are trying to do a or query.
https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects
so your code could be like this.
from django.db.models import Q
properties = Property.objects.filter(Q(name__icontains = name)|
Q(activity_type__exact = int(activity))|
Q(currency_type__exact = int(currency))|
Q(price_from__gte = int(price_from))|
Q(price_from__lte = int(price_to))|
Q(categories__exact = int(categories))
In the Q object | (pipe) represents an or query and & represents an and query.
So this will return if any of the query is matched.
For the forms section I use Modelform like the following which automatically takes the foreign keys and the multiselects.
class SearchPropertyForm(forms.ModelForm):
class Meta:
model = Property
fields = ('name', 'activity','currency', 'price_form')
You can use Q objects, or simply use django-filter:
Django-filter provides a simple way to filter down a queryset based on parameters a user provides.
Once you have it installed, create a forms.py (since a filter is a type of form), and inside it add the following:
import django_filters
from .models import Property
class PropertyFilter(django_filters.FilterSet):
class Meta:
model = Property
Then, you have to wire it up from your views.py:
from .forms import PropertyFilter
def search(request):
f = PropertyFilter(request.GET, Property.objects.all())
return render(request, 'search.html', {'filter': f})
Your template search.html:
<form method="GET" role="form">
{{ f.form }}
<input type="submit" />
</form>
{% if f|length %}
{% for obj in f %}
{{ obj }}
{% endfor %}
{% else %}
Sorry, no results for your search criteria
{% endif %}

File upload form in Django

I'm trying to create a simple upload form for my project in Django 1.5 an Python 2.7.
This is my File class:
class File(models.Model):
middleschool = 'MS'
highschool = 'HS'
university = 'U'
blank = '-'
school_choices = ((middleschool, 'Middle School'), (highschool, 'High school'), (university, 'University'), (blank, 'Not defined'),)
name = models.CharField(max_length = 30, primary_key=True, blank=False, null=False)
description = models.CharField(max_length = 140, blank=False, null=False)
school = models.CharField(max_length = 30, choices = school_choices, default = blank)
subject = models.ForeignKey(Subject)
user = models.ForeignKey(User)
rating = models.DecimalField(max_digits=2, decimal_places=0, default = 0)
price = models.DecimalField(max_digits=2, decimal_places=1, default = 0, blank=True, null=True)
file = models.FileField(upload_to= "/file/")
this is the form:
class UploadFileForm(forms.Form):
middleschool = 'MS'
highschool = 'HS'
university = 'U'
blank = '-'
school_choices = ((middleschool, 'Middle School'), (highschool, 'High school'), (university, 'University'), (blank, 'Not defined'),)
name = forms.CharField(max_length = 30, required = True)
file = forms.FileField()
description = forms.CharField(max_length = 140, required = False, label='Breif description of the files content')
school = forms.ChoiceField(choices = school_choices, required=False, label='What level is the material that are you uploading?', initial = blank)
subject = forms.ModelChoiceField(queryset=Subject.objects.order_by('?'), required=False, label='What subject this file is about?')
price = forms.IntegerField(required=False)
this is the view:
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
new_file = File(file = request.FILE['file'])
cd = form.cleaned_data
new_file.name = cd['name']
new_file.description = cd['description']
new_file.school = cd['school']
new_file.subject = cd['subject']
new_file.price = cd['price']
new_file.rating = '0.0'
new_file.user = request.user
new_file.save()
form = Search()
return render(request, 'home.html', {'form': form, 'request': request})
else:
form = UploadFileForm()
return render(request, 'upload.html', {'form': form, 'request': request})
and this is the relative HTML
{% if request.user.is_authenticated %}
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Upload">
<input type="reset" value="Reset">
</form>
{% else %}
<p>You must be logged to upload a file</p>
{% endif %}
My app path is: C:/Users/User/Desktop/site_is/app_is/ and I want hose files saved in the folder: C:/Users/User/Desktop/site_is/app_is/static/file/. In my Setting.py I set:
MEDIA_ROOT = 'C:/Users/User/Desktop/site_is/app_is/static/file/'
MEDIA_URL = '/file/'
STATIC_ROOT = 'C:/Users/User/Desktop/site_is/app_is/static/'
STATIC_URL = '/static/'
The problem is: when i select the file and hit the upload button the FileField empties itself and the form raise an error since that field is required.
I fear I'm doing something wrong with the media/static paths in the Setting.py because the view syntax it's the same as the one in the Django docmentation but I really don't know how to solve this problem.
You should specify enctype in form tag to allow file upload.
<form action="" method="post" enctype="multipart/form-data">

Categories