I am using Class Based Views in django... Then my model is:
models.py
class Survey(Base):
description = models.CharField('Description', max_length=50, unique=True)
item1 = models.CharField('Item1', max_length=50)
item2 = models.CharField('Item2', max_length=50)
...
class Meta:
verbose_name = 'Survey'
def __str__(self):
return self.description
Now I am reading database data for fill in select and works fine.
How I get this select item for fill table fields?
info.html
<div class="col-12">
<div class="card card-chart">
<div class="card-header ">
<div class="row">
<div class="col-sm-4 text-left">
<h2 class="card-title">Informations</h2>
<option selected>choose a option</option>
{% for s in survey %}
<option>{{s.description}}</option>
{% endfor %}
</select>
</div>
<!-- of course, in this moment variable [s] not exist -->
<div class="col-sm-8 text-right">
<table class="table">
<tbody>
<tr>
<td>item 1</td>
<td>item 2</td>
</tr>
<tr>
<!-- want fill this fields with select item above-->
<td>{{s.item1}}</td>
<td>{{s.item2}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
views.py
from django.views.generic import TemplateView
from .models import Survey
class IndexView(TemplateView):
template_name = 'index.html'
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['survey'] = Survey.objects.all()
return context
You should add value attribute to the options that you create in HTML.
If you want to use the value somewhere else you can follow the procedure below:
You get the Select element by giving a specific id to it and retrieve its value.
You can get the element by using var el = document.getElementById("#id_of_select").
By using el.value you can get the selected value for select.
Related
I would like when I add a file in the table it automatically adds a number from 1. I cannot use the primary key in the model because I already use it. anyone have a solution. thank you.
====Page.html====
<h5>Documents</h5>
</div>
<div class="row">
<div class="col-md">
<div class="card card-body">
<table class="table table-sm">
<tr>
<th>#</th>
<th>Nom du fichier</th>
<th>Fichier</th>
<th></th>
</tr>
{% for d in document %}
<tr>
<td>{{d.Number}}</td>
<td>{{d.Description}}</td>
<td><a download href="{{d.Fichier.url}}">{{d.Fichier}}</a></td>
<td><a class="btn btn-outline-danger" href="{% url 'supprimerdocument' d.id %}">Supprimer</a>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
====view.py====
# Button to add docs
#login_required(login_url='loginpage')
#allowed_users(allowed_roles=['admin', 'livraison'])
def createDocument(request):
forms = documentForm()
if request.method == 'POST':
forms = documentForm(request.POST, request.FILES)
if forms.is_valid():
forms.save()
return redirect('/employe')
context = {'forms':forms}
return render(request, 'accounts/document_form.html', context)
====Models.py====
class Document(models.Model):
employe = models.ForeignKey(Employe, null=True, on_delete=models.SET_NULL)
Number = models.IntegerField(default=1)
Description = models.CharField(max_length=100, null=True)
Fichier = models.FileField(upload_to='documents/')
data_created = models.DateTimeField(auto_now_add=True, null=True)
====Form.py====
class documentForm(ModelForm):
class Meta:
model = Document
fields = '__all__'
exclude = ['Number']
You can use forloop.counter in your template to access the (1-indexed) iteration of the for loop
{% for d in document %}
<tr>
<td>{{ forloop.counter }}</td>
...
</tr>
{% endfor %}
It looks like you can do an AutoField as per How do I make an auto increment integer field in Django?
But as a fallback: You could just do an Integer field and override the modelform's .save() method and auto fill it like self.some_field = Document.objects.all().count()
..if you do that, best to add a flag for if it's an edit form or not.. I believe you can do that with if self.instance: if true, is edit form
use callable default
def get_next_number():
max_val = Document.objects.aggregate(models.Max('Number'))['Number__max'] or 0
return max_val + 1
class Document(models.Model):
Number = models.IntegerField(default=get_next_number)
...
I am tasked with making a shopping crud project with models Products,categories,sub_categories,size,colors. Categories and subcategories are connected via foreign keys and I am using SERAILIZERS.the problem is that when I try to insert the data into sub Categories it doesnt come in both the database and the webpage
I also tried value = "{{c.category_name}}" as well in select dropdown as well
below are the models
class Categories(models.Model):
category_name = models.CharField(max_length=10)
category_description = models.CharField(max_length=10)
isactive = models.BooleanField(default=True)
class SUBCategories(models.Model):
category_name = models.ForeignKey(Categories,on_delete=models.CASCADE)
sub_categories_name = models.CharField(max_length=20)
sub_categories_description = models.CharField(max_length=20)
isactive = models.BooleanField(default=True)
show and insert function of sub_categories
def show_sub_categories(request):
showsubcategories = SUBCategories.objects.filter(isactive=True)
#print(showsubcategories)
serializer = SUBCategoriesSerializer(showsubcategories,many=True)
print(serializer.data)
return render(request,'polls/show_sub_categories.html',{"data":serializer.data})
def insert_sub_categories(request):
if request.method == "POST":
insertsubcategories = {}
insertsubcategories['sub_categories_name']=request.POST.get('sub_categories_name')
insertsubcategories['sub_categories_description']=request.POST.get('sub_categories_description')
form = SUBCategoriesSerializer(data=insertsubcategories)
if form.is_valid():
form.save()
print("hkjk",form.data)
messages.success(request,'Record Updated Successfully...!:)')
print(form.errors)
return redirect('sub_categories:show_sub_categories')
else:
print(form.errors)
else:
insertsubcategories = {}
form = SUBCategoriesSerializer(data=insertsubcategories)
category_dict = Categories.objects.filter(isactive=True)
category = CategoriesSerializer(category_dict,many=True)
hm = {'context': category.data}
if form.is_valid():
print(form.errors)
return render(request,'polls/insert_sub_categories.html',hm)
html of the insert page and show page respectively
<td>category name</td>
<td>
<select name="category_name" id="">
{% for c in context %}
<option value="{{c.id}}">{{c.category_name}}</option>
{% endfor %}
</select>
</td>
</tr>
<tr>
<td>sub categories Name</td>
<td>
<input type="text" name="sub_categories_name" placeholder="sub categories ">
</td>
</tr>
<tr>
<td>Sub categories Description</td>
<td>
<textarea name="sub_categories_description" id="" cols="30" rows="10">
</textarea>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Insert" />
</td>
<td>
{% if messages %}
{% for mess in messages %}
<b style="color:green;">{{mess}}</b>
{% endfor %}
{% endif %}
</td>
<tbody>
<tr>
<td><b>{{result.sub_categories_name}}</b></td>
<td><b>{{result.sub_categories_description}}</b></td>
<td style="position: relative;left:50px;">
<a href="sub_categories/edit_sub_categories/{{result.id}}">
<button class="btn btn-primary">
<i class="fa-solid fa-pen-to-square">EDIT</i>
</button>
</a>
</td>
<td>
<a href="{% url 'sub_categories:delete_sub_categories' result.id %}" onclick="return confirm('Are You Sure you want to delete?')">
<button class="btn btn-danger">
<i class="fa-solid fa-trash">DELETE</i>
</button>
</a>
</td>
</tr>
</tbody>
categories and sub categories serializer
class CategoriesSerializer(serializers.ModelSerializer):
class Meta:
model = Categories
fields = "__all__"
extra_kwargs = {'category_name': {'required': False}}
class SUBCategoriesSerializer(serializers.ModelSerializer):
class Meta:
model = SUBCategories
fields = "__all__"
where am I going wrong in the code?
Try this out and let me know, a few changes you'd require
def insert_sub_categories(request):
if request.method == "POST":
form = SUBCategoriesSerializer(data=request.POST)
if form.is_valid():
form.save()
messages.success(request, "Record Updated Successfully...!:)")
return redirect("sub_categories:show_sub_categories")
category_dict = Categories.objects.filter(isactive=True)
category = CategoriesSerializer(category_dict, many=True)
hm = {"context": category.data}
return render(request, "polls/insert_sub_categories.html", hm)
Form part
<form method="POST">
{% csrf_token %}
<table>
<thead>
<tr>
<td>category name</td>
<td>
<select name="category_name" id="">
{% for c in context %}
<option value="{{c.id}}">{{c.category_name}}</option>
{% endfor %}
</select>
</td>
</tr>
<tr>
<td>sub categories Name</td>
<td>
<input type="text" name="sub_categories_name" placeholder="sub categories ">
</td>
</tr>
<tr>
<td>Sub categories Description</td>
<td>
<textarea name="sub_categories_description" id="" cols="30" rows="10">
</textarea>
</td>
</tr>
<tr>
<td>Active</td>
<td>
<input type="checkbox" name="isactive" value="true" checked>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Insert" />
</td>
<td>
{% if messages %}
{% for mess in messages %}
<b style="color:green;">{{mess}}</b>
{% endfor %}
{% endif %}
</td>
</tr>
</thead>
</table>
<button class="btn btn-success">Go To Home</button>
</form>
model
class SUBCategories(models.Model):
category_name = models.ForeignKey(Categories, on_delete=models.CASCADE)
sub_categories_name = models.CharField(max_length=20)
sub_categories_description = models.CharField(max_length=20)
isactive = models.BooleanField(default=True)
def __str__(self):
return self.category_name.category_name
This error occurs because there is a chance in your function view, that it does not return proper Response or Redirect object. If you send POST request, but the form is not valid, then it will not return anything.
def insert_sub_categories(request):
if request.method == "POST":
...
if form.is_valid():
...
return redirect('sub_categories:show_sub_categories')
else:
print(form.errors)
# HERE YOU MISS REDIRECT/RENDER
else:
...
return render(request,'polls/insert_sub_categories.html',hm)
Also you don't pass SUBCategories.category_name to your serializer. It's required field, so it will never be valid without it. You may try form = SUBCategoriesSerializer(request.POST) instead of adding values one by one.
I am using django filter package to filter data based on start,
end date and class of dues fields defined in my models. The problem is If I select only class_of_fields data is filtered but when I
select start and end_date along with class_of_dues no data is filtered below are my codes
models.py
class DuesLevy(models.Model):
class_of_dues = models.CharField(max_length=30, default=options.CHOOSE, choices=options.CLASS_OF_DUES, blank=True)
payment_circle = models.CharField(max_length=30, default=options.CHOOSE, choices=options.PAYMENT_CIRCLE)
payment_option = models.CharField(max_length=30, default=options.CHOOSE, choices=options.PAYMENT_OPTION)
amount = models.DecimalField(max_digits=8, decimal_places=2)
transaction_id = models.CharField(max_length=30, null=True, blank=True, editable=False, default=my_rand)
payment_channel = models.CharField(max_length=30, default=options.CHOOSE, choices=options.PAYMENT_CHANNEL_TYPE)
payment_date = models.DateField()
start_date = models.DateField()
end_date = models.DateField()
date_recorded = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
description = models.TextField(blank=True, null=True)
def __str__(self):
return self.amount
filter.py
from .models import DuesLevy, User
from django_filters import widgets
import django_filters
from django import forms
from django_select2 import forms as s2forms
from backend import options
class DuesFilter(django_filters.FilterSet):
class_of_dues = django_filters.CharFilter(
widget=s2forms.Select2Widget(choices=options.CLASS_OF_DUES,
attrs={'class':'form-control'}))
start_date = django_filters.DateFilter(field_name='payment_date',
widget=forms.DateInput(attrs={'class':'form-control', 'type':'date'}), lookup_expr='lt',label='Start Date')
end_date = django_filters.DateFilter(field_name='payment_date',
widget=forms.DateInput(attrs={'class':'form-control', 'type':'date'}), lookup_expr='gt',label='End Date')
user = django_filters.ModelChoiceFilter(queryset=User.objects.all(),
widget=s2forms.ModelSelect2Widget(
attrs={'class': 'form-control'},
model=User,
search_fields=['member_id__icontains'],
))
class Meta():
model = DuesLevy
fields = ('class_of_dues', 'start_date', 'end_date')
views.py
class ListMemberDues(LoginRequiredMixin, View):
login_url = '/backoffice/'
def get(self, request):
queryset = DuesLevy.objects.filter(user=request.user)
query_filter = DuesFilter(request.GET, queryset)
context = {
'form':query_filter.form,
'query':query_filter,
}
return render(request, 'dashboard/list-member-dues.html', context)
templates.html
<form class="form-inline d-flex justify-content-around">
<div class="col-sm-3 my-1">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">Class Of Dues</div>
</div>
{{ form.class_of_dues }}
</div>
</div>
<div class="col-sm-3 my-1">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">Start Date</div>
</div>
{{ form.start_date }}
</div>
</div>
<div class="col-sm-3 my-1">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">End Date</div>
</div>
{{ form.end_date }}
</div>
</div>
<button type="submit" class="btn btn-success">Filter</button>
{% csrf_token %}
</form>
{% if request.user %}
<div class="row p-3 bg-light">
<div class="col-md-4">
<h3>Account Details</h3>
<h4>{{ request.user.first_name }} {{ single.user.last_name }}</h4>
<h4>Phone {{ single.user.phone1 }}</h4>
<h4>LCDA: {{ request.user.lcda }}</h4>
<h4>Zone: {{ request.user.zone }}</h4>
<h4>Area: {{ request.user.area }}</h4>
</div>
<div class="col-md-4">
<img style="width: 200px; height: auto;" src="{{ request.user.additionalprofile.get_image_url }}" alt="">
</div>
</div>
{% endif %}
<table class="table">
<tr>
<th>Payment Date</th>
<th>Categories</th>
<th>Amount</th>
<th>Channel</th>
<th>Transaction ID</th>
</tr>
{% if query %}
{% for q in query.qs %}
<tr>
<td>{{ q.date_recorded }}</td>
<td>{{ q.class_of_dues }}</td>
<td>₦{{ q.amount }}</td>
<td>{{ q.payment_channel }}</td>
<td>{{ q.transaction_id }}</td>
</tr>
{% endfor %}
{% endif %}
</table>
It looks like the corresponding lines in the DuesFilter class are pointing to the wrong fields. The two lines in question should be:
start_date = django_filters.DateFilter(
field_name='start_date', # not payment_date
widget=forms.DateInput(attrs={'class':'form-control', 'type':'date'}),
lookup_expr='gt', # Include dates after the start date (exclusive)
label='Start Date')
end_date = django_filters.DateFilter(
field_name='end_date', # not payment_date
widget=forms.DateInput(attrs={'class':'form-control', 'type':'date'}),
lookup_expr='lt', # Include dates before the end date (exclusive)
label='End Date')
I'm going out on a limb to guess you really wanted to include dates between start_date and end_date and have updated the lookup_expr to reflect that.
So, I'm developing a web application to control the inventory on my company in Django (yes, I know there are plenty open source alternatives out there, we are in fact using fusioninventory right now, but I'm not the boss...).
The thing is, one computer can have multiple users, and so I implemented it on the model as a ManyToMany field. Here is the relevant code for the model, filter and html template. Note that I'm using django_filters lib to implement the search filters and widget_tweaks to give some style to the form.
models.py
class Computer(models.Model):
tag = models.CharField(max_length = 20, unique=True)
users = models.ManyToManyField(User, blank = True, default = 'No_User',)
TYPE = (
('DESK','Desktop'),
('LAP','Laptop'),
)
computertype = models.CharField(
max_length = 4,
choices = TYPE,
)
STATUS = (
('OK','OK'),
('Broken','Broken'),
('Unusable','Unusable'),
)
computerstatus = models.CharField(
max_length = 12,
choices = STATUS,
default = 'OK',
)
model = models.CharField(max_length = 36)
serial = models.CharField(max_length = 36)
buy_date = models.DateField()
modified_date = models.DateTimeField(auto_now=True)
def __str__(self):
return self.tag
def get_absolute_url(self):
return reverse('computer_detail', args=[str(self.id)])
filters.py
class UserFilter(django_filters.FilterSet):
class Meta:
model = User
fields = {
'username': ['contains'],
}
class ComputerFilter(django_filters.FilterSet):
tag = django_filters.CharFilter(lookup_expr="icontains",label = 'Etiqueta',)
computertype = django_filters.ChoiceFilter(choices = Computer.TYPE, lookup_expr="icontains",label = 'Tipo',)
computerstatus = django_filters.ChoiceFilter(choices = Computer.STATUS, lookup_expr="icontains",label = 'Estado',)
**users = UserFilter()**
from = django_filters.DateFilter(field_name='buy_date', lookup_expr="gt", label='Adquiridos desde',)
to = django_filters.DateFilter(field_name='buy_date', lookup_expr="lt", label='Hasta',)
class Meta:
model = Computer
fields = ['tag','users','computertype','computerstatus',]
computer_list.html
<form method="get">
<div class="well">
<center><h4><b>Filtro</b></h4></center>
<center><table>
<tr>
<td><div class"form-group">
{{ filter.form.tag.label_tag}}
{% render_field filter.form.tag class="form-control" %}
</div></td>
<td> </td>
<td></td>
</tr>
<tr>
<td><div class"form-group">
{{ filter.form.computertype.label_tag}}
{% render_field filter.form.computertype class="form-control" %}
</div></td>
<td> </td>
<td><div class"form-group">
{{ filter.form.computerstatus.label_tag}}
{% render_field filter.form.computerstatus class="form-control" %}
</div></td>
</tr>
<tr>
<td><div class"form-group">
{{ filter.form.desde.label_tag}}
{% render_field filter.form.desde class="form-control" type="date" %}
</div></td>
<td> </td>
<td><div class"form-group">
{{ filter.form.hasta.label_tag}}
{% render_field filter.form.hasta class="form-control" type="date" %}
</div></td>
</tr>
<tr>
<td><div class"form-control" input type ="text">
{{ filter.form.users.label_tag}}
{% render_field filter.form.users class="form-control" %}
</div></td>
<td></td>
</tr>
</table></center>
<div>
<p> </p><center><button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-search"></span> Buscar
</button></center>
</div>
</div>
</form>
You can see the full code on github
Right now the filter form looks like this:
See the Image
Question: Is there an easy way so that the form field would accept input like:
user1, user2, ... , usern instead of selecting the users?
Bonus: Is there a way to implement it so that it also has autocomplete (I write for example, - user1, use - and it shows me all the users begining with "use" so I can click it and it gets added to the field.
Thank you for your time.
you can user ModelMultipleChoiceField
users = ModelMultipleChoiceField()
I am looking to create a very simple form with several drop down fields allowing users to query a database of restaurants I have created (I would like to use the fields 'food', 'city' and 'average rating'). Whilst I have found an approach to do this using separate html pages (Django form to query database (models)) I would like to implement this on one page (restaurants.html).
I am using Python 3.1.0, Django 2.0.1 and Bootstrap 4.0.
Appreciate all your help.
My models.pyis as follows:
from django.db import models
import numpy as np
# Create your models here.
class Restaurant(models.Model):
name = models.CharField(max_length=100, null=False)
desc = models.CharField(max_length=100)
web = models.CharField(max_length=100)
phone = models.CharField(max_length=40)
address = models.CharField(max_length=100)
post_code = models.CharField(max_length=20)
picture = models.ImageField(upload_to='images/restaurants', null=True)
map = models.ImageField(upload_to='images/restaurants', null=True)
FOOD = ((1,'English'),
(2,'French'),
(3,'American'),
(4,'Indian'),
(5, 'Undefined'))
food = models.IntegerField(choices=FOOD, default=5)
CITY = ((1,'London'),
(2,'Paris'))
city = models.IntegerField(choices=CITY, default=1)
STARS = ((1,'One'),
(2,'Two'),
(3,'Three'),
(4,'Four'),)
CB_rating = models.IntegerField(choices=STARS, default=4)
def average_rating(self):
all_ratings = map(lambda x: x.rating, self.review_set.all())
return np.mean(all_ratings)
def __str__(self):
return self.name
views.py:
from django.shortcuts import get_object_or_404, render
from .models import Review, Restaurant
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from .forms import ReviewForm
import datetime
def review_list(request):
latest_review_list = Review.objects.order_by('-pub_date')[:9]
context = {'latest_review_list':latest_review_list}
return render(request, 'review_list.html', context)
def review_detail(request, review_id):
review = get_object_or_404(Review, pk=review_id)
return render(request, 'review_detail.html', {'review': review})
def restaurant_list(request):
restaurant_list = Restaurant.objects.order_by('-name')
context = {'restaurant_list':restaurant_list}
return render(request, 'restaurants.html', context)
def restaurant_detail(request, restaurant_id):
restaurant = get_object_or_404(Restaurant, pk=restaurant_id)
return render(request, 'restaurant_detail.html', 'restaurant':restaurant})
def user_review_list(request, username=None):
if not username:
username = request.user.username
latest_review_list = Review.objects.filter(user_name=username).order_by('-pub_date')
context = {'latest_review_list':latest_review_list, 'username':username}
return render(request, 'user_review_list.html', context)
restaurants.html:
{% extends 'base.html' %}
{% load staticfiles %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-md-4 col-sm-offset-4" style="text-align: center">
<h3>Search Criteria</h3>
<hr>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-4 col-sm-offset-4" style="text-align: center">
<form method="get" action="/search/">
Search Restaurants:<input type="text" name="q" id="id_q" value="{{ query }}"/>
<input type="submit" value="Search" />
</form>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-4 col-sm-offset-4" style="text-align: center">
<h3>Search Results</h3>
<hr>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div>
{% if restaurant_list %}
<div class="container">
<div class="table-responsive">
<table class="table table-bordered table-hover" style="text-align: center;">
<caption class="text-center">A list of restaurants based on your search criteria above.</caption>
<thead>
<th class="col-xs-2">Name</th>
<th class="col-xs-6">Description</th>
<th class="col-xs-1" style="text-align: center">Food Type</th>
</thead>
<tbody>
{% for restaurant in restaurant_list %}
<tr>
<td style="text-align: left;"><strong>{{ restaurant.name }}</strong></td>
<td style="text-align: left;">{{ restaurant.desc }}</td>
<td style="text-align: center;">{{ restaurant.food }}</td>
{% endfor %}
</tr>
</tbody>
</table>
</div>
</div>
{% else %}
<h3>No restaurants match your search criteria.</h3>
{% endif %}
</div>
</div>
</div>
{% endblock %}