how to get new line in __repr__() in python flask? - html

I made the comment section for my blog page, but the problem is it showing name and comment in a single line and I want both these in different lines. and \n is not working.
class comments(db.Model):
__tablename__ = 'comment'
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.Text)
comm = db.Column(db.Text)
def __init__(self,name,comm):
self.name = name
self.comm = comm
def __repr__(self):
return f" Name: {self.name} Comment: {self.comm}"
function
#app.route('/fat', methods=['GET','POST'])
def fat():
form = AddForm()
if form.validate_on_submit():
name = form.name.data
comm = form.comm.data
newname = comments(name,comm)
db.session.add(newname)
db.session.commit()
return redirect(url_for('fat'))
new = comments.query.all()
return render_template('fat.html',form=form, newnames=new)
the code for fat.html is attached below......................................................................................................................................................
</div>
{% block content %}
<div class="post comment">
{% for co in newnames %}
<li>{{co}}</li>
{% endfor %}
</div>
<div class="myform">
<h2>Leave a Comment</h2>
<form method="POST">
{{ form.hidden_tag() }}
<div class="myforms">
<h1 class="myform1"> {{ form.name.label }}</h1>
<h1 class="myform2"> {{ form.name() }} </h1>
</div>
<div class="myformss">
<h1 class="myform3"> {{ form.comm.label }} </h1>
<h1 class="myform4"> {{ form.comm()}}</h1>
</div>
<div class="myformsss">
<h1 class="myform5"> {{ form.submit() }} </h1>
</div>
</form>
</div>
{% endblock %}

It's not that flexible to do the HTML content layout in the backend. The display style should be decided on the front end. I mean, you should modify your fat.html.
If you need my help. Modify your question and paste out the content of fat.html.
Update:
<div class="post comment">
{% for co in newnames %}
<li>Name: {{ co.name }}</li>
<li>Name: {{ co.comm }}</li>
{% endfor %}
</div>
Here's a simple example. You can access the Comment object just like what you do in Python.
You may need to change the css style to indent the comments block and make it align with the other blocks.

Related

Django multiple images for post to render

For the past few days I have been trying to give access to the admin user to upload multiple images/slides for every single post, one idea I had in mind was nesting a for loop inside the posts for loop that for every post, render also every image associated with it but it seem's I cant get it quite right.
class Post(models.Model):
title = models.CharField(max_length = 128)
image = models.ImageField(default = 'default.jpg', upload_to = 'post_pics')
content = models.TextField()
date_posted = models.DateTimeField(default = timezone.now)
category = models.ForeignKey(Category, on_delete = models.CASCADE)
def __str__(self):
return f"{self.title} - {self.category}"
def get_image_filename(instance, filename):
title = instance.post.title
slug = slugify(title)
return "post_images/%s-%s" % (slug, filename)
class Images(models.Model):
post = models.ForeignKey(Post, default= None, on_delete = models.CASCADE, related_name= 'Images')
image = models.ImageField( upload_to = get_image_filename, verbose_name = 'Images')
def __str__(self):
return f"imazh per {self.post}"
and my Html:
<div class="post-list-container">
{% for post in posts %}
<article class="post-container">
<div class="post-top">
> Focus on the for loop here
{% for post.Images in post.Images %}
<img src="{{ post.Images.url }}">
{% endfor %}
<div class="post-title"><h1>{{ post.title }} </h1></div>
<div class="post-images">
<img class="rounded" src="{{ post.image.url }}">
</div>
</div>
<div class="post-middle">
<div class="post-content"><p> {{ post.content }}</p> </div>
</div>
<div class="post-bottom">
<div class="post-category"><h2>{{ post.category }}</h2>
</div>
<div class="post-date_posted"><h1>{{ post.date_posted|date:"F d, Y" }}</h1>
</div>
</div>
</article>
{% endfor %}
</div>
Is there any way to render those images this way?
A Post will have a related set, which is what you refer to that reverse relationship as.
By default, django will make the relationship on a Post instance images_set because it takes your model name on the relationship & adds _set.
You can also choose your own related name by setting the related_name attribute on the FK field. (docs)
Here's an example;
class Map(models.Model):
members = models.ManyToManyField(
User,
related_name='maps',
verbose_name=_('members')
)
# Reverse relationship:
User.maps.all()
Or in python using your models;
post = Post.objects.first()
print(f"Images in post {post.title}")
for image in post.images_set.all():
print(image.url)
So without a custom related_name, your template loop would be something like;
{% for image in post.images_set.all %}
<img src="{{ image.url }}">
{% empty %}
<p>No images found</p>
{% endfor %}

How do I include the same partial multiple times with different content using Nunjucks?

I have a few page templates which need to include the same partial numerous times but with different content. I've had a look at looping this, however, they're not necessarily going to be in the concurrent order.
For example my page template will look like this
{% extends "layout.html" %}
{% set page = inner %}
{% block content %}
{% include "partials/image-text-block.html" %}
{% include "partials/example-block.html" %}
{% include "partials/image-text-block.html" %}
{% endblock %}
With my include file looking like
<div class="col-12 col-sm-6 col-sm-offset-1 image-text__copy">
<h2 class="navy">{{ page.imageText.title }}</h2>
<p class="light-body">{{ page.imageText.text }}</p>
<div class="button-wrap">
{{ page.imageText.buttonText }}
</div>
</div>
I'm currently using a json file to inject the content.
"inner": {
"imageText": {
"imageSide": "left",
"text": "dsauhf oaiuoags f"
}
}
What would be the best way to provide different content to each include please?
Thanks in advance!
try using setting different variable values
Input:
{% set sectionHeader = { title: 'Title 1', subtitle: 'Subtitle 1' } %}
{% include "_partials/section-header.html" %}
{% set sectionHeader = { title: 'Title 2', subtitle: 'Subtitle 2' } %}
{% include "_partials/section-header.html" %}
_partials/section-header.html
<header class="section-header">
<h3 class="section-title">{{sectionHeader.title}}</h3>
<p class="section-subtitle">{{sectionHeader.subtitle}}</p>
</header>
Output:
<header class="section-header">
<h3 class="section-title">Title 1</h3>
<p class="section-subtitle">Subtitle 1</p>
</header>
<header class="section-header">
<h3 class="section-title">Title 2</h3>
<p class="section-subtitle">Subtitle 2</p>
</header>
or you could use macros
article.njk
{% macro articleMacro(title) %}
<article>
<header>{{title}}</header>
<p>article body</p>
<footer></footer>
</article>
{% endmacro %}
page.njk
{% import "article.njk" as article %}
{{ article('header one') }}
{{ article('header two') }}

Language choice affects text overflow in html(bootstrap) (Django)

I'm using bootstrap to implement my post detail page.
It works well and fit perfectly into tho format when using Korean.
But, if I wrote english contents, it overflow the format.
What's wrong with it?
Here is the code :
models.py
from django.db import models
from django.core.urlresolvers import reverse
from django.conf import settings
def upload_location(instance, file_name):
return "{}/{}".format(instance.author.username, file_name)
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
content = models.TextField()
image = models.ImageField(upload_to=upload_location, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('-created_at',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse(
"posts:detail",
kwargs={
"pk": self.id,
}
)
def get_image_url(self):
if self.image:
return self.image.url
return "http://placehold.it/300x200"
post_detail.html
{% extends 'chacha_dabang/skeleton/base.html' %}
{% load pipeline %}
{% block content %}
<div class="container">
<section class="post-content-section">
<h2> {{ post.title }} </h2>
<h5 style="text-align: right;"> {{ post.created_at }} </h5>
<hr class="thin">
<img src="{{ post.get_image_url }}" alt="image">
<p> {{ post.content }} </p>
</section>
</br>
<hr class="thin">
</br>
<section id="comment-section" data-post-id={{ post.pk }}>
<h3> 댓 글 (<span id="comment-count"></span>)</h3>
<ul>
</ul>
<form method="POST" action="">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
</section>
</div>
{% endblock %}
{% block custom_js %}
{% javascript "comments" %}
{% javascript "message" %}
{% endblock %}

Shopify discount code specific message to be displayed

I want to apply discount code specific messages on the shopify email templates. I tried the following code, it's showing me error - "Liquid error: Unknown operator = " in the purchase email which I receive.
<div class="row">
<div class="left-column">
{% if discounts %}Discount (code: {{ discounts.first.code }})
</div>
<div class="right-column">
{{ discounts_savings | money_with_currency }}
{% endif %}
</div>
<div class="left-column">
{% for discount in discounts %}
{% if discount.first.code = "DISCODE-2015" %}
Your $50 amazon.com gift card will be send to you soon!
{% endif %}
{% endfor %}
</div>
</div>
You are using =, but it should be ==. See here.
I think you also want discount.code where you have discount.first.code.
Try replacing this line:
{% if discount.first.code = "DISCODE-2015" %}
with this:
{% if discount.code == "DISCODE-2015" %}

Django: How to access the label and checkbox separately in CheckboxSelectMultiple?

I would like to make each checkbox into a toggle button. However, Django renders the checkboxes automatically as a list. I couldn't any way to make them separate.
this is what I have right now:
<div class="column">
<div id="filters">
{% for field in filter_form %}
<div class="filter_category">
{% for checkbox in field %}
{{ checkbox }}
{% endfor %}
</div>
{% endfor %}
</div>
I would like something such as this so I have more flexibility with what I can do.
<div class="column">
<div id="filters">
{% for field in filter_form %}
<div class="filter_category">
{% for checkbox in field %}
{{ checkbox.label }}{{ checkbox.tag }}
{% endfor %}
</div>
{% endfor %}
</div>
This is my form class, the constructor simply populates the choices for each of the fields
class Class_filters_form(forms.Form):
subject_code = forms.CharField(widget=forms.CheckboxSelectMultiple(attrs={"checked": ""}))
subject_level_CLB = forms.CharField(widget=forms.CheckboxSelectMultiple(attrs={"checked": ""}))
subject_level_CEFR = forms.CharField(widget=forms.CheckboxSelectMultiple(attrs={"checked": ""}))
time_start = forms.TimeField(widget=forms.CheckboxSelectMultiple(attrs={"checked": ""}))
campus = forms.CharField(widget=forms.CheckboxSelectMultiple(choices=Data_room.CAMPUS_CHOICE, attrs={"checked": ""}))
def __init__(self, *args, **kwargs): ...