How can I edit data without deleting what has been added before. In my situation, I want to use forms.Form which looks like this
class SecondForm(forms.Form):
data_1 = forms.ChoiceField(choices=CHOICES, label="")
data_2 = forms.ChoiceField(choices=CHOICES, label="")
data_3 = forms.ChoiceField(choices=CHOICES, label="")
In my views.py
id = #some object number
if request.method =="POST":
second_form = SecondForm(request.POST)
if second_form.is_valid():
cd = second_form.cleaned_data
object = Valuation(pk=object_id)
object.data_1 = cd['data_1']
object.data_2 = cd['data_2']
object.data_3 = cd['data_3']
object.save()
return HttpResponseRedirect(reverse('app:valuation_third', args=[forwarding]))
else:
second_form = SecondForm()
In this situation, if my model looks like this:
class Valuation(models.Model):
data_added_before = models.CharField(max_length=50, blank=True)
data_1 = models.CharField(max_length=50, blank=True)
data_2 = models.CharField(max_length=50, blank=True)
data_3 = models.CharField(max_length=50, blank=True)
Every time a field 'data_added_before' it's cleaned. How to avoid it. So that the information added earlier in this field has been preserved. And new data from the current form added to existing ones.
EDIT:
Any help will be appreciated.
Tempate.html
{% load crispy_forms_tags %}
<form action="." method="post">
<div class="">
<h2 class="h3 text-primary font-weight-normal mb-4">More information></h2>
</div>
{% csrf_token %}
<p>data_1 name</p>
{{ second_form.data_1|as_crispy_field }}
<p>data_2 name</p>
{{ second_form.data_2|as_crispy_field }}
<p>data_3 name</p>
{{ second_form.data_3|as_crispy_field }}
<div class="form-row">
<div class="form-group col-md-6 mb-0">
<form>
<input class="btn btn-text btn-text-secondary" type="button" value="before" onclick="history.back()">
</form>
</div>
<div class="form-group col-md-6 mb-0">
<div class="text-right">
<button type="submit" class="btn btn-primary">next <i class="fas fa-angle-right fa-lg"></i></button>
</div>
</div>
</div>
</form>
Related
I have a django app and I need to count the number of listings in a category (as defined by the models below):
here is my complete model
class Category(models.Model):
name = models.CharField(max_length=500)
icon = models.ImageField(upload_to='photos/icons/%Y/%m/%d/')
def __str__ (self):
return self.name
class Listing(models.Model):
name = models.CharField(max_length=300)
category = models.ForeignKey(Category, on_delete=models.CASCADE, default=False, null=True)
email = models.EmailField(max_length=300)
description = RichTextField(blank=False, null=False)
photo_main = models.ImageField(upload_to = 'photos/%Y/%m/%d/')
photo_1 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank=True, default=True)
photo_2 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank=True, default=True)
photo_3 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank=True, default=True)
photo_4 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank=True, default=True)
location = models.CharField(max_length=500, null=True)
phone_number = models.CharField(max_length=11, default = "#")
website = models.CharField(max_length=150, blank=True, default="#")
facebook = models.CharField(max_length=150, blank=True, default="#")
instagram = models.CharField(max_length=150, blank=True, default="#")
opening_time = models.CharField(max_length=7)
closing_time = models.CharField(max_length=7)
is_published = models.BooleanField(default=False)
posted_date = models.DateTimeField(auto_now_add=True)
user_id = models.IntegerField(blank=True)
def __str__ (self):
return self.name
here are my views
from django.shortcuts import render
from listings.models import Listing
from listings.models import Category
from testimonies.models import Testimony
from our_team.models import Team_Mate
from testimonies.models import Testimony
from django.db.models import Count
def index(request):
this part is working perfectly.
listings = Listing.objects.order_by('-posted_date').filter(is_published=True)[:6]
category = request.GET.get('category')
categories = Category.objects.all()[:7]
counting listings in a category
count_cate = Category.objects.all()
cate_count = count_cate.count()
if category == None:
listings = Listing.objects.order_by('-posted_date').filter(is_published=True)[:6]
else:
listings = Listing.objects.filter(Category__name=category)
here is my context
context ={
'listings': listings,
'categories': categories,
'cate_count': cate_count,
}
return render(request, 'pages/index.html', context)
Here is my html where I want the number of listings in category to show
{% extends 'base.html' %}
{% load static %}
{% block content %}
<!-- ======= Intro Section ======= -->
<div class="header">
<div class="header-content display-table">
<div class="table-cell">
<div class="container">
<h1 class="header-title text-light text-uppercase pb-3">Explore Bonny Island</h1>
<h3 class="text-light">Find. Connect. Share</h3>
<div class="search mt-3 px-0 py-1 mx-0">
<form action="{% url 'search' %}" method="GET">
{% csrf_token %}
<div class="row d-flex justify-content-center container p-0 m-0 px-1">
<input type="text" name="keywords"
class="form-control col-lg-3 col-md-12 col-sm-12 mx-2 py-4 my-2 border border-5"
placeholder=" Keyword">
<input type="text" name="location"
class="form-control col-lg-3 col-md-12 mx-2 py-4 col-sm-12 my-2 border border-5"
placeholder=" Location">
<input type="text" name="category" value="{{ query }}" list="category"
class="form-control col-lg-3 col-md-12 col-sm-12 mx-2 py-4 my-2 border border-5"
placeholder=" Category (All)">
<datalist id="category">
{% for categories in categories %}
<option>{{ categories.name }}</option>
{% endfor %}
</datalist>
<button type="submit"
class="btn search-bt col-lg-2 col-md-12 mx-2 col-sm-12 py-2 px-2 font-weight-bold my-
2">Search</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div><!-- End Intro Section -->
<!-- ======== most popular categories ========= -->
<section class="main">
<div class="discover pb-1 m-0">
<h2>Explore Categories</h2>
<div class="container">
<div class="row justify-content-around m-0 p-0 pt-3">
{% for category in categories %}
{% if category %}
<div class="col-lg-3 col-md-6 py-2">
<a href="{% url 'listings' %}?category={{ category.name }}" class="card category">
<div class="d-flex justify-content-between align-items-start px-3 m-0 py-2">
<div class="category-name-icon p-0 m-0">
<span class="text-dark font-weight-bold"><img class="category-icon" src="{{
category.icon.url }}">
{{category.name}}</span>
</div>
<div class="category-list-number text-muted font-weight-bold">{{cate_count}}</div>
</div>
</a>
</div>
{% endif %}
{% endfor %}
<div class="col-lg-3 col-md-6 py-2">
<a href="{% url 'category' %}" class="card category" data-bs-toggle="collapse"
href="#collapseExample"
role="button" aria-expanded="false" aria-controls="collapseExample">
<div class="d-flex justify-content-between = px-3 m-0 py-2">
<i class="font-weight-bold py-1 text-secondary">More Categories...</i>
</div>
</a>
</div>
</div>
</div>
</section> <!-- ======== most popular categories end ======== -->
<!-- STRUCTURING THE POPULAR LISTINGS CONTENT-->
<section id="popularListings" class="container mb-5 py-5">
<!-- Popular listenings head title-->
<div class="sectionTitle d-flex justify-content-between align-items-baseline">
<div class="mainTitleContents">
<h2 class="titleText h2 text-blue">Popular Listings</h2>
<p class="subTitleText mb-2">Explore businesses on the island.</p>
</div>
<div class="filterOption">
All Listings
</div>
</div>
<!-- MAIN POPULAR LISTINGS ROW CONTENT-->
<div class="popularListingsRows row py-2">
{% if listings %}
{% for listing in listings %}
<div class="customCard p-1 m-0 col-lg-3 col-md-4 col-sm-6 mt-sm-3">
<div class="card">
<div class="card-header p-0">
<div class="blank rounded" style="background-image: url('{{
listing.photo_main.url }}'); background-repeat: no-repeat;
background-size:cover; width:100%; height: 15em; background-
position:center-top" ;></div>
</div>
<div class="card-body">
<div class="content-details">
<h3 class="m-0 mt-1 mb-2 cardTitle">{{ listing.name }}</h3>
<p class="cardSubTitle">
{%autoescape off%}
{{ listing.description|striptags|truncatechars:100 }}
{%endautoescape%}
</p>
<a href="{% url 'listing' listing.id %}" class="btn btn-sm bg-blue text-
light rounded-none">Read More</a>
</div>
</div>
</div>
</div>
{% endfor %}
{% else %}
<div class="col-md-12">
<p class="text-dark">No listings Available</p>
</div>
{% endif %}
</div>
</section>
{% endblock %}
How can I make this code work as intended?
You should call the count method on the list of objects like...
if category == None:
listings = Listing.objects.order_by('-posted_date').filter(is_published=True)[:6]
else:
listings = Listing.objects.filter(category__name=category).count()
Please ensure where you have Category__name=category you must allow this to match your model field category.
In your html:
<!-- ======= Intro Section ======= -->
<form action="{% url 'search' %}" method="GET">
{% csrf_token %}
<div class="row d-flex justify-content-center container p-0 m-0 px-1">
...
<!--<input type="text" name="category" value="{{ query }}" list="category" class="form-control col-lg-3 col-md-12 col-sm-12 mx-2 py-4 my-2 border border-5" placeholder=" Category (All)">-->
<!-- Remove value="{{ query }}" -->
<input type="text" name="category" list="categories" class="form-control col-lg-3 col-md-12 col-sm-12 mx-2 py-4 my-2 border border-5" placeholder=" Category (All)">
<!-- Should be category in categories instead of categories in categories -->
<datalist id="categories">
{% for category in categories %}
<option value="{{ category.name }}"> <!-- Setting the value here... -->
{% endfor %}
</datalist>
...
</div>
</form>
I solved the it by calling the name of the category i want to count but am still to look for a way to count it without specifying the category name.
cate_count = Listing.objects.filter(category__name="Catering services").count()
I have created two models, Porumbei and Perechi. Porumbei means pigeon and it can be male or female, they live in pairs(Perechi). My models below(part of it)
class Gender(models.Model):
sexul = models.CharField(max_length=20, null=False, blank=False)
def __str__(self):
return self.sexul
class Porumbei(models.Model):
....
serie_inel = models.CharField(....)
sex = models.ForeignKey(Gender, on_delete=models.CASCADE)
....
class Perechi(models.Model):
....
mascul = models.ForeignKey(Porumbei, on_delete=models.CASCADE)
femela = models.ForeignKey(Porumbei, on_delete=models.CASCADE)
My form:
class AdaugaPereche(forms.Form):
boxa = forms.IntegerField(label="Boxa", min_value=1)
sezon = forms.CharField(label="Sezon reproducere", initial=datetime.now().year)
mascul = forms.ChoiceField(choices=Porumbei.objects.filter(sex__sexul="Mascul", perechi_masculi__isnull=True), label="Mascul")
femela = forms.ChoiceField(choices=Porumbei.objects.filter(sex__sexul="Femelă", perechi_femele__isnull=True), label="Femela")
serie_pui_1 = forms.CharField(label="Serie pui 1")
serie_pui_2 = forms.CharField(label="Serie pui 2")
culoare_pui_1 = forms.ChoiceField(choices=CuloriPorumbei.objects.all(), label="Culoare pui 1")
culoare_pui_2 = forms.ChoiceField(choices=CuloriPorumbei.objects.all(), label="Culoare pui 2")
data_imperechere = forms.DateField(label="Dată împerechere")
primul_ou = forms.DateField(label="Primul ou")
data_ecloziune = forms.DateField(label="Dată ecloziune")
data_inelare = forms.DateField(label="Dată inelare")
comentarii = forms.Textarea()
My view:
def perechenoua(request):
if request.method == "POST":
form = AdaugaPereche(request.POST)
if form.is_valid():
form.save()
return redirect("porumbei")
else:
form = AdaugaPereche()
context = {
'form': form
}
template = loader.get_template("adauga_pereche.html")
return HttpResponse(template.render(context, request))
The template:
<form method="post">{% csrf_token %}
<div class="form-group row">
<div class="col-sm-3">
{{ form.boxa|add_class:"form-control" }}
</div>
<div class="col-sm-3">
{{ form.sezon|add_class:"form-control" }}
</div>
</div>
<div class="form-group row">
<div class="col-sm-3">
{{ form.mascul|add_class:"form-control custom-select d-block w-100" }}
</div>
<div class="col-sm-3">
{{ form.femela|add_class:"form-control custom-select d-block w-100" }}
</div>
</div>
<div class="form-group row">
<div class="col-sm-3">
{{ form.serie_pui_1|add_class:"form-control" }}
</div>
<div class="col-sm-3">
{{ form.serie_pui_2|add_class:"form-control custom-select d-block w-100" }}
</div>
</div>
<div class="form-group row">
<div class="col-sm-3">
{{ form.culoare_pui_1|add_class:"form-control custom-select d-block w-100" }}
</div>
<div class="col-sm-3">
{{ form.culoare_pui_2|add_class:"form-control custom-select d-block w-100" }}
</div>
</div>
<div class="form-group row">
<div class="col-sm-3">
{{ form.data_imperechere }}
</div>
<div class="col-sm-3">
{{ form.primul_ou }}
</div>
</div>
<div class="form-group row">
<div class="col-sm-3">
{{ form.data_ecloziune }}
</div>
<div class="col-sm-3">
{{ form.data_inelare }}
</div>
</div>
<div class="form-group row">
<div class="col-sm-3">
{{ form.comentarii }}
</div>
</div>
</form>
When I create a new Perechi(pair), the field mascul I want to be sorted with all male in Porumbei(pigeons) and once it has been added to pairs, the next time when adding pairs that male to be excluded from list because it already have pair. The same with female. How can I implement this?
You can use the limit_choices_to argument of ForeignKey to directly limit the choices:
from django.db.models import Q
mascul = models.ForeignKey(Porumbei, on_delete=models.CASCADE,
limit_choices_to=Q(sex__sexul="male",
related_name="pairs_as_male"))
Here's the documentation.
With the related_name you can also query the reverse relationship:
Porumbei.objects.filter(sex__sexul="male", pairs_as_male__isnull=True)
will give you male pigeons that aren't paired yet.
I am trying to edit multiple rows of data in a model via formsets. In my rendered form, I use javascript to delete (hide and assign DELETE) rows, and then save changes with post.
My view:
def procedure_template_modification_alt(request, cliniclabel, template_id):
msg = ''
clinicobj = Clinic.objects.get(label=cliniclabel)
template_id = int(template_id)
template= ProcedureTemplate.objects.get(templid = template_id)
formset = ProcedureModificationFormset(queryset=SectionHeading.objects.filter(template = template))
if request.method == 'POST':
print(request.POST.get)
# Create a formset instance with POST data.
formset = ProcedureModificationFormset(request.POST)
if formset.is_valid():
print("Form is valid")
instances = formset.save(commit=False)
print(f'instances:{instances}')
for instance in instances:
print(f'Instance: {instance}')
instance.template = template
instance.save()
msg = "Changes saved successfully."
print("Deleted forms:")
for form in formset.deleted_forms:
print(form.cleaned_data)
else:
print("Form is invalid")
print(formset.errors)
msg = "Your changes could not be saved as the data you entered is invalid!"
template= ProcedureTemplate.objects.get(templid = template_id)
headings = SectionHeading.objects.filter(template = template)
return render(request, 'procedures/create_procedure_formset_alt.html',
{
'template': template,
'formset': formset,
'headings': headings,
'msg': msg,
'rnd_num': randomnumber(),
})
My models:
class ProcedureTemplate(models.Model):
templid = models.AutoField(primary_key=True, unique=True)
title = models.CharField(max_length=200)
description = models.CharField(max_length=5000, default='', blank=True)
clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE)
def __str__(self):
return f'{self.description}'
class SectionHeading(models.Model):
procid = models.AutoField(primary_key=True, unique=True)
name = models.CharField(max_length=200)
default = models.CharField(max_length=1000)
sortorder = models.IntegerField(default=1000)
fieldtype_choice = (
('heading1', 'Heading1'),
('heading2', 'Heading2'),
)
fieldtype = models.CharField(
choices=fieldtype_choice, max_length=100, default='heading1')
template = models.ForeignKey(ProcedureTemplate, on_delete=models.CASCADE, null=False)
def __str__(self):
return f'{self.name} [{self.procid}]'
My forms:
class ProcedureCrMetaForm(ModelForm):
class Meta:
model = SectionHeading
fields = [
'name',
'default',
'sortorder',
'fieldtype',
'procid'
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['name'].widget.attrs.update({'class': 'form-control'})
self.fields['default'].widget.attrs.update({'class': 'form-control'})
self.fields['sortorder'].widget.attrs.update({'class': 'form-control'})
self.fields['fieldtype'].widget.attrs.update({'class': 'form-control'})
ProcedureCreationFormset = formset_factory(ProcedureCrMetaForm, extra=3)
ProcedureModificationFormset = modelformset_factory(SectionHeading, ProcedureCrMetaForm,
fields=('name', 'default', 'sortorder','fieldtype', 'procid'),
can_delete=True,
extra=0
# widgets={"name": Textarea()}
)
The template:
{% block content %} {% load widget_tweaks %}
<div class="container">
{% if user.is_authenticated %}
<div class="row my-1">
<div class="col-sm-2">Name</div>
<div class="col-sm-22">
<input type="text" name="procedurename" class="form-control" placeholder="Enter name of procedure (E.g. DNE)"
value="{{ template.title }}" />
</div>
</div>
<div class="row my-1">
<div class="col-sm-2">Description</div>
<div class="col-sm-22">
<input type="text" name="proceduredesc" class="form-control" placeholder="Enter description of procedure (E.g. Diagnostic Nasal Endoscopy)"
value="{{ template.description }}" />
</div>
</div>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %} {{ formset.management_form }}
<div class="row mt-3">
<div class="col-sm-1">Select</div>
<div class="col-sm-6">Heading</div>
<div class="col-sm-8">Default (Normal description)</div>
<div class="col-sm-2">Sort Order</div>
<div class="col-sm-4">Type</div>
<div class="col-sm-2">Action</div>
</div>
{% for form in formset %}
<div class="row procrow" id="row{{ forloop.counter0 }}">
<div class="" style="display: none;">{{ form.procid }}</div>
<div class="col-sm-6">
{{ form.name }}
</div>
<div class="col-sm-8">
<div class="input-group">
{{ form.default }}
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
{{ form.sortorder }}
</div>
</div>
<div class="col-sm-4">
<div class="input-group">
{{ form.fieldtype }}
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<div class="input-group-append">
<button id="add{{ forloop.counter0 }}" class="btn btn-success add-row">+</button>
</div>
<div class="input-group-append">
<button id="del{{ forloop.counter0 }}" class="btn btn-danger del-row">-</button>
</div>
</div>
</div>
</div>
{% endfor %} {% endif %}
<div class="row my-3">
<div class="col-sm-8"></div>
<div class="col-sm-8">
<div class="input-group">
<div class="input-group-append mx-1">
<button id="save_report" type="submit" class="btn btn-success"><i class="fal fa-shield-check"></i>
Save Report Format</button>
</div>
<div class="input-group-append mx-1">
<button id="save_report" type="button" class="btn btn-danger"><i class="fal fa-times-hexagon"></i>
Cancel</button>
</div>
</div>
</div>
<div class="col-sm-8"></div>
</div>
<div>
{% for dict in formset.errors %} {% for error in dict.values %} {{ error }} {% endfor %} {% endfor %}
</div>
</form>
</div>
{% endblock %}
My data is displayed as below (Screenshot). I make changes with javascript when the delete button is pressed, so that the html becomes like this:
<div class="row procrow" id="row2" style="display: none;">
<div class="" style="display: none;"><input type="hidden" name="form-2-procid" value="25" id="id_form-2-procid"></div>
<div class="col-sm-6">
<input type="text" name="form-2-name" value="a" maxlength="200" class="form-control" id="id_form-2-name">
</div>
<div class="col-sm-8">
<div class="input-group">
<input type="text" name="form-2-default" value="v" maxlength="1000" class="form-control" id="id_form-2-default">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<input type="number" name="form-2-sortorder" value="1000" class="form-control" id="id_form-2-sortorder">
</div>
</div>
<div class="col-sm-4">
<div class="input-group">
<select name="form-2-fieldtype" class="form-control" id="id_form-2-fieldtype">
<option value="heading1" selected="">Heading1</option>
<option value="heading2">Heading2</option>
</select>
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<div class="input-group-append">
<button id="add2" class="btn btn-success add-row">+</button>
</div>
<div class="input-group-append">
<button id="del2" class="btn btn-danger del-row">-</button>
</div>
</div>
</div>
<input type="checkbox" name="form-2-DELETE" id="id_form-2-DELETE" checked=""></div>
On submitting the data, I get the following output, and data does not reflect the deletion I did. It displays the same thing again. There are no errors. But my edited data is not being saved.
Output:
<bound method MultiValueDict.get of <QueryDict: {'csrfmiddlewaretoken': ['ka3avICLigV6TaMBK5a8zeVJlizhtsKW5OTDBLlYorKd7Iji9zRxCX2vvjBv6xKu'], 'form-TOTAL_FORMS': ['3'], 'form-INITIAL_FORMS': ['3'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-0-procid': ['23'], 'form-0-name': ['External ear canal'], 'form-0-default': ['Bilateral external ear canals appear normal. No discharge.'], 'form-0-sortorder': ['100'], 'form-0-fieldtype': ['heading1'], 'form-1-procid': ['24'], 'form-1-name': ['Tympanic membrane'], 'form-1-default': ['Tympanic membrane appears normal. Mobility not assessed.'], 'form-1-sortorder': ['500'], 'form-1-fieldtype': ['heading1'], 'form-2-procid': ['25'], 'form-2-name': ['a'], 'form-2-default': ['v'], 'form-2-sortorder': ['1000'], 'form-2-fieldtype': ['heading1'], 'form-2-DELETE': ['on']}>>
Form is valid
instances:[]
Deleted forms:
{'name': 'a', 'default': 'v', 'sortorder': 1000, 'fieldtype': 'heading1', 'procid': <SectionHeading: a [25]>, 'DELETE': True}
You actually need to delete the instances: Loop through the formsets' deleted_objects property after you called saved(commit=False) and delete them.
I have a Django project and I encountered with a problem of comparing a database foreign key attribute with form foreign key attribute. My project files are below :
My Model.py File:
class Teacher(models.Model):
Name = models.CharField(max_length=100)
Designation = models.CharField(max_length=100,choices=DESIGNATION)
Department = models.CharField(max_length=100,choices=T_Dept)
Address = models.CharField(max_length=100)
def __str__(self):
return self.Name + ", " + self.Designation + ", " + "("+self.Department +"), "+ self.Address
class Moderation(models.Model):
year = models.CharField(max_length=100,choices=T_Year)
semester = models.CharField(max_length=100,choices=T_Semester)
examtype = models.CharField(max_length=30,choices=EXAMTYPE)
examyear = models.CharField(max_length=30,choices=EXAMYEAR)
NamAdd = models.ForeignKey(Teacher, on_delete=models.CASCADE)
position = models.CharField(max_length=100,choices=POSITON)
def __str__(self):
return unicode(self.NamAdd)
My forms.py File :
class modaForm(forms.ModelForm):
class Meta:
model=Moderation
fields=[
'year',
'semester',
'NamAdd',
'position','examtype','examyear'
]
My HTML File :
<form action="{% url 'modIni' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="col-sm-12 col-md-4">
<br>
<div class="input-group">
<span class="input-group-addon">Year </span>
{% load widget_tweaks %}
{{ modForm.year|add_class:"form-control" }}
</div>
</div>
<div class="col-sm-12 col-md-4">
<br>
<div class="input-group">
<span class="input-group-addon">Semester </span>
{% load widget_tweaks %}
{{ modForm.semester|add_class:"form-control" }}
</div>
</div>
<div class="col-sm-12 col-md-4">
<br>
<div class="input-group">
<span class="input-group-addon">Exam Type</span>
{% load widget_tweaks %}
{{ modForm.examtype|add_class:"form-control" }}
</div>
</div>
<div class="col-sm-12 col-md-4">
<br>
<div class="input-group">
<span class="input-group-addon">Exam Year</span>
{% load widget_tweaks %}
{{ modForm.examyear|add_class:"form-control" }}
</div>
</div>
<div class="col-sm-12 col-md-4">
<br>
<div class="input-group">
<span class="input-group-addon">Name and Address</span>
{% load widget_tweaks %}
{{ modForm.NamAdd|add_class:"form-control" }}
</div>
</div>
<div class="col-sm-12 col-md-4">
<br>
<div class="input-group">
<span class="input-group-addon">Position </span>
{% load widget_tweaks %}
{{ modForm.position|add_class:"form-control" }}
</div>
</div>
<div class="col-sm-12 col-md-12">
<br>
<center>
<button type="submit" class="btn btn-success btn-lg"><spam class="glyphicon glyphicon-send"> </spam> Submit</button>
</center>
</div>
</form>
My View.py File :
def modIni(request):
modForm = modaForm(request.POST or None,request.FILES or None)
year = modForm['year'].value()
semester = modForm['semester'].value()
examtype = modForm['examtype'].value()
examyear = modForm['examyear'].value()
NamAdd = modForm['NamAdd'].value()
position = modForm['position'].value()
fMod = Moderation.objects.all().last
if modForm.is_valid():
instance = modForm.save(commit=False)
flag =True
for obj in Moderation.objects.all():
if obj.year == year and obj.semester == semester and obj.examtype == examtype and obj.examyear == examyear and obj.NamAdd == NamAdd and obj.position == position:
context = {'fMod':fMod,'modForm':modForm,'msg':"<span style='color:red;'><h3>Already Inserted!</h3> Last entry : </span>"}
flag = False
break
if flag:
instance.save()
#modForm = modaForm()
context = {'NamAdd':NamAdd,'fMod':fMod,'modForm':modForm,'msg':"<span style='color:#4BB543;'><h3>successfully accomplished!</h3> Last entry : </span>"}
else:
context = {'fMod':fMod,'modForm':modForm,'msg':"<span style='color:Red;'> <center>Please fill in all the fields</center>Last entry : </span>"}
return render(request, 'tbs/form/modaration.html',context)
How to compare obj.NamAdd.Name == NamAdd in view File? Please help me by providing any hint.
Basically, I want to save a unique Moderation object into database How doing this? Has any alternative way?
Thanks advance.
Whats wrong with obj.NamAdd == NamAdd ?
Many.
The primary issue for the comparison failure is that NamAdd is an integer(Teacher object id) where obj.NamAdd is a model object.
So, on this regard, it should be obj.NamAdd.id == NamAdd
Don't do this please. Not that way. You are bypassing input validation.
It could be obj.NamAdd == modForm.cleaned_data['NamAdd']
Since you want unique Moderation,
add this to the model:
class Meta:
unique_together = (('year', 'semester', 'examtype', 'examyear', 'NamAdd', 'position'))
so that it now looks like
class Moderation(models.Model):
year = models.CharField(max_length=100, choices=[])
semester = models.CharField(max_length=100, choices=[])
examtype = models.CharField(max_length=30, choices=[])
examyear = models.CharField(max_length=30, choices=[])
NamAdd = models.ForeignKey(Teacher, on_delete=models.CASCADE)
position = models.CharField(max_length=100, choices=[])
def __str__(self):
return unicode(self.NamAdd)
class Meta:
unique_together = (('year', 'semester', 'examtype', 'examyear', 'NamAdd', 'position'))
(remember makemigrations and migrate)
**note I used empty list for choices, adjust for your case.
now in the view, use this for checking moderation existence:
moderation_exists = Moderation.objects.filter(year=modForm.cleaned_data['year'], semester=modForm.cleaned_data['semester'],examtype=modForm.cleaned_data['examtype'], examyear=modForm.cleaned_data['examyear'], NamAdd=modForm.cleaned_data['NamAdd'], position=modForm.cleaned_data['position']).exists()
if moderation_exists:
context = {'fMod': fMod, 'modForm': modForm,
'msg': "<span style='color:red;'><h3>Already Inserted!</h3> Last entry : </span>"}
flag = False
Someone could help me with this problem ?
models.py
#autoconnect
class Event(models.Model):
title = models.CharField(max_length=50, unique=True)
slug = models.CharField(max_length=100, default=' ', blank=True)
description = models.CharField(max_length=250, blank=True)
PrivacityType = ((1, 'Público'), (2, 'Privado'))
privacity = models.IntegerField(choices=PrivacityType, default=1, blank=True)
EVENT_TYPE = ((1, 'Deporte'), (2, 'Nutrición'), (3, 'Salud'))
type = models.IntegerField(choices=EVENT_TYPE, default=1)
owner = models.ForeignKey(User)
creation_date = models.DateTimeField(auto_now=True)
updated_date= models.DateTimeField(auto_now_add=True)
start = models.DateTimeField(default=datetime.datetime.now())
end = models.DateTimeField(default=datetime.datetime.now())
address = models.CharField(max_length=250, default='', blank=True)
notes = models.CharField(max_length=250, default='', blank=True)
def __unicode__(self):
return self.title
def pre_save(self):
self.slug = self.title.replace(" ", "_").lower()
forms.py
class EventForm(forms.ModelForm):
title = forms.CharField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Título'}))
description = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Descripción'}))
address = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Lugar'}))
notes =forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Añade tus notas'}))
class Meta:
model = event_models.Event
fields = '__all__'
views.py
class EventUpdateView(LoginRequiredMixin, UpdateView):
model = events_models.Event
template_name = 'event.html'
fields = ['title', 'description']
slug_field = 'slug'
slug_url_kwarg = 'slug'
context_object_name = 'event'
urls.py
url(r'^eventos/(?P<slug>\w+)/$', calendar_views.EventUpdateView.as_view(), name='detail_event'),
url(r'^eventos/nuevo/$', calendar_views.add_event, name='add_event'),
event.html:
{% extends "calendar.html" %}
{% load static %}
{% load calendar_tags %}
{% block event %}
<!-- Event Information Area -->
<div class="col-md-6 col-lg-6 col-sm-12 col-xs-12 smt-30 xmt-30">
<div class="map-contacts">
<!--<form id="contact-form" method="POST">-->
<form action="{% url 'calendar:detail_event' event_slug=event.slug %}" method="POST">
{% csrf_token %}
<!-- Event Form Area -->
<div class="single-contact-form">
<div class="contact-box subject">
<h3>Privacidad</h3>
{{ event.privacity }}
</div>
</div>
<!-- Event Form Area -->
<div class="single-contact-form">
<div class="contact-box subject">
<h3>Categoría</h3>
{{ event.type }}
</div>
</div>
<!-- Event Form Area -->
<div class="single-contact-form">
<div class="contact-box subject">
{{ event.title }}
</div>
</div>
<!-- Event Form Area -->
<div class="single-contact-form">
<div class="contact-box subject">
{{ event.description }}
</div>
</div>
<!-- Event Form Area -->
<div class="single-contact-form">
<div class="contact-box subject">
{{ event.address }}
</div>
</div>
<!-- Event Form Area -->
<div class="single-contact-form">
<div class="contact-box subject">
<h3>Inicio</h3>
{{ event.start }}
</div>
</div>
<!-- Event Form Area -->
<div class="single-contact-form">
<div class="contact-box subject">
<h3>Fin</h3>
{{ event.end }}
</div>
</div>
<!-- Event Form Area -->
<div class="single-contact-form">
<div class="contact-box subject">
<h3>Privacidad</h3>
{{ event.notes }}
</div>
</div>
<div class="contact-btn">
<input type="submit" class="fv-btn" value="Modificar">
</div>
</form>
</div>
</div>
{% endblock %}
The template call:
{{ event.title }}
This is the error that appears.
How can i fix it ?
Reverse for 'detail_event' with keyword arguments '{u'event_slug': u'evento_1'}' not found. 1 pattern(s) tried: [u'calendario/eventos/(?P\w+)/$']
Thanks in advance.
Your approach won't work because you need an event_slug to reach the form where you will create the event. But the event_slug won't exist until after you create the event!
The usual solution is to have separate 'create' and 'update' views.
Check out the generic editing views for this purpose. For example, you could navigate to /event/new/ to create a new event (without slug) and then go to /event/(?P<slug>\w+)/ to edit that event once the slug exists.
This answer should also help you out.