ValueError: while trying to use the crispy forms - python

I am trying to make use of the crispy forms to display the form for inserting the data. I have a model as:
class Athlete(models.Model):
athlete_name=models.CharField(max_length=50)
GENDER_CHOICES=(
('M','Male'),
('F','Female'),
('O','Others')
)
gender=models.CharField(choices=GENDER_CHOICES,max_length=100)
age=models.IntegerField()
athlete_category=models.ForeignKey(Category,on_delete=models.CASCADE)
image=models.FileField(upload_to='static/athlete_img', null=True)
COUNTRY_CHOICES=(
('np','nepal'),
('in','india'),
('uk','united kingdom'),
('sp','spain'),
('ch','china')
)
medals=models.IntegerField
country=models.CharField(choices=COUNTRY_CHOICES,max_length=100)
def __str__(self):
return self.athlete_name
In the forms.py...I have modelform as:
class AthleteForm(ModelForm):
class Meta:
model:Athlete
fields='__all__'
In my views.py I have the following function:
def add_athlete(request):
if request.method == 'POST':
form = AthleteForm(request.POST, request.FILES)
if form.is_valid():
form.save()
messages.add_message(request, messages.SUCCESS,
'Athlete added sucessfully')
return redirect('/admin/athletes')
else:
messages.add_message(request, messages.ERROR,
'Enter the appropriate values')
return render(request, 'forgame/addathletes.html', {
'form': form
})
context = {
'form': AthleteForm
}
return render(request, 'forgame/addathletes.html', context)
Inside my templates/forgame I have created addathletes.html
{% extends 'layouts.html' %}
{% load crispy_forms_tags %}
{% block title %}
<title>Game Category</title>
{%endblock%}
{% block main_content %}
<div class="container-fluid mt-4">
<div class="d-flex justify-content-center">
<div class="col-md-6">
<h2>Add Categories Here!</h2>
{% for msg in messages %}
{% if msg.level == DEFAULT_MESSAGE_LEVELS.SUCCESS %}
<div class="alert alert-success">
{{msg}}
</div>
{%endif%}
{% if msg.level == DEFAULT_MESSAGE_LEVELS.ERROR %}
<div class="alert alert-danger">
{{msg}}
</div>
{%endif%}
{%endfor%}
<form action="" method="post" class="shadow-lg p-3">
{%csrf_token%}
{{form | crispy}}
<div class="mt-3">
<input type="submit" value="Add Category" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
{% endblock %}
My urls looks fine but I have been getting this error:
Along with this:

It should be = not : so:
class AthleteForm(ModelForm):
class Meta:
model = Athlete
fields='__all__'
I'd also recommend you to maintain gaps between template tags like it should be {% endblock %} not {%endblock%} same goes for every tag.

Related

Double post after refresh django

After I posted my comment and decided to refresh the page it adds the same comment over and over on every refresh how can I stop this?
The code for the comment review is at the far bottom in the template.html.
And the review code is under "def product_detail" in the views.py.
Can someone give me some tips so if I refresh it dosen't do another post?
template file:
{% extends "base.html" %}
{% load static %}
{% block page_header %}
<div class="container header-container">
<div class="row">
<div class="col"></div>
</div>
</div>
{% endblock %}
{% block content %}
<div class="overlay"></div>
<div class="container-fluid">
<div class="row">
<div class="col-12 col-md-6 col-lg-4 offset-lg-2">
<div class="image-container my-5">
{% if product.image %}
<a href="{{ product.image.url }}" target="_blank">
<img class="card-img-top img-fluid" src="{{ product.image.url }}" alt="{{ product.name }}">
</a>
{% else %}
<a href="">
<img class="card-img-top img-fluid" src="{{ MEDIA_URL }}noimage.png" alt="{{ product.name }}">
</a>
{% endif %}
</div>
</div>
<div class="col-12 col-md-6 col-lg-4">
<div class="product-details-container mb-5 mt-md-5">
<p class="mb-0">{{ product.name }}</p>
<p class="lead mb-0 text-left font-weight-bold">${{ product.price }}</p>
{% if product.category %}
<p class="small mt-1 mb-0">
<a class="text-muted" href="{% url 'products' %}?category={{ product.category.name }}">
<i class="fas fa-tag mr-1"></i>{{ product.category.friendly_name }}
</a>
</p>
{% endif %}
{% if product.get_rating > 0 %}
<small class="text-muted"><i class="fas fa-star mr-1"></i>{{ product.get_rating }} / 5</small>
{% else %}
<small class="text-muted">No Rating</small>
{% endif %}
{% if request.user.is_superuser %}
<small class="ml-3">
Edit |
<a class="text-danger" href="{% url 'delete_product' product.id %}">Delete</a>
</small>
{% endif %}
<p class="mt-3">{{ product.description }}</p>
<form class="form" action="{% url 'add_to_bag' product.id %}" method="POST">
{% csrf_token %}
<div class="form-row">
{% with product.has_sizes as s %}
{% if s %}
<div class="col-12">
<p><strong>Size:</strong></p>
<select class="form-control rounded-0 w-50" name="product_size" id='id_product_size'>
<option value="xs">XS</option>
<option value="s">S</option>
<option value="m" selected>M</option>
<option value="l">L</option>
<option value="xl">XL</option>
</select>
</div>
{% endif %}
<div class="col-12">
<p class="mt-3"><strong>Quantity:</strong></p>
<div class="form-group w-50">
<div class="input-group">
<div class="input-group-prepend">
<button class="decrement-qty btn btn-black rounded-0"
data-item_id="{{ product.id }}" id="decrement-qty_{{ product.id }}">
<span class="icon">
<i class="fas fa-minus"></i>
</span>
</button>
</div>
<input class="form-control qty_input" type="number"
name="quantity" value="1" min="1" max="99"
data-item_id="{{ product.id }}"
id="id_qty_{{ product.id }}">
<div class="input-group-append">
<button class="increment-qty btn btn-black rounded-0"
data-item_id="{{ product.id }}" id="increment-qty_{{ product.id }}">
<span class="icon">
<i class="fas fa-plus"></i>
</span>
</button>
</div>
</div>
</div>
</div>
<div class="col{% if s %}-12 mt-2{% endif %}">
<a href="{% url 'products' %}" class="btn btn-outline-black rounded-0 mt-5">
<span class="icon">
<i class="fas fa-chevron-left"></i>
</span>
<span class="text-uppercase">Keep Shopping</span>
</a>
<input type="submit" class="btn btn-black rounded-0 text-uppercase mt-5" value="Add to Bag">
</div>
<input type="hidden" name="redirect_url" value="{{ request.path }}">
{% endwith %}
</div>
</form>
</div>
</div>
</div>
<div class="w-full mt-6">
<h2 class="text-xl">Reviews</h2>
{% if request.user.is_authenticated %}
<form method="post" action="." class="mt-6 mb-6 p-6 bg-gray-100 rounded-xl">
{% csrf_token %}
<div>
<label>Rating</label><br>
<select class="form-control" name="rating">
<option value="1">1</option>
<option value="2">2</option>
<option value="3" selected>3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
<div class="form-group">
<label for="comment">Comment</label>
<textarea class="form-control" rows="5" id="comment" name="content"></textarea>
</div>
<button type="submit" class="btn btn-primary mb-2">Submit</button>
</form>
{% endif %}
{% for review in reviews %}
<div class="px-4 py-6 bg-gray-100 rounded-xl mb-4">
<strong>Author:</strong> {{ review.created_by }}<br>
<strong>Rating:</strong> {{ review.rating }}/5<br>
<strong>Date:</strong> {{ review.created_at|date:"Y-m-d" }}<br>
<strong>Comment:</strong><br>
{{ review.content }}
</div>
{% endfor %}
</div>
</div>
{% endblock %}
{% block postloadjs %}
{{ block.super }}
{% include 'products/includes/quantity_input_script.html' %}
{% endblock %}
views.py:
from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.db.models.functions import Lower
from .models import Product, Category, Review
from .forms import ProductForm
# Create your views here.
def all_products(request):
""" A view to show all products, including sorting and search queries """
products = Product.objects.all()
query = None
categories = None
sort = None
direction = None
if request.GET:
if 'sort' in request.GET:
sortkey = request.GET['sort']
sort = sortkey
if sortkey == 'name':
sortkey = 'lower_name'
products = products.annotate(lower_name=Lower('name'))
if sortkey == 'category':
sortkey = 'category__name'
if 'direction' in request.GET:
direction = request.GET['direction']
if direction == 'desc':
sortkey = f'-{sortkey}'
products = products.order_by(sortkey)
if 'category' in request.GET:
categories = request.GET['category'].split(',')
products = products.filter(category__name__in=categories)
categories = Category.objects.filter(name__in=categories)
if 'q' in request.GET:
query = request.GET['q']
if not query:
messages.error(request, "You didn't enter any search criteria!")
return redirect(reverse('products'))
queries = Q(name__icontains=query) | Q(description__icontains=query)
products = products.filter(queries)
current_sorting = f'{sort}_{direction}'
context = {
'products': products,
'search_term': query,
'current_categories': categories,
'current_sorting': current_sorting,
}
return render(request, 'products/products.html', context)
def product_detail(request, product_id):
""" A view to show individual product details """
product = get_object_or_404(Product, pk=product_id)
if request.method == 'POST':
rating = request.POST.get('rating', 3)
content = request.POST.get('content', '')
review = Review.objects.create(
product=product,
rating=rating,
content=content,
created_by=request.user
)
reviews = Review.objects.filter(product=product)
context = {
'product': product,
'reviews': reviews
}
return render(request, 'products/product_detail.html', context)
#login_required
def add_product(request):
""" Add a product to the store """
if not request.user.is_superuser:
messages.error(request, 'Sorry, only store owners can do that.')
return redirect(reverse('home'))
if request.method == 'POST':
form = ProductForm(request.POST, request.FILES)
if form.is_valid():
product = form.save()
messages.success(request, 'Successfully added product!')
return redirect(reverse('product_detail', args=[product.id]))
else:
messages.error(request, 'Failed to add product. Please ensure the form is valid.')
else:
form = ProductForm()
template = 'products/add_product.html'
context = {
'form': form,
}
return render(request, template, context)
#login_required
def edit_product(request, product_id):
""" Edit a product in the store """
if not request.user.is_superuser:
messages.error(request, 'Sorry, only store owners can do that.')
return redirect(reverse('home'))
product = get_object_or_404(Product, pk=product_id)
if request.method == 'POST':
form = ProductForm(request.POST, request.FILES, instance=product)
if form.is_valid():
form.save()
messages.success(request, 'Successfully updated product!')
return redirect(reverse('product_detail', args=[product.id]))
else:
messages.error(request, 'Failed to update product. Please ensure the form is valid.')
else:
form = ProductForm(instance=product)
messages.info(request, f'You are editing {product.name}')
template = 'products/edit_product.html'
context = {
'form': form,
'product': product,
}
return render(request, template, context)
#login_required
def delete_product(request, product_id):
""" Delete a product from the store """
if not request.user.is_superuser:
messages.error(request, 'Sorry, only store owners can do that.')
return redirect(reverse('home'))
product = get_object_or_404(Product, pk=product_id)
product.delete()
messages.success(request, 'Product deleted!')
return redirect(reverse('products'))
You should implement the Post/Redirect/Get architectural pattern [wiki], and thus return a redirect such that the browser will make a GET request next, and thus prevent making another POST request when refreshing the page:
def product_detail(request, product_id):
product = get_object_or_404(Product, pk=product_id)
if request.method == 'POST':
rating = request.POST.get('rating', 3)
content = request.POST.get('content', '')
Review.objects.create(
product=product,
rating=rating,
content=content,
created_by=request.user
)
# redirect to the same page 🖟
return redirect('product_detail', product_id=product_id)
reviews = Review.objects.filter(product=product)
context = {
'product': product,
'reviews': reviews
}
return render(request, 'products/product_detail.html', context)

Django display data from two different models

I have two seperated models. One with two text fields and one for multiple images. Now I want to display the entire data in one html div. What do I have to change in the projects view and in projects.html?
models.py
class Project(models.Model):
title = models.CharField(max_length=200)
describtion = models.TextField(null=True, blank=True)
class ProjectImage(models.Model):
project = models.ForeignKey(Project, on_delete=models.CASCADE)
image = models.FileField(upload_to="products/")
forms.py
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ['title', 'describtion']
class ProjectImageForm(forms.ModelForm):
class Meta:
model = ProjectImage
fields = ['image']
widgets = {
'image': ClearableFileInput(attrs={'multiple': True}),
}
views.py
def createProject(request):
form = ProjectForm()
form2 = ProjectImageForm()
if request.method == 'POST':
form = ProjectForm(request.POST)
form2 = ProjectImageForm(request.POST, request.FILES)
images = request.FILES.getlist('image')
if form.is_valid() and form2.is_valid():
title = form.cleaned_data['title']
describ = form.cleaned_data['describtion']
project_instance = Project.objects.create(
title=title, describtion=describ)
for i in images:
ProjectImage.objects.create(project=project_instance, image=i)
context = {'form': form, 'form2': form2}
return render(request, 'projects/project_form.html', context)
def projects(request):
projects = Project.objects.all()
context = {"projects":projects}
return render(request, 'projects/projects.html', context)
projects.html
{% for project in projects %}
<div class="column">
<div class="card project">
<img class="project__thumbnail" src="{{project.image.url}}" alt="project thumbnail" />
<div class="card__body">
<h3>{{project.title}}</h3>
<h2>{{project.describtion}}</h2>
</div>
</a>
</div>
</div>
{% endfor %}
You don't need to change anything.
You should be able to access the reverse with project.project_image_set attribute in the template:
<div class="card__body"
<h3>{{project.title}}</h3>
<h2>{{project.describtion}}</h2>
{% for image in project.project_image_set.all %}
{{ image.image }}
{% endfor %}
</div>
Docs: https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_one/
I don't really understand the question here but i see a problem in your template considering you are using foreign key in ProjectImage. And update the question
{% for project in projects %}
<div class="column">
<div class="card project">
{% for j in project.projectimage_set.all %}
<img class="project__thumbnail" src="{{j.image.url}}" alt="project thumbnail" />
{% endfor %}
<div class="card__body">
<h3>{{project.title}}</h3>
<h2>{{project.describtion}}</h2>
</div>
</a>
</div>
</div>
{% endfor %}
I would change FileField to ImageField and add function:
#property
def get_photo_url(self):
if self.image and hasattr(self.image, 'url'):
return self.image.url
else:
return ''
If createProject function works( I would rename it to create_project) then in projects.html:
{% for project in projects %}
<div class="column">
<div class="card project">
<div class="card__body">
<h3>{{project.title}}</h3>
<h2>{{project.describtion}}</h2>
{% for img in project.projectimage_set.all %}
<img class="project__thumbnail" src="{{img.get_photo_url}}" alt="project thumbnail" />
{% endfor %}
</div>
</a>
</div>
</div>
{% endfor %}

Django initial_forms.is_valid() returns false

My goal is to edit/update existing data. I am able to display existing data and add new data but not edit data. My model are Recipe and Ingredient. I am using modelformset_factory to add ingredients to recipe.
Here is the forms.py:
class RecipeModelForm(forms.ModelForm):
class Meta:
model = Recipe
fields = ('name', )
labels = {
'name': 'Recipe Name'
}
widgets = {
'name': forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Recipe Name here'
}
)
}
IngredientFormset = modelformset_factory(
Ingredient,
fields=('name', 'amount', 'unit'),
labels={
'name': 'Ingredient Name',
'amount': 'Amount',
'unit': 'Unit'
},
extra=1,
widgets={
'name': forms.TextInput(
attrs={
'class': 'form-control',
'placeholder': 'Enter Ingredient Name here'
}
),
'amount': forms.TextInput(
attrs={
'class': 'form-control',
'placeholder': 'Enter Amount here'
}
),
'unit': forms.Select(
attrs={
'class': 'form-control',
'placeholder': 'Enter Unit here'
}
)
},
can_delete=True
)
views.py:
#login_required
def update_recipe(request, pk):
template_name = 'recipe/create_with_ingredients.html'
# template_name = 'recipe/update.html'
recipe = Recipe.objects.get(id=pk, author=request.user)
ingredients = Ingredient.objects.filter(recipe=recipe)
if request.method == 'GET':
recipeform = RecipeModelForm(instance=recipe)
formset = IngredientFormset(queryset=ingredients)
elif request.method == 'POST':
recipeform = RecipeModelForm(request.POST, instance=recipe)
formset = IngredientFormset(request.POST, queryset=ingredients)
if recipeform.is_valid(): # and formset.is_valid():
recipe = recipeform.save(commit=False)
recipe.author = request.user
recipe.save()
for form in formset.initial_forms:
print(form.is_valid())
if form.is_valid():
data = form.cleaned_data
for form in formset:
if form.is_valid():
data = form.cleaned_data
if data:
ingredient = form.save(commit=False)
ingredient.recipe = recipe
ingredient.author = request.user
ingredient.save()
return redirect('recipe:list-recipe')
context = {
'recipeform': recipeform,
'formset': formset,
}
return render(request, template_name, context)
My html template:
{% extends "recipe/base.html" %}
{% block container %}
{% if heading %}
<h3>{{heading}}</h3>
{% endif %}
<form class="form-horizontal" method="POST" action="">
{% csrf_token %}
<div class="row spacer">
<div class="col-6">
<label>{{recipeform.name.label}}</label>
</div>
<div class="col-8">
<div class="input-group">
{{recipeform.name}}
</div>
</div>
</div>
{{ formset.management_form }}
{% for form in formset %}
{% if form.subject.errors %}
<ol>
{% for error in form.subject.errors %}
<li><strong>{{ error|escape }}</strong></li>
{% endfor %}
</ol>
{% endif %}
<!-- {% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %} -->
<div class="row form-row spacer">
<table>
<div class="col-2">
<tr>
<th><label>{{form.name.label}}</label></th>
<th><label>{{form.amount.label}}</label></th>
<th><label>{{form.unit.label}}</label></th>
</tr>
</div>
<div class="col-4">
<tr>
<div class="input-group">
<td>{{form.name}}</td>
<td>{{form.amount}}</td>
<td>{{form.unit}}</td>
<div class="input-group-append">
<td><button class="btn btn-success add-form-row">+</button></td>
</div>
</tr>
</div>
</div>
</table>
</div>
{% endfor %}
<div class="row spacer">
<div class="col-4 offset-0">
<button type="submit" class="btn btn-block btn-primary">Create</button>
</div>
</div>
</form>
{% endblock %}
First I had if recipeForm.is_valid() and formset.is_valid() but this never result to True (formset fails). So, I removed second check and instead validate each form in formset. With this approach I found out that initial_forms (existing data) are not in formset. Therefore, to get initial forms I get it from formset.initial_forms this gives me forms with edited data and existing data but when I call form.is_valid() it fails. I am not sure why does initial data fail to valid when they are already in database. How can I update edited forms to existing data in database?
Try checking form validation errors first.
this answer may help you doing this,
if not, check this documentation.
Give us an additional feedback with error messages in case my solution wasn't enough.

Attribute error : 'WSGIRequest' object has no attribute 'get'

I've been working on a project lately and got the above error. It says " Error during template rendering".I have a similar model, which works perfectly fine. I've looked for similar errors but got none matching my situation. I don't know where I went wrong. It would be great if I get helpful answers.
Models.py
class ServiceTax(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="service_tax",null=True,blank=True)
name=models.CharField(max_length=100)
percent=models.FloatField(default='0')
add_amount=models.IntegerField(default='0')
def __str__(self):
return self.name
Forms.py
class ServiceTaxForm(forms.ModelForm):
class Meta:
model = ServiceTax
fields = "__all__"
widgets = {
'name' : forms.TextInput(attrs={'class': 'form-control'}),
'percent' : forms.NumberInput(attrs={'class': 'form-control','step':'0.01'}),
'add_amount' : forms.NumberInput(attrs={'class':'form-control','maxlength':5}),
}
labels={
'add_amount': "Additional Amount"
}
Views.py
def tax_form(request,id=0):
if request.method == 'GET':
if id == 0:
form = ServiceTaxForm(request)
else:
tax = ServiceTax.objects.get(pk=id)
if tax in request.user.service_tax.all():
form = ServiceTaxForm(request,instance=tax)
else:
return redirect('/revenue/tax')
return render(request,'tax-form.html',{'form':form})
else:
if id==0:
form = ServiceTaxForm(request,request.POST)
if form.is_valid():
name = form.cleaned_data["name"]
percent = form.cleaned_data["percent"]
add_amount = form.cleaned_data["add_amount"]
t = AnnualTax(
name=name,
percent=percent,
add_amount=add_amount,
)
t.save()
request.user.service_tax.add(t)
else:
tax = ServiceTax.objects.get(pk=id)
if tax in request.user.service_tax.all():
form = ServiceTaxForm(request,request.POST,instance=tax)
if form.is_valid():
name = form.cleaned_data["name"]
percent = form.cleaned_data["percent"]
add_amount = form.cleaned_data["add_amount"]
tax_obj = ServiceTax.objects.get(pk=id)
tax_obj.name = name
tax_obj.percent = percent
tax_obj.add_amount = add_amount
tax_obj.save()
return redirect('/revenue/tax')
tax-form.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<i class="fa fa-chevron-circle-left fa-3x m-2"></i>
<div class="content">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-header">
<h4 class="card-title">Add Service Tax</h4>
</div>
<div class="card-body">
<form action="" method="POST" autocomplete="off">
{% csrf_token %}
<div class="row">
<div class="col-md-4 pr-1">
<div class="form-group">
{{ form.name | as_crispy_field}}
</div>
</div>
<div class="col-md-4 pr-1">
<div class="form-group">
{{ form.percent | as_crispy_field}}
</div>
</div>
<div class="col-md-4 pr-1">
<div class="form-group">
{{ form.add_amount | as_crispy_field}}
</div>
</div>
</div>
<button type="submit" class="btn btn-success btn-fill pull-right">
{% if request.get_full_path == '/income/tax/add/' %}
Add Tax
{% else %}
Update
{% endif %}
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
You should retrieve your forms passing request.METHOD, not just request
As an example this piece of code form = ServiceTaxForm(request) should be form = ServiceTaxForm(request.POST)

saving multiple data like checkbox at once in django

I am working in ang django project onlinevoting. In my template I use
looping to loop all the positions and also the candidates. I have trouble in saving many data at once in one attribute for example in my model I have:
class Vote(models.Model):
candidate_id = models.ForeignKey('Candidate', blank=True, null=True)
election_id = models.ForeignKey('Election', blank=True, null=True)
user_id = models.ForeignKey('User', blank=True, null=True)
def __str__(self):
return "%s %s" % (user_id.first_name, election_id.year)
and in my template vote.html:
<form method="POST" class="form-horizontal" role="form">
{% if success %}
<div class="alert alert-success">
×
<strong>Success!</strong> {{ success }}
</div>
{% endif %}
{% if exist %}
<div class="alert alert-warning">
×
<strong>Warning!</strong> {{ exist }}
</div>
{% endif %}
{% csrf_token %}
<div class="form-group ">
{% for position in positions %}
<label for="cname" class="control-label col-lg-2">{{ position }}<span class="required">*</span></label>
{% for candidate in candidates %}
{% if position.pk == candidate.position_id.pk %}
<div class="col-lg-3">
<input type="checkbox" name="candidate_id" value="{{ candidate.pk }}">{{ candidate }}<br>
</div>
{% endif %}
{% endfor %}
</div>
{% endfor %}
<button class="btn btn-primary" type="submit">Save</button>
<button class="btn btn-default" type="button">Cancel</button>
</div>
</div>
</form>
How can I add/save all the candidates? because the user can select many candidates and I want to save them at once. This is my views.py
def vote(request):
if request.user.is_authenticated and request.user.is_admin:
candidates = Candidate.objects.all()
election = Election.objects.all().filter(is_active=True)
positions = Position.objects.all()
user = get_object_or_404(User, pk=request.user.pk)
try:
if request.method == 'POST':
candidate_id = request.POST['candidate_id']
vote = Vote.objects.create(candidate_id=candidate_id)
vote.save()
vote.election_id = election
vote.save()
vote.user_id = user
vote.save()
else:
form = VoteForm()
return render(request,'system/vote.html', {'form':form, 'candidates': candidates,
'election': election, 'user': user,
'positions': positions})
except:
exist = "ERROR!"
form = VoteForm()
return render(request,'system/vote.html', {'form':form, 'exist': exist})
elif not request.user.is_authenticated:
return redirect('system.views.user_login')

Categories