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?...
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)
I'm begginer in Python and Django. I'm trying to write simple Property management System. I've got problem with asigning existing house association to new property entry. My files:
models.py
class Property(models.Model):
# Fields
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=45, blank=False) # Property name
address = models.CharField(max_length=198, blank=False) # Property address
postalcode = models.CharField(max_length=6, blank=False) # Property postalcode
city = models.CharField(max_length=45, blank=False) # Property city
kw_number = models.CharField(max_length=15, blank=True) # Numer KW
ha_choice = models.CharField(max_length=2, choices=[(i.pk, i.name) for i in HousingAssociation.objects.all()])
# Foreign Keys
# TODO zmiana on_delete na inny!
house_association = models.ForeignKey(HousingAssociation, on_delete=models.CASCADE)
# Metadata
class Meta:
ordering = ['id']
# Methods
def add(self):
self.save()
def __str__(self):
"""String for representing the MyModelName object (in Admin site etc.)."""
# return self.id, self.name, self.address, self.postalcode, self.city, self.kw_number
return self.name
forms.py
class PropertyForm(forms.ModelForm):
class Meta:
model = Property
fields = ('name', 'address', 'postalcode', 'city', 'ha_choice', 'kw_number')
views.py
def property_form_new(request):
if request.method == "POST":
form = PropertyForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'registration/prop/success.html')
else:
form = PropertyForm()
return render(request, 'registration/prop/prop_new.html', {'property_new': form})
In case of that django returns to me this:
screenshot
It means 'Choose the correct option. 14 is not among the valid values.' 14 is an id of existing entry in db and it's correct. The HTML source is like that:
<h2>Nowa nieruchomość</h2>
<form method="POST" class="post-form">
<input type="hidden" name="csrfmiddlewaretoken" value="wsrMCEU8UfLMHCBGHtKfcI1wZzGdqM8HpEAEyexx2OIDZue8Chi4DaJxsLYg7aHk">
<p><label for="id_name">Name:</label> <input type="text" name="name" value="BCh" maxlength="45" required id="id_name"></p>
<p><label for="id_address">Address:</label> <input type="text" name="address" value="Batalionów Chłopskich 1/18" maxlength="198" required id="id_address"></p>
<p><label for="id_postalcode">Postalcode:</label> <input type="text" name="postalcode" value="15-661" maxlength="6" required id="id_postalcode"></p>
<p><label for="id_city">City:</label> <input type="text" name="city" value="Białystok" maxlength="45" required id="id_city"></p>
<ul class="errorlist"><li>Wybierz poprawną wartość. 14 nie jest żadną z dostępnych opcji.</li></ul>
<p><label for="id_ha_choice">Ha choice:</label> <select name="ha_choice" required id="id_ha_choice">
<option value="">---------</option>
<option value="14" selected>Spółdzielnia1</option>
<option value="15">Spółdzielnia 2</option>
<option value="16">flatman</option>
<option value="17">Perspektywa</option>
<option value="18">ŁSM</option>
<option value="42">ŁSM</option>
<option value="43">ŁSM 43</option>
<option value="44">ŁSM</option>
<option value="45">ŁSM</option>
<option value="46">ŁSM</option>
<option value="47">ŁSM</option>
<option value="48">ŁSM</option>
<option value="49">Spółdzielnia Testowa 0</option>
</select></p>
<p><label for="id_kw_number">Kw number:</label>
<input type="text" name="kw_number" value="BI/1A/56743" maxlength="15" id="id_kw_number"></p>
<button type="submit" class="save btn btn-default">Save</button>
</form>
I tried with
class PropertyForm(forms.ModelForm):
ha_choice = models.ChoiceField(choices=[(i.pk, i.name) for i in HousingAssociation.objects.all()])
class Meta:
model = Property
fields = ('name', 'address', 'postalcode', 'city', 'ha_choice', 'kw_number')
and also with MultipleChoiceField but with no good effects. Can anybody help to find how to asign it correctly?
I found a solution. Very simple, just to change a field
ha_choice
in
class PropertyForm(forms.ModelForm):
class Meta:
model = Property
fields = ('name', 'address', 'postalcode', 'city', 'ha_choice', 'kw_number')
to
house_association
So simple.
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
I am working on a project in Django where two custom build user model is used.
Industry
Employee
Here every Industry user will entry some of their Employee's data, and later on Employee will verify and finish to create his account.
my models.py:
class myCustomeUser(AbstractUser):
id = models.AutoField(primary_key=True)
username = models.CharField(max_length=20, unique="True", blank=False)
password = models.CharField(max_length=20, blank=False)
is_Employee = models.BooleanField(default=False)
is_Inspector = models.BooleanField(default=False)
is_Industry = models.BooleanField(default=False)
is_Admin = models.BooleanField(default=False)
class Industry(models.Model):
user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='industry_releted_user')
name = models.CharField(max_length=200, blank=True)
owner = models.CharField(max_length=200, blank=True)
license = models.IntegerField(null=True, unique=True)
industry_extrafield = models.TextField(blank=True)
class Employee(models.Model):
user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='employee_releted_user', blank=True)
#industry = models.OneToOneField(Industry, on_delete=models.CASCADE, related_name='employee_releted_industry')
industry = models.ForeignKey(Industry, on_delete=models.CASCADE)
i_id = models.IntegerField(null=True, blank=False, unique=True)
name = models.CharField(max_length=200, blank=False, null=True)
gmail = models.EmailField(null=True, blank=False, unique=True)
rank = models.CharField(max_length=20, blank=False, null=True)
employee_varified = models.BooleanField(default=False, blank=True)
Now I wrote the following code in views.py to create an Employee's entry by Industry user when the Industry user signed in from their account:
#method_decorator(industry_required, name='dispatch')
class industryDetails(DetailView):
model = Industry
template_name = 'app/industryDetails.html'
def get_queryset(self):
return Industry.objects.filter(user=self.request.user)
def get_object(self):
return get_object_or_404(Industry, user=self.request.user)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['inserted_text'] = "inserted text from EmployeeDetails of views.py"
return context
def employeeRegister_byIndustry(request):
employeeRegister_dict={
'insert_me' : "hello this is extra inserted"
}
if request.method == "POST":
this_i_id = request.POST['i_id']
this_name = request.POST['name']
this_rank = request.POST['rank']
this_gmail = request.POST['gmail']
this_industry = self.request.user.industry_releted_user
employee_obj = Employee.objects.create(industry=this_industry, i_id=this_i_id, name=this_name, rank=this_rank, gmail=this_gmail)
employee_obj.save()
if employee_obj.is_valid():
print('valid employee Object')
return redirect('app:employeeSignup')
return render(request, 'app/employeeSignup.html', employeeRegister_dict)
and my template (industryDetails.html):
<div class="container-fluid">
<div class="row m-0">
<div class="col-xl-10 mx-auto">
<p>inserted text: {{ inserted_text }}</p>
<hr>
<h3>Username: {{ industry.user }}</h3>
<p>name: {{ industry.name }}</p>
<p>owner: {{ industry.owner }}</p>
<p>license: {{ industry.license }}</p>
<p>id: {{ industry.user.id }}</p>
<p>username: {{ industry.user.username }}</p>
<p>password: {{ industry.user.password }}</p>
</div>
</div>
</div>
<div class="my-5"></div>
<hr>
<div class="my-5"></div>
<div class="container-fluid">
<div class="row m-0">
<div class="col-xl-8">
</div>
<div class="col-xl-3">
<h3>Add new Employee</h3>
<form class="" action="{% url 'app:employeeRegister_byIndustry' %}" method="post">
{% csrf_token %}
<div class="form-group">
<label>Enter industrial id</label>
<input type="text" class="form-control" name="i_id" placeholder="Industrial id">
</div>
<div class="form-group">
<label>Enter employee name</label>
<input type="text" class="form-control" name="name" placeholder="Employee name">
</div>
<div class="form-group">
<label>rank</label>
<input type="text" class="form-control" name="rank" placeholder="rank">
</div>
<div class="form-group">
<label>Enter employee's gmail</label>
<input type="email" class="form-control" name="gmail" placeholder="gmail">
</div>
<button type="submit" class="btn btn-primary" name="button">Submit</button>
</form>
</div>
</div>
</div>
But here the Foreign Key assignment does not working as I want. How can I fix it?
self.request.user is a user model object, so in thus case a myCustomUser object, not an Industry object. You can access the related Industry object with:
this_industry = request.user.industry_releted_user
This is thus the name of the relation from Industry to myCustomUser in reverse, the name of that relation is determined by the related_name=… parameter [Django-doc].
I would also advise to make use of ModelForm [Django-doc] to validate and clean user input. A POST request can lack certain data or can be forged, so request.POST will for example not per see contain a value for name. A form makes it convenient to validate that all required data is present, check if the email address is indeed a valid email address, and convert data from a string-like object to a python object that is more specific to the model field.
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>