How to access and make use of html data in django? - html

I am having a hard time figuring out the right logic for my problem, i have 3 models,
class Item(SmartModel):
name= models.CharField(max_length=64,help_text="Name for this item e.g Hamburger")
price=models.DecimalField(max_digits=9,decimal_places=2)
optionalitems = models.ManyToManyField('optionalitems.OptionalItemCategory',null=True,blank=True)
class OptionalItems(SmartModel):
"""Optional items that belong to an item e.g topping that belongs to a pizza"""
name = models.CharField(max_length=20, help_text="Item name.")
price = models.DecimalField(max_digits=9, decimal_places=2, null=True,blank=True)
class OptionalItemCategory(SmartModel):
"""Category to which optional items belong"""
title = models.CharField(max_length=20,help_text="Category name")
optional_items = models.ManyToManyField(OptionalItems)
in my template,
{%for optionalcategory in optionalcategories %}
<h5 id="blah"> {{ optionalcategory.title}} </h5>
{% for optionalitem in optionalcategory.optional_items.all %}
<ul>
<input type="radio" value="radio" name="optional" value="op"><li id="item_appearence">{{optionalitem.name}}<span> {{optionalitem.price}}</span></li><a/>
</ul>
{% endfor %}
{% endfor %}
So for example an Item like a burrito will have an OptionalItem steak or chicken.I am able to access the Item like so item = get_object_or_404(Item, pk=obj.id) but my problem is i cannot figure out how to capture the OptionalItem. I want to be able to access the OptionalItem, i want to obtain the value of the radio button and its attributes. its kind of tricky.

Your code is inconsistent and that makes it hard to read, understand and work with. Some advice, clean it up. Something like this:
class Category(models.Model):
name = models.CharField(max_length=200)
class Option(models.Model):
name = models.CharField(max_length=200)
price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True)
class Item(models.Model):
category = models.ForeignKey(Category)
name = models.CharField(max_length=200)
price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True)
options = models.ManyToManyField(Option)
Than you need a from and a view. As I interpret your question: you want a form to select a option for an Item. So the code below will render all options and the widget RadioSelect() lets the user select one item. But why use radiobuttons? If an Item has a relation to one Option, than the Item model should have a foreignKey not M2M!
Form:
class ItemForm(ModelForm):
options = forms.ChoiceField(widget=forms.RadioSelect())
class Meta:
model = Item
fields = ( 'options', )
View:
from django.shortcuts import render
from django.http import HttpResponseRedirect
def your_view(request, id):
item = Item.objects.get(pk=id) # Your item object.
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
options = form.cleaned_data['options']
# ...
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ArticleForm(instance=article)
return render(request, 'contact.html', {
'form': form,
})
Template:
{% for obj in item.options_set.all %}
{{ obj.name }} {{ obj.price }}
{% endfor %}
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
I dind't test the code. But this should get you started. The documentation is your friend:
https://docs.djangoproject.com/en/1.5/topics/forms/
https://docs.djangoproject.com/en/1.5/#forms

In your template, you can simply render the price. I'd write a method in the Item model, that formats the OptionalItems the way you like.
i.e.
class Item(SmartModel)
...
def get_optional(self):
return ','.join([a.optionalitems for a in self.optionalitems.all()])
Of course, you should change that method to have it format the way you'd like.
If you pass a queryset of Items to your template, you can do something like the following:
{% for item in items %}
Name: {{ item.name}}
Price: {{ item.price }}
Optional Items: {{ item.get_optional }}
{% endfor %}

Related

Loading specific foreign key attribute in Django Template

Devs,
I have a 2 Models and one of them have a foreign key attribute as a reference to the other. Now I am trying to view both objects in my Template.
class ItemDetailView(DetailView):
model = Item
template_name = "product.html"
def get_context_data(self, **kwargs):
context = super(ItemDetailView, self).get_context_data(**kwargs)
context['markets'] = Market.objects.all()
# And so on for more models
return context
In my template I just want the exact market for my product
I tryed something like this:
{% for market in markets %} // or {% for object.market in markets %}
{% if market.market == object.market %}
>> Do smth if conditions match <<
{% endif %}
{% endfor %}
In the loop I get strings like x1, x2, x3 and object.market have the value x1.
So I just want to output the object for the corresponding market.
But if I check {% if market.market == object.market %} the conditions somehow don't match. When I print them out inside the loop I get x1,x2,x3,... for market.market and x1,x1,x1,... for object.market
These are my models:
class Market(models.Model):
market = models.CharField(max_length=30)
branch = models.CharField(choices=BRANCH_CHOICES, max_length=1)
image = models.ImageField(blank=True)
slug = models.SlugField(blank=True)
def __str__(self):
return self.market
def get_absolute_url(self):
return reverse("core:market-product-list", kwargs={
'slug': self.slug
})
class Item(models.Model):
title = models.CharField(max_length=100)
market = models.ForeignKey(Market, related_name='children', on_delete=models.CASCADE, blank=True, null=True)
price = models.FloatField()
discount_price = models.FloatField(blank=True, null=True)
category = models.ForeignKey(ItemCategory, related_name='children', on_delete=models.CASCADE, blank=True, null=True)
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
slug = models.SlugField()
path = models.CharField(default='/market-product-list/', max_length=100)
description = models.TextField()
image = models.ImageField()
I just solved the issue. The problem was that object.market is interpreted as an object not as a string. So it was impossible to check the conditions in the if-clause. I managed to output the corresponding market with converting the object to a string like this:
At first:
{% if object.market|slugify|capfirst == market.market %}
and then changed it to simply
{% if object.market == market %}
which is obviously the better solution
PS: I also learned that this is bad programming I should not filter in a Template but I am new to Django and I am glad that things are working now :)
Just call the field for the particular market as in the model.
{% for market in markets %} // or {% for object.market in markets %}
{% if market.market == object.market %}
{{ market.fieldname }}
{% endif %}
{% endfor %}
Why don't you loop through Product(Item) objects?

Auto complete Flask wtforms

I want to auto-update my total amount field using quantity and item price? is there any way to do it using a flask without javascript? I want the total amount to be updated while typing quantity and item price.
class ItemForm(FlaskForm):
item = StringField('Item')
quantity=IntegerField('Quantity')
item_price=IntegerField('Item Price')
class Meta:
csrf = False
class CostumerForm(FlaskForm):
costumer_name=StringField('Costumer Name: ')
item_detail = FieldList(FormField(ItemForm), min_entries=1)
add_item = SubmitField(label='Add Item')
remove_item = SubmitField(label='Remove Item')
total_amount=IntegerField('Total Amount')
paid_amount=IntegerField('Paid Amount')
submit=SubmitField('Submit')
proceed=SubmitField('Proceed')
#app.route('/costumer',methods=['GET','POST'])
#login_required
def costumer():
form=CostumerForm()
if form.add_item.data:
form.item_detail.append_entry()
return render_template('costumer.html', form=form)
if form.remove_item.data:
form.item_detail.pop_entry()
return render_template('costumer.html', form=form)
if form.validate_on_submit():
item=breakdown(form.item_detail.data)[0]
quantity=breakdown(form.item_detail.data)[1]
item_price=breakdown(form.item_detail.data)[2]
amount=breakdown(form.item_detail.data)[3]
total_amount=breakdown(form.item_detail.data)[4]
remaning_amount=total_amount-form.paid_amount.data
sales=Costumer(admin_id=current_user.id,item_id=item,
costumer_name=form.costumer_name.data,quantity=quantity,
item_price=item_price,amount=amount,total_amount=total_amount,
paid_amount=form.paid_amount.data,remaning_amount=remaning_amount)
db.session.add(sales)
db.session.commit()
return redirect(url_for('salesvoucher'))
return render_template('costumer.html',form=form)
costumer.html
Sales
{{form.hidden_tag()}}
{{form.costumer_name.label}}{{form.costumer_name(class='form-control input-group-ig',placeholder='Costumer Name')}}
Item
Quantity
Item Price
{% for field in form.item_detail %}
{% for f in field%}
{{ f(class='form-control') }}
{% endfor %}
{% endfor %}
{{ form.add_item(class='btn btn-primary') }} {{ form.remove_item(class='btn btn-danger') }}
{{form.proceed(class='btn btn-primary')}}
```
no way. even when you're updating in only on the frontend, you must use javascript.

How to create a form for feeding multiple object entries based on a query in django?

I am currently working on my college management application, where staff can enter internal marks of students and the student can view their marks. What i am stuck with is, i want a populate a list of forms to fill the internal marks of each student and submit it at once.
I tried modelformset with the code below and it work exactly as below
formset = modelformset_factory(Internal, fields=('student','marks1','marks2','marks3'))
if request.method == "POST":
form=formset(request.POST)
form.save()
form = formset()
return render(request, 'console/academics/internals.html',{'form':form})
For the model
class Internal(models.Model):
student = models.ForeignKey(User, on_delete=models.CASCADE)
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
marks1 = models.IntegerField(default=0)
marks2 = models.IntegerField(default=0)
marks3 = models.IntegerField(default=0)
marks = models.IntegerField(default=100)
marksob = models.IntegerField(default=0)
def save(self):
self.marksob = (self.marks1 + self.marks2 + self.marks3)/15
return super(Internal, self).save()
I want the form to be rendered in html using <input> and not passing {{form}} in html. And moreover I want the form to display only the entries of particular students based on a query. Can anyone help me on this?
I want the form to display only the entries of particular students based on a query.
As stated in the docs, you can specify a queryset for your formset:
formset = modelformset_factory(Internal, queryset=Internal.Objects.filter(...), fields=('student','marks1','marks2','marks3'))
I want the form to be rendered in html using and not passing {{form}} in html
You can do that by iterating over fields, just like normal forms:
<form method="post"> {% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
{% for field in form %}
{{ field.label_tag }} {{ field }}
{% endfor %}
{% endfor %}
</form>
More details at using the formset in the template.
Edit
If you want to use custom css classes for your form fields, you can do:
<form method="post"> {% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
<div class="...">
{{ form.marks1.errors }}
<label for="{{ form.marks1.id_for_label }}">Your email address:</label>
<input type="number" name="{{ form.marks1.name }}" value="{{ form.marks1.value }}" class="css-class">
</div>
<!-- and for other fields as well -->
{% endfor %}
</form>

How to hyperlink data from database on django

I am trying to build a simple search function on django that leads me to the link when I click on it. (I know API links are JSON links so clicking on them gives you no output of value but the point is to be able to click on them)
i tried using but it doesn't work
from my results.html:
{% for dataset in datasets %}
<br/>
{{ dataset.datasets_available }}
<br/>
{{ dataset.data_source }}
<br/>
{{ dataset.brief_description_of_datasets }}
<br/>
{{ dataset.country }}
<br/>
<a href='https://www.google.com'>{{ dataset.api_documentation }}<a>
<br/> #^ is the part i wanna fix
<br/>
{% endfor %}
{% else %}
<p style="font-family:Cambria">No search results for this query</p>
{% endif %}`
from views.py:
def results(request):
query = request.GET.get('q')
if query:
datasets = api_data.objects.filter(Q(datasets_available__icontains=query))
context = {
'datasets': datasets,
}
return render(request, 'Search/results.html', context)
from models.py:
class api_data(models.Model):
data_source = models.TextField()
brief_description_of_data = models.TextField()
datasets_available = models.TextField()
brief_description_of_datasets = models.TextField()
country = models.TextField()
api_documentation = models.TextField()
class Meta:
verbose_name_plural = "api_data"
api_documentation is currently urls in strings. i want to be able to click on the output in html and view the actual website
I'm not sure what you're trying to do, but if the website URL is in the api_documentation field, then you need to make this field the href of your html anchor.
Something like this:
<a href='{{ dataset.api_documentation }}'>{{ dataset.api_documentation }}</a>

How to pass foreign key in a hierarchical url in django?

I have a hierarchy within my Django App. I want to achieve the following:
First show several boards
Then, if the user clicks on one board, I want to display all topics within the board.
Now the problem is that I have declared a foreign key within the Topic model, but now the topic can be called from each of the boards, not only from within the one I assigned it to.
Here my models:
from django.db import models
from django.contrib.auth.models import User
from mptt.models import TreeForeignKey
# overview over all topics
class Board(models.Model):
name = models.CharField(max_length=30, unique=True)
description = models.CharField(max_length=100)
def __str__(self):
return self.name
# topics withing the boards
class Topic(models.Model):
board = TreeForeignKey(Board, on_delete=models.CASCADE, related_name='Topic')
subject = models.CharField(max_length=255, unique=True)
last_updated = models.DateTimeField(auto_now_add=True) # auto_now_add sets current date+time when created
starter = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Topic')
def __str__(self):
return self.subject
Then the views:
from .models import Board, Topic
class BoardsView(generic.ListView):
template_name = 'dbconnect/board.html'
context_object_name = 'board_list'
def get_queryset(self):
""" Return all boards."""
return Board.objects.all()
class TopicView(generic.ListView):
model = Topic
template_name = 'dbconnect/topic.html'
context_object_name = 'topic_list'
def get_queryset(self):
"""Return all topics."""
return Topic.objects.all()
The board.html works fine, since there is no second level in the url:
<div style = "text-align: left; margin-left: 10%; margin-right: 10%">
<div style = "display: inline-block; text-align: left;">
{% if board_list %}
<ul>
{% for board in board_list %}
<li>{{ board.name }}</li>
{% endfor %}
</ul>
{% else %}
<p>No boards are available.</p>
{% endif %}
</div>
But then comes topic.html and now I'm lost, what to pass, so that the topic refers to the board:
<div style = "text-align: left; margin-left: 10%; margin-right: 10%">
<div style = "display: inline-block; text-align: left;">
{% if topic_list %}
<ul>
{% for topic in topic_list %}
<li>{{ topic.subject }}</li>
{% endfor %}
</ul>
{% else %}
<p>No topics are available.</p>
{% endif %}
</div>
Here you can see my urls:
app_name = 'dbconnect'
urlpatterns = [
path('', views.BoardsView.as_view(), name = 'board'),
path('<int:topic>/', views.TopicView.as_view(), name='topic'),
path('<int:topic>/<int:level>/', views.LevelView.as_view(), name='level')]
How could I achieve that to show the restricted topic list inside each board?
The URLs
If I understand your question correctly, you should probably adapt your URLs to fit the case you describe:
urlpatterns = [
...
path('<int:board_id>/', views.TopicView.as_view(), name='topic-list'),
...
]
The first URL can stay the same, but the second URL gets the board_id as URL parameter, not the topic_id, since you want to display a list of topics belonging to the selected board.
And maybe rename that URL from topic to topic-list or something similar to be clearer what it is about.
Now, filtering inside the view:
You can filter your topic queryset like this:
class TopicView(generic.ListView):
model = Topic
...
def get_queryset(self):
return super().get_queryset().filter(board=self.kwargs['board_id'])
You can use super().get_queryset() there as you already defined model = Topic on the class; see the docs.
See this post for a similar case.