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
Related
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)
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.
currently I'm trying to show part quantity (quan) together with part name in the dropdown. I have a Part table that carries the part name and part quantity and this table called as ForeignKey into the Order table. So, in the Order form during choose the part name from the part dropdown, I would like to show part quantity as well besides the part name. Any idea to make it like that?
models.py
class Part(models.Model):
partno = models.CharField(max_length=50)
partname = models.CharField(max_length=50)
quan = models.PositiveIntegerField(default= 0)
def __str__(self):
return '{}, quantity - {}'.format(self.partname, self.quan)
class Order(models.Model):
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
part = models.ForeignKey(Part, on_delete=models.CASCADE)
views.py
def create_order(request):
from django import forms
form = OrderForm()
if request.method == 'POST':
for form_data in forms_data:
forms = OrderForm(request.POST)
if forms.is_valid():
supplier = forms.cleaned_data['supplier']
product = forms.cleaned_data['product']
part = forms.cleaned_data['part']
order = Order.objects.create(
supplier=supplier,
product=product,
part=part,
)
return redirect('order-list')
context = {
'form': form
}
return render(request, 'store/addOrder.html', context)
HTML
<form action="#" method="post" id="form-container" novalidate="novalidate">
{% csrf_token %}
<div class="form-group">
<label for="product" class="control-label mb-1">Product</label>
{{ form.product }}
</div>
<div class="form-group">
<label for="supplier" class="control-label mb-1">Supplier</label>
{{ form.supplier }}
</div>
<div class="form-group">
<label for="part" class="control-label mb-1">Part Name</label>
{{ form.part }}
</div>
</form>
You will have to write "__ str __"(without spaces between str and __) method for model 'Part'
def __str__(self):
return '{}, quantity - {}'.format(self.partname, self.quan)
Check this post also: What is doing __str__ function in Django?
I need to get the data from a form in a Django database. The problem when I use .cleaned_data['name'] I am getting an attribute error
'SnippetForm' object has no attribute 'cleaned_data'.
when I tried passing through if old_form.is_valid(), the if is False.
With my code, I can get the HTML info, but I can not parser it with .clean_data.
Basically I don't want to create a regex and parse the html, I am looking for some Django Method that can help.
Html code got from Django:
<tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" value="Ariel" maxlength="100" id="id_name"></td></tr>
<tr><th><label for="id_email">Email:</label></th><td><input type="email" name="email" value="as#onsemi.com" maxlength="254" id="id_email"></td></tr>
<tr><th><label for="id_subject">Subject:</label></th><td><input type="text" name="subject" value="Test" maxlength="100" id="id_subject"></td></tr>
<tr><th><label for="id_body">Body:</label></th><td><textarea name="body" cols="40" rows="10" id="id_body">
This is a test</textarea></td></tr>
In my views.py
def data_detail (request, request_id):
data_detail_django = get_object_or_404(Snippet, pk=request_id)
if request.method == "POST": #Also, it is not going throu this if...
old_form = SnippetForm(request.POST, instance=data_detail_django)
else: #The old_form is the html output and is get it with this
old_form = SnippetForm(instance=data_detail_django)
if old_form.is_valid():
print(old_form.cleaned_data['name'])
return HttpResponse("contact view")
In my models
from django.db import models
# Create your models here.
class Snippet(models.Model):
name = models.CharField(max_length=100, blank=True, null=True)
email = models.EmailField(blank=True, null=True)
subject = models.CharField(max_length=100, blank=True, null=True)
body = models.TextField(blank=True, null=True)
def __str__(self):
return self.name
in my form.py
from django import forms
from .models import Snippet
class SnippetForm(forms.ModelForm):
class Meta:
model = Snippet
fields = ('name', 'email','subject', 'body')
The solution was: Uning .objects.get(pk = vaule)
def data_detail (request, request_id):
data_dbs = Snippet.objects.get(pk= request_id)
data_out = {'data_dbs': data_dbs}
return render(request, 'form_app/detail.html', data_out )
and in the html to render:
{% extends 'form_app/base.html' %}
{% block main_content %}
{% if data_dbs %}
<p>Name: {{data_dbs.name}}</p>
<p>Email: {{data_dbs.email}}</p>
<p>Subject: {{data_dbs.subject}}</p>
<p>Body: {{data_dbs.body}}</p>
{% else %}
<p> No data</p>
{% endif %}
<a href = '/data'><b>See Form</b></a></li>
{% endblock %}
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")