Turbo-flask turbo.push when button is submitted - flask

I am using WTForms and turbo-flask
I have a template which I want to change
<div>
{% if data is defined %}
{% for item in data %}
<div id="load" class="col-12 col-sm-6 offset-md-0 col-md-6 col-lg-4 col-xl-3 p-1 p-md-2">
<div class="card rounded p-1 d-flex flex-column h-100">
<div class="card-body p-1">
<h5 class="card-title">{{item._source.judgment_name}}</h5>
<h6 class="card-subtitle mb-2 text-muted">{{item._source.justice_kind_name}}</h6>
<p class="card-text">{{item._source.court_name}}</p>
<p class="card-text">{{item._source.adjudication_date}}</p>
{{item._id}}
{{item._source.cause_num}}
</div>
</div>
</div>
{% endfor %}
{% endif %}
</div>
And where I include it
<div class="container">
<div class="row px-2 pt-0">
{% include "test.html" %}
</div>
</div>
#app.route('/', methods=['GET', 'POST'])
def main():
form = SearchForm()
if form.is_submitted():
resp = es.search(index="test", query={"match_all": {}})
data = resp['hits']['hits']
turbo.push(turbo.replace(render_template("test.html", data=data), 'load'))
else:
return render_template('home.html', form=form)
When I use this script it doesn't want to work. Do you have any idea how to fix it?

I solved this. Here working code
in app.route function
if turbo.can_stream():
return turbo.stream(
turbo.replace(render_template('doc_cards.html', data=data), target='load_cards'))
else:
return render_template('home.html', form=search_form, data=data)
On page where content will be updated
<div class="container">
{% with data=data %}
{% include "doc_cards.html"%}
{% endwith %}
</div>
and dynamic content
<div id="load_cards" class="container">
{% if data is defined %}
{% for item in data %}
.......
{% endfor %}
{% endif %}
</div>

Related

why link is not working in html and how to solve it?

When i click a 'add to cart' button, it shows a blank page instead of cart page.
product.html
<a class="btn btn-secondary" href="{% url 'cart:add_cart' product.id %}">Add to Cart</a>
cart.views
def add_cart(request, product_id):
product = Product.objects.get(id=product_id)
try:
cart = Cart.objects.get(cart_id=_cart_id(request))
except Cart.DoesNotExist:
cart = Cart.objects.create(cart_id=_cart_id(request))
cart.save()
try:
cart_item = CartItem.objects.get(product=product, cart=cart)
if cart_item.quantity < cart_item.product.stock:
cart_item.quantity += 1
cart_item.save()
except CartItem.DoesNotExist:
cart_item = CartItem.objects.create(
product=product,
quantity=1,
cart=cart
)
cart_item.save()
return redirect('cart:cart_detail')
Your URL is probably not concatenated correctly. Try to debug your URL that should be in the "href" attribute, and you will see that there is probably some mistake.
In your main.urls, just add namespace in cart include.
let's add:
main.urls:
path('cart/',include('cart.urls',namespace='cart')),
OR
If above code doesn't work, try below code.
path('cart/',include(('cart.urls','url'),namespace='cart')),
And now this will work:
href="{% url 'cart:add_cart' product.id %}">
And see if it solves
this is the result when i click the button
product.html
{% extends 'base.html' %}
{% load static %}
{% block metadescription %}
{{ product.description|truncatewords:155 }}
{% endblock %}
{% block title %}
{% if category %}
{{ product.name }} -A&A store
{% endif %}
{% endblock %}
{% block content %}
<div class="row my_prod_row_class"
<div class="mx_auto">
<p>Home|{{product.category}}|{{product.name}}</p>
</div>
<div class="container">
<br>
<div class="row">
<div class="col-12 col-sm-12 col-md-12 col-lg-6 text-center ">
<div style="min-width:18rem">
<img src="{{product.image.url}}" alt="{{product.name}}">
</div>
</div>
<div class="col-12 col-sm-12 col-md-12 col-lg-6">
<div>
<h1 class="my_prod_title">{{product.name}}</h1>
<p>{{product.price}}$</p>
<p class="my_title">product Description </p>
<p class="text-justify my_prod_text">{{product.description}}</p>
{% if product.stock <= 0 %}
<p class="text-justify my_prod_text"><b>Out of stock </b></p>
{% else %}
<a class="btn btn-secondary" href="{% url 'cart:add_cart' product.id %}">Add to Cart</a>
{% endif %}
</div>
</div>
</div>
</div>
{% endblock %}

how to put my form in line orientation (horizontal). django forms

I want to put my form in horizontal.I tried to do this, but it got unformatted and disorganized
MY HTML:
<div class="tab-pane fade container-fluid p-2" id="profile" role="tabpanel"
aria-labelledby="profile-tab">
<h6 class="m-0 font-weight-bold text-primary">Horas Adicionais</h6>
<div class="row mt-4">
<div class="col">
{{ form_funcionarioadicional.management_form }}
{% for fa in form_funcionarioadicional %}
<div class="faform row">
<div class="col">
{{fa}}
</div>
</div>
{% endfor %}
</div>
</div>
</div>
currently it is like this, I wanted to leave it horizontal
How can I fix this in html, or in forms.py?
You can iterate form like this with col class of Bootstrap...
views.py
def Demoview(request):
form = DemoForm()
context = {'form':form}
return render(request,'index.html',context)
form.py
class DemoForm(forms.ModelForm):
class Meta:
model = DemoClass
fields = "__all__"
widgets = {
'field1':forms.TextInput(attrs={'class':'form-control','placeholder':'Field1'}),
'field2':forms.NumberInput(attrs={'class':'form-control','placeholder':'Field2'}),
'field3':forms.EmailInput(attrs={'class':'form-control','placeholder':'Field3'}),
'field4':forms.TextInput(attrs={'class':'form-control','placeholder':'Field4'}),
}
HTML Code
{% block body %}
<div class="container-fluid">
<div class="row">
{% for fm in form %}
<div class="col-6">
<label >{{fm.label}}</label>
{{fm}}
</div>
{% endfor %}
</div>
</div>
{% endblock body %}
Output

why when I click a different user returns me back to the current request user?

sorry, I had to take some screenshots to explains what is going on with me. now, I have much profile that has many different users and when I log in with one of it I'll assume the username is: medoabdin like you find on the screenshot now (medoabdin) and the name of it is (Origin) for me is a current user request. so, now I have also many different questions created by the different users, and when I want to enter any other profile let's suppose the user is (abdelhamedabdin) by current request user it returns me back to the current request (medoabdin) and not returns me back to abdelhamedabdin.
however, when I check the link URL I find the link is correct and when I log in with (abdelhamedabdin) user I see the same thing occurs to me against (medoabdin) so, can anyone tell me what is going on guys?
these are screenshots:
current request (medoabdin),
several questions,
show the link url for different users,
accounts/profile.html
{% extends 'base.html' %}
{% block title %} {{ user.first_name }} {{ user.last_name }} Profile {% endblock %}
{% block body %}
<!-- User Profile Section -->
{% if user.is_authenticated %}
<div class="profile">
<div class="container-fluid">
<div class="col-md-1">
<div class="thumbnail">
<div class="row">
<div class="col-xs-12">
<!-- Profile View Section -->
<div class="logo-image text-center">
{% if user.userprofile.logo %}
<div class="my-image">
{% if request.user.username == user.userprofile.slug %}
<a href="{% url 'accounts:user_image' user.userprofile.slug %}">
<img class="img-responsive" src="{{ user.userprofile.logo.url }}">
</a>
<span>
<a href="{% url 'accounts:add_avatar' user.userprofile.slug %}" class="fa fa-camera fa-1x text-center">
<p>Upload Image</p>
</a>
</span>
{% endif %}
</div>
{% else %}
{% load static %}
<div class="my-image">
<img class="img-responsive img-thumbnail" src="{% static 'index/images/default-logo.jpg' %}">
<span>
<a href="{% url 'accounts:add_avatar' user.userprofile.slug %}" class="fa fa-camera fa-1x text-center">
<p>Upload Image</p>
</a>
</span>
</div>
{% endif %}
{% if user.first_name != '' and user.last_name != '' %}
<h4>{{ user.first_name }} {{ user.last_name }}</h4>
{% else %}
<h4>User Profile</h4>
{% endif %}
</div>
</div>
<div class="col-xs-12">
<div class="caption">
<ul class="nav nav-pills nav-stacked">
<li role="presentation" class="active">Overview</li>
<li role="presentation" class="">Personal Information</li>
<li role="presentation" class="">Skills</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<!-- Information Sections -->
<div class="col-md-8 col-md-offset-3 information">
<div class="overview show" id="overview">
<h2 class="line">Overview</h2>
<p class="lead">{{ user.userprofile.overview }}</p>
<a data-placement="bottom" title="update overview" class="fa fa-edit" data-toggle="modal" data-tooltip="tooltip" data-target=".overview_info"></a>
</div>
<div class="personal-info" id="personal-information">
<h2 class="line">Personal Information</h2>
<p class="lead">City: {{ user.userprofile.city }}</p>
<p class="lead">Phone Number: 0{{ user.userprofile.phone }}</p>
<p class="lead">Sex: {{ user.userprofile.sex }}</p>
<a data-placement="bottom" title="update personal information" class="fa fa-edit" data-toggle="modal" data-tooltip="tooltip" data-target=".personal_info"></a>
</div>
<div class="skill" id="my-skills">
<h2 class="line">Skills:</h2>
<p class="lead">{{ user.userprofile.skill }}</p>
<a data-placement="bottom" title="update skills" class="fa fa-edit" data-toggle="modal" data-tooltip="tooltip" data-target=".skills"></a>
</div>
</div>
<!-- get all questions -->
{% if user_prof.userasking_set.all %}
<div class="col-md-8 col-md-offset-3 user_questions">
<h2 class="line">All Questions You Asked</h2>
{% for questions in user_prof.userasking_set.all %}
<p>{{ questions.title }}</p>
{% endfor %}
</div>
{% endif %}
<!-- get favourites -->
{% if get_favourite %}
<div class="col-md-8 col-md-offset-3 user_questions">
<h2 class="line">Favourites</h2>
{% for fav in get_favourite %}
<p>{{ fav.title }}</p>
{% endfor %}
</div>
{% endif %}
</div>
{% include 'accounts/information_form.html' %}
</div>
{% include 'base_footer.html' %}
{% endif %}
{% endblock %}
accounts/views.py
#method_decorator(login_required, name='dispatch')
# view profile page
class ViewProfile(UpdateView):
queryset = UserProfile.objects.all()
template_name = 'accounts/profile.html'
form_class = UpdateInfoForm
slug_field = 'slug'
slug_url_kwarg = 'user_slug'
def get_success_url(self):
return reverse_lazy('accounts:view_profile', kwargs={'user_slug': self.request.user.userprofile.slug})
def get_context_data(self, **kwargs):
self.request.session['switch_comment'] = False
context = super().get_context_data(**kwargs)
user_prof = UserProfile.objects.get(user=self.request.user)
context['user_prof'] = user_prof
context['get_favourite'] = User.objects.get(username=self.request.user.username).favorite.all()
return context
def form_valid(self, form):
form.instance.user_slug = self.request.user.userprofile.slug
self.object = form.save()
return super().form_valid(form)
community/views.py
# List all questions + search
class UserQuestions(ListView):
template_name = 'community/user_questions.html'
context_object_name = 'all_objects'
queryset = UserAsking
def get_context_data(self, object_list=queryset, **kwargs):
context = super().get_context_data(**kwargs)
# paginator
context['all_objects'] = UserAsking.objects.all()
paginator = Paginator(context['all_objects'], 5)
page_number = self.request.GET.get('page_number')
context['all_objects'] = paginator.get_page(page_number)
# search
context['query'] = self.request.GET.get("query", '')
if context['query']:
all_objects = UserAsking.objects.all().order_by('-date')
context['all_objects'] = all_objects.filter(
Q(title__contains=self.request.GET['query']) |
Q(question__contains=self.request.GET['query']) |
Q(field__contains=self.request.GET['query'])
)
return context
community/user_questions.py
{% extends 'base.html' %}
{% block title %} All Questions That People Asked {% endblock %}
{% block body %}
{% if request.user.is_authenticated %}
<div class="all-questions">
<div class="container">
<div class="fl-left hidden-sm hidden-xs">
<h2>All Questions</h2>
</div>
<div class="fl-right hidden-sm hidden-xs">
Ask Question
</div>
<div class="clear"></div>
<div class="row">
<div class="add-q">
<div class="col-sm-12 visible-sm-block visible-xs-block">
<h2>All Questions</h2>
</div>
<div class="col-sm-12 visible-sm-block visible-xs-block">
Ask Question
</div>
</div>
{% if all_objects %}
<div class="col-sm-12">
<div class="questions">
{% for post in all_objects %}
<div class="q_section">
<a class="text-primary title" href="{% url 'community:question_view' post.ask_slug %}">{{ post.title }}</a>
<p class="field">{{ post.field }}</p>
<div class="info fl-right">
<span class="time">{{ post.date }}</span> |
<a href="{% url 'accounts:view_profile' post.userprofile.slug %}" style="font-size:14px">
{% if post.userprofile.user.first_name != '' %}
{{ post.userprofile.user.first_name }}
{% else %}
User
{% endif %}
<img class="logo-image" style="width:25px;height: 25px" src="
{% if request.user.userprofile.logo %}
{{ request.user.userprofile.logo.url }}
{% else %}
{% load static %}
{% static 'index/images/default-logo.jpg' %}
{% endif %}
">
</a>
</div>
<div class="">
<!--a class="btn btn-primary btn-lg" href="{# {% url 'community:delete_post' post.id %} #}">
<i class="fa fa-trash x2"></i>
</a-->
</div>
</div>
{% endfor %}
</div>
</div>
{% else %}
<h2 class="text-center text-info">No Questions</h2>
{% endif %}
</div>
<!-- Pagination -->
{% if all_objects %}
<div class="pagination">
<span class="step-links">
{% if all_objects.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ all_objects.number }} of {{ all_objects.paginator.num_pages }}.
</span>
{% if all_objects.has_next %}
next
last »
{% endif %}
</span>
</div>
{% endif %}
</div>
</div>
{% include 'base_footer.html' %}
{% endif %}
{% endblock %}

Image ids apparently not being created

I have created a template for displaying a photo gallery and giving users the ability to add photos to that gallery:
{% extends 'nowandthen/base.html' %}
{% block body_block %}
<br>
<br>
{% if pictures %}
<ul>
{% for p in pictures %}
<div class="container">
<div class="row">
<div class="col-md-8 card mb-4 mt-3 ">
<!-- Card -->
<!-- Card content -->
<div class="card-body d-flex flex-row">
<!-- Content -->
<div>
<!-- Title -->
<h4 class="card-title font-weight-bold mb-2">{{ p.title }}</h4>
<!-- Subtitle -->
<p class="card-text"><i class="far fa-clock pr-2"></i>{{ p.when_added }}</p>
</div>
</div>
<!-- Card image -->
<div class="view overlay">
<img class="card-img-top rounded-0" src="{{ p.image.url }}" alt="Card image cap">
<a href="#!">
<div class="mask rgba-white-slight"></div>
</a>
</div>
<!-- Card content -->
<div class="card-body">
<div class="collapse-content">
<!-- Text -->
<p class="card-text collapse" id="collapseContent">{{ p.description }}</p>
<!-- Button -->
<a class="btn btn-flat red-text p-1 my-1 mr-0 mml-1 collapsed" data-toggle="collapse" href="#collapseContent" aria-expanded="false" aria-controls="collapseContent">Click for description</a>
<i class="fas fa-share-alt text-muted float-right p-1 my-1" data-toggle="tooltip" data-placement="top" title="Share this post"></i>
<i class="fas fa-heart text-muted float-right p-1 my-1 mr-3" data-toggle="tooltip" data-placement="top" title="I like it"></i>
</div>
</div>
<div class="card-body">
<!-- comments -->
<h2>comments</h2>
{% if not p.comments %}
No comments
{% endif %}
{% for x in p.comment %}
<div class="comments" style="padding: 10px;">
<p class="font-weight-bold">
<h4>Comment by</h4> {{ x.user }}
<span class=" text-muted font-weight-normal">
{{ x.created_on }}
</span>
</p>
{{ x.body | linebreaks }}
</div>
{% endfor %}
</div>
<div class="card-body">
{% if new_comment %}
<h2>Your comment has been posted.</h2>
{% else %}
<h3>Leave a comment</h3>
<form action="{% url 'nowandthen:add_comment' p.image_id %}" method="POST">
{{ comment_form.as_p }}
{% csrf_token %}
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
{% endif %}
</div>
</div>
</div>
</div>
<!-- Card -->
{% endfor %}
</ul>
{% else %}
<li><strong>There are no photographs present.</strong></li>
{% endif %}
{% endblock %}
The idea is that there is an image associated with each comment - there is a for loop of {% for p in pictures %} at the start of the page, and I use variations of p. (e.g. p.image_id) to associate particular pictures with particular comments.
In addition, the urls.py contains the following:
path('add_comment/<int:p.image_id>', views.add_comment, name='add_comment')
However, when I run the code, I get an error message that suggests that image ids aren't being created (even though image is a field in he Pictures model I created):
Reverse for 'add_comment' with arguments '('',)' not found. 1 pattern(s) tried: ['add_comment/$']
What do you suggest, please?
EDIT: This is my view:
#login_required
def add_comment(request, image_id):
new_comment = None
template_name = 'add_comment.html'
image = get_object_or_404(Picture, id=image_id)
comment = image.comments.filter(active=True)
new_comment = None
# Comment posted
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object and don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
context = {'image': image,'comment': comment, 'new_comment': new_comment,'comment_form': comment_form}
return render(request, template_name, context)
And this is my add_comment.html template:
{% extends 'nowandthen/base.html' %}
{% load staticfiles %}
{% block title_block %}
Add self
{% endblock %}
{% block body_block %}
<h1>Add a Comment</h1>
<div>
<form id="comment_form" method="post" action="{% url 'nowandthen:add_comment' comment_id%}" enctype="multipart/form-data" >
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="submit" value="Add Comment" />
</form>
</div>
{% endblock %}
Since you pictures variable is a Queryset, when you loop through it in your template, to access its ID, you just need to do it that way. instance.id
Based on your case, you will have:
{% url 'nowandthen:add_comment' p.id %}
And you will be able to access the id in your view with image_id

Django : Redirect after post doesn't work

After Create moneylog, I want to got back to moneybook_detail, so I made a moneylog/view.py:
class moneylog_create(CreateView):
form_class = forms.CreateMoneylogForm
template_name = "moneylogs/create.html"
def form_valid(self, form):
moneylog = form.save()
moneybook = moneybook_models.Moneybook.objects.get(
pk=self.kwargs["pk"])
form.instance.moneybook = moneybook
moneylog.save()
form.save_m2m()
return redirect(reverse("moneybooks:detail", kwargs={'pk': moneybook.pk}))
and this is moneybook/urls.py
app_name = "moneybooks"
urlpatterns = [
path("create/", views.moneybook_create.as_view(), name="create"),
path("update/<int:pk>/",
views.moneybook_update.as_view(), name="update"),
path("<int:pk>/", views.moneybook_detail, name="detail")
]
moneylogs/urls.py
app_name = "moneylogs"
urlpatterns = [
path("create/<int:pk>/", views.moneylog_create.as_view(), name="create"),
path("update/<int:pk>/", views.moneylog_update.as_view(), name="update")
]
here is my detail.html
<a style="display:scroll;position:fixed;bottom:50px;right:30px;" href="{% url 'moneylogs:create' pk %}">
<div class="rounded-full h-16 w-16 flex items-center justify-center bg-red-400 text-bold font-bold text-white">+</div>
</a>
here is my moneylogs/forms.py
class CreateMoneylogForm(forms.ModelForm):
class Meta:
model = models.Moneylog
fields = (
"pay_day",
"payer",
"dutch_payer",
"price",
"category",
"memo",
)
widgets = {
"payer": forms.RadioSelect(attrs={"style": "width: 100 %"}),
"dutch_payer": forms.CheckboxSelectMultiple,
"memo": forms.Textarea(attrs={"rows": 3})
}
def save(self, *args, **kwargs):
moneylog = super().save(commit=False)
return moneylog
and moneylog_form.html
<form method="POST" class="w-full" enctype="multipart/form-data">
{% csrf_token %}
{% if form.non_field_errors %}
{% for error in form.non_field_errors %}
<span class="text-red-700 font-medium text-sm">{{error}}</span>
{% endfor %}
{% endif %}
<div class="input {% if field.errors %}has_error{% endif %}">
<div class="flex">
<div class="w-1/4">
{{form.name.label}}
</div>
<div class="w-3/4 border-b my-2 py-3">
{{form.name}}
</div>
</div>
{% if form.name.errors %}
{% for error in form.name.errors %}
<span class="text-red-700 font-medium text-sm">{{error}}</span>
{% endfor %}
{% endif %}
</div>
<div class="input {% if field.errors %}has_error{% endif %}">
<div class="flex">
<div class="w-1/4">
{{form.companion.label}}
</div>
<div class="w-3/4 flex inline border-b my-2 py-3">
<div class="w-3/4">
{{form.companion}}
</div>
<div class= "w-1/4 flex justify-center ">
<i class="fas fa-plus-circle"></i>
</div>
</div>
</div>
{% if form.companion.errors %}
{% for error in form.companion.errors %}
><span class="text-red-700 font-medium text-sm">{{error}}</span>
{% endfor %}
{% endif %}
</div>
<div class="input {% if field.errors %}has_error{% endif %}">
<div class="flex">
<div class="w-1/4">
{{form.country.label}}
</div>
<div class="w-3/4 border-b my-2 py-3">
{{form.country}}
</div>
</div>
{% if form.country.errors %}
{% for error in form.country.errors %}
<span class="text-red-700 font-medium text-sm">{{error}}</span>
{% endfor %}
{% endif %}
</div>
<div class="input {% if field.errors %}has_error{% endif %}">
<div class="flex">
<div class="w-1/4">
{{form.location.label}}
</div>
<div class="w-3/4 border-b my-2 py-3">
{{form.location}}
</div>
</div>
{% if form.location.errors %}
{% for error in form.location.errors %}
<span class="text-red-700 font-medium text-sm">{{error}}</span>
{% endfor %}
{% endif %}
</div>
<div class="input {% if field.errors %}has_error{% endif %}">
<div class="flex">
<div class="w-1/4">
{{form.start_date.label}}
</div>
<div class="w-3/4 border-b my-2 py-3">
{{form.start_date}}
</div>
</div>
{% if form.start_date.errors %}
{% for error in form.start_date.errors %}
<span class="text-red-700 font-medium text-sm">{{error}}</span>
{% endfor %}
{% endif %}
</div>
<div class="input {% if field.errors %}has_error{% endif %}">
<div class="flex">
<div class="w-1/4">
{{form.end_date.label}}
</div>
<div class="w-3/4 border-b my-2 py-3">
{{form.end_date}}
</div>
</div>
{% if form.end_date.errors %}
{% for error in form.end_date.errors %}
<span class="text-red-700 font-medium text-sm">{{error}}</span>
{% endfor %}
{% endif %}
</div>
<button class="px-2 py-1 rounded bg-red-500 text-white">{{cta}}</button>
</form>
there is no page redirect. no move, it print just log
"POST /moneylogs/create/1/ HTTP/1.1" 200 5275
How can I return to moneybook_detail after create moneylog?? why my redirect doesn't work?
The generic CreateView has two possible return paths when receiving a POST request:
form_valid() which in your case redirects. This is a HTTP status 302.
form_invalid() which renders the template again with the bound form in its context, in order to display the errors. This is a HTTP status 200.
Since your request returns status 200, we can conclude that the view went into the form_invalid() method, meaning your form has errors. It seems you're rendering the various field errors (although the template you're showing is for the wrong form, I assume this is a copy & paste error) but the easiest to debug is add {{ form.errors }} at the top of your template to display all errors. Or set a breakpoint in your form_invalid() method (override it to return super().form_invalid(form)).
either change the app_name or change the href in details.html. Because in one place you mentioned moneylogs and in another place, you mentioned moneybooks.