I want to save data from html template select field in django.
html example code:
<label for="type" style="color:red;">Short Name *</label>
<input type="text" name="short_name" class="form-control" required placeholder="">
<br> <br>
<select style='bakground-color:red' name="category" required class="form-control show-tick">
<option value="" selected="selected">---------</option>
{% for cat in category %}
<option value="{{ cat }}">{{ cat }}</option>
{% endfor %}
</select>
Django code:
Views.py
def addBooks(request):
template = 'admin_panel/add_books.html'
category = Category.objects.all()
book_details = BookDetails.objects.all()
context = {
"page_title": "Add Book",
"category": category,
"book_details" :book_details,
}
if request.method == "POST":
short_name = request.POST.get('short_name', None)
category = request.POST.get('category',None)
book_details = BookDetails.objects.create(short_name=short_name, category=category)
return render(request, template,context)
models.py
class BookDetails(models.Model):
id = models.AutoField(primary_key=True)
short_name = models.CharField(max_length=50, unique=True, db_index=True)
category = models.ForeignKey(
Category,
on_delete=models.CASCADE
)
Error Showing:
ValueError at /superadmin/add_books/
Cannot assign "'Story'": "BookDetails.category" must be a "Category" instance.
How to solve this problem?
In tamplate
option value={{cat.id}}
In view:
BookDetails.objects.create(short_name=short_name, category_id=category)
Related
Hello I am creating a cinema book system in Django, and the user must select a film and its date/time from two drop down menus. My issue is that it only takes the film and not date/time. I was wondering how I would be able to add these two in the same form.
Thanks
the html file:
<form action="/booking" method="post">
{% csrf_token %}
<div class="movie-container">
<label>Pick a film:</label>
<select name="selectedFilm">
{% for showing in showings %}
<option value="{{ showing.film }}" name="film">{{ showing.film }}</option>
{% endfor %}
</select>
<br>
<br>
<label>Pick a time:</label>
<select id="selectedDate">
{% for showing in showings %}
<option value="{{ showing.date_time }}" name="date">{{ showing.date_time }}</option>
{% endfor %}
</select>
<br>
<div class="btn-layer">
<input type="submit" value="Select">
</div>
</div>
</form>
the form file
class SelectedFilmForm(forms.Form):
selectedFilm = forms.CharField(required=True)
selectedDate = forms.DateTimeField(required=True, input_formats=["%Y-%m-%dT%H:%M", ])
enter code here
the models file
class Film(models.Model):
name = models.CharField(verbose_name='Film name', max_length=30)
age_rating = models.CharField(verbose_name='Age rating', max_length=5, choices=AgeRatings, default='U')
duration = models.DecimalField(verbose_name='Duration (minutes)', max_digits=4, decimal_places=1, blank=True, null=True)
description = models.CharField(verbose_name='Description', max_length=500, blank=True, null=True)
image = models.ImageField(upload_to='films',default='null')
def __str__(self):
return self.nameclass
Screen(models.Model):
screen_id = models.CharField(verbose_name='Screen ID', max_length=30)
capacity = models.IntegerField(verbose_name='Capacity')
def __str__(self):
return self.screen_id
class Showing(models.Model):
film = models.ForeignKey(Film, on_delete=models.CASCADE, verbose_name='Film', blank=True, null=True)
date_time = models.DateTimeField()
screen = models.ForeignKey(Screen, on_delete=models.CASCADE, verbose_name='Screen', blank=True, null=True)
def __str__(self):
return self.film.name
and my views file
def booking(request):
if request.method == "POST":
form = SelectedFilmForm(request.POST)
d = request.POST.get('selectedDate')
f = request.POST.get('selectedFilm')
print("Here", f)
print("Here", d)
if form.is_valid():
print(form.errors)
f = form.cleaned_data['selectedFilm']
d = form.cleaned_data['selectedDate']
print("Here", f)
print("Here", d)
# genderselect = form.cleaned_data['genderselect']
# request.session["genderselect"] = request.POST['genderselect']
request.session["selectedFilm"] = request.POST['selectedFilm']
request.session["selectedDate"] = request.POST['selectedDate']
else:
form = SelectedFilmForm()
film = request.session.get('selectedFilm')
date = request.session.get('selectedDate')
print("Here", film)
print("Here", date)
return render(request, "booking.html", {'film': film})
You haven't given your selectedDate dropdown a name. Note that your film dropdown has a name attribute and works. Try
<select id="selectedDate" name="selectedDate">
This will enable the selection to be pulled by your view.
Also, probably best to remove the name attribute in your options:
<option value="{{ showing.film }}" name="film"
It's not a suitable attribute for an option and may confuse things.
I am trying to insert my product by category in django. I have two model Product and Category. I want to add Product in Product table.when I add product category comes in select box and select category. Category id in category value. which is insert in product table. Category is ForeignKey. But show this error: Cannot assign "<QuerySet [<Category: Mixeur>, <Category: Hachoir>, <Category: Batteur>]>": "Product.category" must be a "Category" instance.
model.py:
from django.db import models
from django.forms import ModelForm
class Category(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Product(models.Model):
label = models.CharField(max_length=50)
description = models.CharField(max_length=200)
category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True)
quantity = models.IntegerField()
def __str__(self):
return self.label
view.py :
def add_product(request):
print(request.POST)
p_category = Category.objects.all()
if request.method == 'POST':
label = request.POST['label']
description = request.POST['description']
quantity = request.POST['quantity']
category = request.POST['category']
data = Product(
label=label,
description=description,
quantity=quantity,
category=p_category
)
data.save()
return HttpResponseRedirect('/products/')
else:
form = AddProduct()
return render(request, 'product/add_product.html', {'form': form, 'p_category':p_category})
add_product.html
<form action="/add-product/" method="post">
{% csrf_token %}
<label for="label">Label: </label>
<input id="label" type="text" name="label" value="">
<label for="description">Description: </label>
<input id="description" type="text" name="description" value="">
<label for="quantity">Quantity: </label>
<input id="quantity" type="text" name="quantity" value="">
<select class="form-control mb-4" name="category">
<option selected disabled>Select Category</option>
{% for cat in p_category %}
<option value="{{cat.id}}">{{cat.name}}</option>
{% endfor %}
</select>
<!-- {{ form }} -->
<input type="submit" value="Submit">
</form>
What you are trying to do here is to add a QuerySet to the ForeignKey field. That's why you're getting an error.
def add_product(request):
p_category = Category.objects.all()
if request.method == 'POST':
label = request.POST['label']
description = request.POST['description']
quantity = request.POST['quantity']
category = Category.objects.get(id = request.POST['category'])
data = Product(
label=label,
description=description,
quantity=quantity,
category=category
)
data.save()
return HttpResponseRedirect('/products/')
else:
form = AddProduct()
return render(request, 'product/add_product.html', {'form': form, 'p_category':p_category})
I assigned the category related to category.objects.get() from the id information to the category variable and sent it to the Product class.
You need to create a primary key which cann be referenced as foreign key in the Product table try creating a fiels id as primary key in whichever kind of sql you are using then set
id= models.BigAutoField(primary_key=True)
then you can reference the following on your product table
So, I have the following in my models.py:
UNITY_CHOICES = (
('g', 'Gram(s)'),
('kg', 'Kilogram(s)'),
('l', 'Liter(s)'),
('cl', 'Centiliter(s)'),
)
class Recipe_Ingredient(models.Model):
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
quantity = models.FloatField()
cost = models.DecimalField(max_digits=20, decimal_places=2)
quantityUnit = models.CharField(
max_length=2,
choices=UNITY_CHOICES,
default=GRAM,
)
class Ingredient(models.Model):
name = models.CharField(max_length=200)
articleNumber = models.IntegerField(unique=True)
costPrice = models.DecimalField(max_digits=20, decimal_places=2)
costAmout = models.FloatField()
costUnity = models.CharField(
max_length=2,
choices=UNITY_CHOICES,
default=GRAM,
)
And I have a simple form to add this model to my database:
class Recipe_IngredientForm(forms.ModelForm):
class Meta:
model = Recipe_Ingredient
fields = ('quantity', 'quantityUnit', 'ingredient')
So I was wondering if there's a way of filtering the quantityUnit available choices depending on the ingredient chosen.
I'll try to make it clear by an example: Let's say I choose to add Potato and the costUnity for Potato is 'g', then I want to make 'kg' and 'g' the only choices for quantityUnit. Is that a good example? I can try to think of something better if it's not clear enough.
Anyway, is it possible to do such thing? Thanks.
UPDATE:
forms.py:
class Recipe_IngredientForm(forms.ModelForm):
class Meta:
model = Recipe_Ingredient
fields = ('quantity', 'quantityUnit', 'ingredient')
template:
{% extends 'recipe/base.html' %}
{% block content %}
<h1>Add Ingredient to Recipe</h1>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% endblock %}
Rendered HTML:
<h1>Add Ingredient to Recipe</h1>
<form method="POST" class="post-form"><input type="hidden" name="csrfmiddlewaretoken" value="tXVR3NM1R4TBwOJArWWClL71r8S5C18gWKz9mKK42wlEamf6NcBjzrieF5dQBOaO">
<p>
<label for="id_quantity">Quantity:</label>
<input type="number" name="quantity" required="" id="id_quantity" step="any">
</p>
<p>
<label for="id_quantityUnit">QuantityUnit:</label>
<select name="quantityUnit" id="id_quantityUnit">
<option value="g" selected="">Gram(s)</option>
<option value="kg">Kilogram(s)</option>
<option value="l">Liter(s)</option>
<option value="cl">Centiliter(s)</option>
</select>
</p>
<p>
<label for="id_ingredient">Ingredient:</label> <select name="ingredient" required="" id="id_ingredient">
<option value="" selected="">---------</option>
<option value="1">Carrot</option>
<option value="2">Potato</option>
<option value="3">Water</option>
<option value="4">Juice</option>
</select>
</p>
<button type="submit" class="save btn btn-default">Save</button>
</form>
I am currently struggling to get my form to work properly. I created the form manually (template.html) and I can see all the data when I call it with print(request.POST) (in views.py - checkout) however form.is_valid(): (in views.py - checkout) doesn't work. Means my form is not valid.
I think the issue is, that I created the form manually and combined it with a model form where I want after validating my data with form.valid() save it in. Can anyone of you guys help me with my problem, why it's not valid?
template.html
<form action="{% url 'checkout:reserve_ticket' %}" method="post">
{% csrf_token %}
{% for ticket in event.tickets.all %}
<p>
{{ ticket.name }} for {{ ticket.price_gross }} with quantity:
<input type="hidden" name="order_reference" value="123456af">
<input type="hidden" name="ticket" value="{{ ticket.id }}">
<input type="hidden" name="ticket_name" value="{{ ticket.name }}">
<input type="number" name="quantity" max="{{ ticket.event.organiser.max_quantity_per_ticket }}" placeholder="0">
</p>
{% endfor %}
<button type="submit" class="btn btn-primary">Continue</button>
</form>
models.py
class ReservedItem(models.Model):
order_reference = models.CharField(
max_length=10,
unique=True
)
ticket = models.ForeignKey(
Ticket,
on_delete=models.PROTECT,
related_name='reserved_tickets'
)
ticket_name = models.CharField(max_length=100)
quantity = models.IntegerField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
forms.py
class ReserveForm(forms.ModelForm):
class Meta:
model = ReservedItem
fields = ['order_reference', 'ticket', 'ticket_name', 'quantity']
views.py - events
# Create your views here.
class EventDetailView(DetailView):
context_object_name = 'event'
def get_object(self):
organiser = self.kwargs.get('organiser')
event = self.kwargs.get('event')
queryset = Event.objects.filter(organiser__slug=organiser)
return get_object_or_404(queryset, slug=event)
views.py - checkout
def reserve_ticket(request):
if request.method == 'POST':
form = ReserveForm(request.POST)
if form.is_valid():
print("Hello World")
return redirect("https://test.com")
else:
print("back to homepage")
I have a form that needs references from another model. here the example.
I have models.py
class Employee(models.Model):
name = models.CharField(max_length=100)
class Inven(models.Model):
name = models.CharField(max_length=255)
sn = models.DecimalField(max_digits=20, decimal_places=0)
employee = models.ForeignKey(Employee, null=True, on_delete=models.SET_NULL, related_name='employee')
here my views.py
class InventoryListView(ListView):
context_object_name = 'inventorys'
model = models.Inventory
and here my inven template_form.html
<input type="text" name="name" maxlength="100" required="" id="id_name">
<input type="text" name="sn" maxlength="100" required="" id="id_sn">
<select>
{% for employee in employees %}
<option value="{{employee.pk}}">{{employee.name}}</option>
{% endfor %}
</select>
how to make employee field as a select list from employee model?...