Unable to make Dynamic Django dependent dropdown - python

I am new to Django and I am struggling to make a dynamic Django dependent select dropdown for 'Categories', and I have been making a CRUD with Products having categories ,sub categories ,colors ,size
below is the code for my Products model:
from tkinter import CASCADE
from django.db import models
from rest_framework import serializers
# Create your models here.
CATEGORY_CHOICES = [('ninesixwear','9-6WEAR'),('desiswag','DESI SWAG'),('fusionwear','FUSION WEAR'),
('bridalwear','BRIDAL WEAR')]
class Products(models.Model):
Categories = serializers.ChoiceField(choices = CATEGORY_CHOICES)
sub_categories = models.CharField(max_length=15)
Colors = models.CharField(max_length=15)
Size = models.CharField(max_length=15)
image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True)
title = models.CharField(max_length=50)
price = models.CharField(max_length=10)
sku_number = models.CharField(max_length=10)
prod_details = models.CharField(max_length=300)
quantity = models.IntegerField(default=0)
isactive = models.BooleanField(default=True)

model file create Category field
class Category (models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(max_length=255, unique=True)
def __str__(self):
return self.name
class Meta:
verbose_name_plural= 'Categories'
viwe file query all category from database
def category(request):
categories = Category.objects.all()
html file code
<div class="col-md-12">
<label>Category</label>
<select name="category" class="form-control">
<option value="">select category</option>
{% for category in categories %}
<option value="{{category.id}}">{{category.name}}</option>
{% endfor %}
</select>
</div>
If you still don't understand then check this repo Github

Related

How to print data in template django of a diffrent table joined by foreign key?

Hello Everyone i have Two model first one is as following:
class Item(models.Model):
title = models.CharField(max_length=100)
price = models.FloatField()
bargainprice = models.FloatField(default=0)
discount_price = models.FloatField(blank=True, null=True)
category = models.CharField(choices=CATEGORY_CHOICES, max_length=2)
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
slug = models.SlugField()
description = models.TextField()
image = models.ImageField()
and i am getting this model data using the following view:
class ItemDetailView(DetailView):
model = Item
template_name = "product.html"
and in product.html i am accessing Item objects like this:
<span class="mr-1">
<del>₹ {{ object.price }}</del>
</span>
<span>₹ {{ object.discount_price }}</span>
{% else %}
<span> ₹ <span id="pp">{{ object.price }}</span></span>
and so on..
everything working fine up here. but problem arises when i created the following model:
class BargainModel(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
itemId = models.IntegerField()
bprice = models.FloatField()
i joined this with foreign key as mentioned.
**what i want to do is print the " bprice " in the product.html of the same user but i am not able to do it **
can anyone help me with this i am new to Django.
Thanks in advance
in this case you need to import User like
from django.contrib.auth.models import User
class BargainModel(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
itemId = models.ForeignKey(Item, on_delete=models.CASCADE)
bprice = models.FloatField()
in product.html you can call the model of BargainModel it also contains the Item with user
It is better to work with a ForeignKey since this will guarantee referential integrity. You thus shoudl define the BargainModel as:
from django.conf import settings
class Bargain(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
item = models.ForeignKey(
Item,
on_delete=models.CASCADE
)
bprice = models.FloatField()
class Meta:
constraints = [
models.UniqueConstraint(fields=['item', 'user'], name='unique_user_item')
]
In the DetailView, we can then look if there is a Bargain record for the given item and user with:
class ItemDetailView(DetailView):
model = Item
template_name = "product.html"
def get_bargain(self):
if self.request.user.is_authenticated():
return Bargain.objects.filter(item=self.object, user=request.user).first()
Then you can render this with:
{{ view.get_bargain.bprice }}
if there is a related Bargain, then it will show the corresponding bprice.
Note: Models normally have no Model suffix. Therefore it might be better to rename BargainModel to Bargain.

Html select POST Django

Hello i'm new to django.
I have a model that looks like this.
Models.py
class CustomUser(AbstractUser):
pass
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
def __str__(self):
return self.username
class Campus(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Intervention(models.Model):
subject = models.CharField(max_length=200)
begin_date = models.DateField(default=datetime.datetime.today)
end_date = models.DateField(default=datetime.datetime.today)
description = models.TextField(blank=True)
speaker = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
campus = models.ForeignKey(Campus, on_delete=models.CASCADE)
class Meta:
verbose_name = 'Intervention'
verbose_name_plural = 'Interventions'
def __str__(self):
return self.subject
class Evaluation(models.Model):
interventions = models.ForeignKey(Intervention, on_delete=models.CASCADE)
student_id = models.CharField(max_length=20)
speaker_knowledge_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)])
speaker_teaching_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)])
speaker_answer_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)])
slide_content_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)])
slide_examples_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)])
comment = models.TextField(blank=True)
class Meta:
verbose_name = 'Evaluation'
verbose_name_plural = 'Evaluations'
So, basically what i'm trying to do is on home page i want to have a select box where student have to choose his campus then he will be redirected to a new page where he can see only the interventions that belongs to the campus he choosed
My home page looks like this:
<form method="post" action="/Mark/"/>
<select name="campus_id">
<option value="" disabled selected>Choose your Campus</option>
{% for camp in campus %}
<option value="camp.pk">{{ camp.name }}</option>
{% endfor %}
</select>
<input type="submit" />
</form>
I tried several things but none worked :/ if anybody can help or give me a hint.
Thanks.
Best regards.
I would suggest you to have a clear idea and define the flow:
You have a view that displays the form to select the campus (alternatively you might have a list of links)
Create a view (ListView) that displays a table (list) of Interventions
Create a Django form with choices from your Campus model
The view (FormView) that will process this form would get the selected value and redirect to another view using the provided value (id).
List items provided by the Intervention display view (ListView) filtered (get_queryset) by the respective campus id

Django: Form template: Input fields but not choose existing fields for ManyToMany Relations

I am creating a website for users to upload images... here's the form page:
As from the screencap above, I cannot input any tags, I can only choose existing tags
My Question is: What to add to the code so that users can input at most 10 tags when they have to upload an image
models.py
class Image(models.Model):
owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.DO_NOTHING)
tag = models.ManyToManyField(Tag, blank=True, null=True)
title = models.CharField(max_length=100)
photo = models.FileField()
description = models.CharField(max_length=1000)
def __str__(self):
return self.title + '-' + self.description
class Tag(models.Model):
tag_name = models.CharField(max_length=50)
class ImageTag (models.Model):
image = models.ForeignKey(Image, blank=True, null=True, on_delete=models.DO_NOTHING)
tag = models.ForeignKey(Tag, blank=True, null=True, on_delete=models.DO_NOTHING)
urls.py
url(r'image/add/$', views.ImageCreate.as_view(), name='image-add'),
view.py
class ImageCreate (CreateView):
model = Image
fields = ['category', 'title', 'photo', 'description', 'tag']
image_form.html (I have deleted unrelated div)
<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'imagebank/form-template.html' %}
<button type="submit" class="btn btn-success">Submit</button>
</form>

Django Multiple ForeignKey Navigation

I'm building a shopping cart. In my shopping cart an item can be composed of other items. I need to display a set of items with their corresponding associated parts in a single template. I know how to show a single item with its corresponding parts in a template, but I can't seem to figure out how to show more than one item, each with its own list of included parts.
I have fiddled with every permutation of tags in the template file:
# checkout.html
{% for item in cart_items %}
<tr>
<td class="left">
{{ item.name }}
<ul>
{% for part in item.product.buildpart.part_set.all %}
<li>{{ part.name }}
{% endfor %}
</ul>
</td>
<td>${{ item.price }}</td>
<td>{{ item.quantity }}</td>
<td class="right">${{ item.lineItemTotal }}</td>
</tr>
{% endfor %}
Here is the vew that generates the template:
# views.py
def checkout(request):
cart_items = get_cart_items(request)
<snip>
return render(request, 'checkout.html', locals())
And here's the get_cart_items() function that returns all the items in the user's shopping cart:
# cart.py
def get_cart_items(request):
""" return all items from the current user's cart """
return CartItem.objects.filter(cart_id=get_cart_id(request))
Here's the CartItem model:
# models.py
class Item(models.Model):
cart_id = models.CharField(max_length=50)
quantity = models.IntegerField(default=1)
product = models.ForeignKey(PartModel, unique=False)
class Meta:
abstract = True
<snip>
class CartItem(Item):
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['date_added']
verbose_name = "Cart Item"
<snip>
The 'product' field is a ForeignKey to the PartModel model:
# models.py
class PartModel(models.Model):
family = models.ForeignKey(PartFamily)
name = models.CharField("Model Name", max_length=50, unique=True)
slug = models.SlugField(help_text="http://www.Knowele.com/<b>*slug*</b>",
unique=True)
<snip>
buildpart = models.ManyToManyField('self', through='BuildPart',
symmetrical=False, related_name='+')
class Meta:
ordering = ['name']
verbose_name = "Product Model"
<snip>
The PartModel model has a ManyToMany relationship with itself through the buildpart field and the BuildPart model to facilitate the notion of catalog items that can be composed of other catalog items:
# models.py
class Build(models.Model):
build = models.ForeignKey(PartModel, related_name='+')
part = models.ForeignKey(PartModel, related_name='+')
quantity = models.PositiveSmallIntegerField(default=1)
class Meta:
abstract = True
unique_together = ('build', 'part')
def __unicode__(self):
return self.build.name + ' with ' + str(self.quantity) + ' * ' + \
self.part.family.make.name + ' ' + self.part.name
class BuildPart(Build):
pass
class Meta:
verbose_name = "Build Part"
I can't seem to make the necessary ForeignKey traversals in the template (listed above) in order to get all the parts associated with the user's items in the CartItem model. Is it something I'm not doing right in the template or am I not packaging up the right QuerySets in my view?
The second part of this issue is that once I get those parts, I need them to show up in the order specified in the 'order' integer field of the PartType model:
# models.py
class PartType(models.Model):
name = models.CharField("Part Type", max_length=30, unique=True)
slug = models.SlugField(unique=True)
order = models.PositiveSmallIntegerField()
description = models.TextField(blank=True, null=True)
class Meta:
ordering = ['name']
verbose_name = "Product Type"
def __unicode__(self):
return self.name
class PartFamily(models.Model):
make = models.ForeignKey(PartMake)
type = models.ForeignKey(PartType)
name = models.CharField("Family Name", max_length=30,
unique=True)
slug = models.SlugField(unique=True)
url = models.URLField("URL", blank=True, null=True)
description = models.TextField(blank=True, null=True)
class Meta:
ordering = ['name']
verbose_name = "Product Family"
verbose_name_plural = "Product Families"
def __unicode__(self):
return self.name
So as you can see, in the PartModel model, the 'family' field is a ForeignKey to the PartFamily model, and in the PartFamily model the 'type' field is a ForeignKey to the PartType model, within which is the all-important 'order' field that the parts need to be ordered by.
I hope this makes sense and you can see why this is so complicated for a noob like me.
Just iterate on item.product.buildpart.all:
{% for item in cart_items %}
[...]
{% for part in item.product.buildpart.all %}
{{ part.name }}[...]
{% endfor %}
{% endfor %}

Problems with submit button in change_form template Django

im new with Django and Python, and im still confuse about how to prepopulate values from manytomany field related lookup as my question in Prepopulate tabularinline with value from related lookup in manytomany field
here is my model:
class Product(models.Model):
product_name= models.CharField(max_length=50)
price = models.DecimalField(max_digits=10, decimal_places=2, default=Decimal('0.00'))
tax_per_item = models.DecimalField(max_digits=10, null=True, blank=True, decimal_places=2, default=Decimal('0.00'))
discount_per_item = models.DecimalField(max_digits=10, null=True, blank=True, decimal_places=2, default=Decimal('0.00'))
class Order(models.Model):
produks = models.ManyToManyField(Product, verbose_name=u"Kode Produk")
no_customer = models.ForeignKey(Customer, null=True, blank=True, related_name='%(class)s_kode_cust')
def order_view(request):
if 'enter' in request.POST:
#response to tabular.html template
return HttpResponseRedirect('/admin/POS/Pemesanan/inline')
class Foo(models.Model):
product = models.ForeignKey(Product, editable=False)
pemesanan = models.ForeignKey(Order)
quantity = models.IntegerField()
price = models.IntegerField()
discount = models.IntegerField()
tax = models.IntegerField()
and here is my admin:
class PemesananAdmin(admin.ModelAdmin):
fieldsets = (
('Customer in Time (Person)', {
'fields': ('no_customer',),
}),
('Date', {
'fields' : ('date', 'delivery_date',),
}),
('Order Details', {
'fields' : ('produks',),
}),
)
search_fields = ['produks', 'no_customer']
raw_id_fields = ('produks', 'no_customer',)
related_lookup_fields = {
'fk': ['no_customer'],
'm2m': ['produks'],
}
inlines = [
FooInline,
]
class FooInline(admin.TabularInline):
model = Foo
template = 'admin/POS/Pemesanan/inline/tabular.html'
extra = 0
allow_add = True
and here is my change_form override template:
{% extends "admin/change_form.html" %}
{% block after_field_sets %}{{ block.super }}
<form action="" method="post">
<input type="submit" name="enter" value="Enter" />
</form>
{% endblock %}
But, still nobody can tell me how :(. (If you please response to my question on that page). And now, im confusing about 2 problems:
1. I want my submit button in change_form to redirect to change_form too a.k.a in the same page need no refresh page (not to change_list page or the actual submission).
2. How can i get instances of related lookup 'produks' fieldset (manytomany) from submit button so that i can access parent values (Class Product) and prepopulate all to tabularinline (Class Foo or intermediary class)?
FYI, submit button is below all fieldsets.
Anyone help me please :(. Thank you for your kindly responses :).
your problem is, that this
<form action="" method="post">
<input type="submit" name="enter" value="Enter" />
</form>
will just send your submit-button back to your server.
the form-tag needs to sorround every form-element.
just remove: <form action="" method="post"> and </form>
and it may work.
as i understand you correctly you want to display an order (Order) and its items (Foo)?
my naive solution would be:
class Product(models.Model):
...
class Order(models.Model):
products = models.ManyToManyField(Product, through='Item')
class Item(models.Model):
order = models.ForeignKey(Order)
product = models.ForeignKey(Product)
quantity = models.IntegerField()
...
and the admin could be as simple as this:
class ItemInline(admin.TabularInline):
model = Item
class OrderAdmin(admin.ModelAdmin):
inlines = (ItemInline,)
you need to test that, as i cant (actually)

Categories