I made a small blog site and is not showing all the items from the database. If i try to see the posts from my phone i see only 3 posts, when in my DB there are 9. When i click on one post i got a Not Found error saying that the requested URL posts/legea etc was not found on server.
LE: My server is inside a VM. Is this maybe an issue?
This is the link that should have all of the posts: http://cohen.ro/posts/
PS I dont have a migrations folder. I just created now and put an init.py file in it. Bu still after running migrate didn't see the migrations and the result is the same.
However, if i enter in admin trhourgh site/admin i can see all of the posts in DB and when i go back to the site all of the items are out there and i can read the posts.
Can someone, please help me in order to fix this?! thank you!
My post List:
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block head_title %} Blog | {% endblock %}
{% block content %}
<div class="container-fluid" style="width:91%;color: currentColor;!important;">
<div class="row" id="list_posts" style="background-color: white;padding-top: 40px;">
<br/>
<br/>
<br>
{% for obj in object_list %}
<div class="col-sm-4">
<div class="thumbnail">
{% if obj.image %}
<img src="{{ obj.image.url }}"/>
{% endif %}
<div class="caption" style="color:currentColor">
{% if obj.draft %} <h3>Staff Only Draft</h3> {% endif %}{% if obj.publish > today %}<h3>Staff Only: Future Post{%endif%}</h3>
<h2><a href='{{ obj.get_absolute_url }}' >{{obj.title }}</a> </h2>
<h5>{{obj.location }} </h5>
{% if obj.user.get_full_name %}<p>Author: {{ obj.user.get_full_name }}</p>{% endif %}
<p> {{ obj.content |linebreaks |truncatechars:150}}</p>
{# <p>View</p>#}
</div>
</div>
</div>
{# {% cycle "" "" "<div class='col-sm-12'><hr/></div></div><div class='row'style='background-color:white;color:currentColor'>" %}#}
{% cycle "" "" "<div class='col-sm-12'><hr/><br/></div><div class='row'style='background-color:white;color:currentColor'></div>" %}
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if object_list.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ object_list.number }} of {{ object_list.paginator.num_pages }}.
</span>
{% if object_list.has_next %}
next
last »
{% endif %}
</span>
</div>
</div>
</div>
Post Form:
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block head_title %} Blog | {% endblock %}
{% block content %}
<div class="container-fluid" id="post_form_id" style="background-color: teal">
<div class="col-sm-6 offset-sm-3">
<h1> Form </h1>
<form method='POST' action='' enctype="multipart/form-data"> {% csrf_token %}
{{ form |crispy }}
<input type="submit" class="btn btn-default" role="button" value="Create Post">
</form>
</div>
</div>
{% include 'navbar_bottom.html' %}
{% endblock %}
My Post detail:
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% load i18n %}
{% block head_title %} Blog | {% endblock %}
{% block content %}
<div class="container-fluid" id="detail_posts" style="background-color: white">
<div class="col-xs-12 offset-xs-0 col-sm-6 offset-sm-3">
{% if instance.image %}
<img src="{{ instance.image.url }}" class="img-responsive" />
{% endif %}
<h1> {{ title }} <small> {% if instance.draft %} <span style="color:red">{% trans "Draft" %}</span> {% endif %}</small></h1>
{% if instance.user.get_full_name %}
<p> {% trans "Autor:" %} {{ instance.user.get_full_name }}</p>
{% endif %}
{{ instance.location |linebreaks }} <br/>
{{ instance.content |linebreaks }} <br/>
Facebook
Twitter
<a href="https://www.linkedin.com/shareArticle?mini=true&url={{ request.build_absolute_uri }}/&title={{ instance.title }}&source={{ request.build_absolute_uri }}">
Linkedin </a>
Reddit
<a href='https://plus.google.com/share?url={{ request.build_absolute_uri }}'>GooglePlus</a>
</div>
</div>
{% include 'navbar_bottom.html' %}
{% endblock content%}
My views:
from contact.forms import ContactForm
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from contact.forms import ContactForm
from django.utils.translation import ugettext_lazy as _
import requests
from django.conf import settings
from django.contrib import messages
def index(request):
return render(request, 'home.html')
def board(request):
return render(request, 'board.html')
def persoanefizice(request):
return render(request, 'persoanefizice.html')
def consultanta(request):
return render(request, 'consultanta.html')
def cyberintelligence(request):
return render(request, 'cyberintelligence.html')
#
# def pay(request):
# return render(request, 'pay.html')
def blog(request):
return render(request, 'blog.html')
def contact(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
contact_name = form.cleaned_data['numele_dumneavoastra']
contact_phone = form.cleaned_data['numarul_de_telefon']
# contact_period = form.cleaned_data['perioada_cand_va_putem_contacta']
subject = contact_name + " | " + contact_phone
content = form.cleaned_data['mesajul_dumneavoastra']
contact_email = form.cleaned_data['emailul_dumneavoastra']
''' Begin reCAPTCHA validation '''
recaptcha_response = request.POST.get('g-recaptcha-response')
data = {
'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
'response': recaptcha_response
}
r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data)
result = r.json()
''' End reCAPTCHA validation '''
if result['success']:
try:
send_mail(subject,content,contact_email, ['greatjobdone770#gmail.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
else:
form = ContactForm()
return render(request, "contact.html", {'form': form})
def success(request):
return HttpResponse('Succes! Multumim pt mesajul trimis.')
Related
I am trying to display 2 forms in my contact.html page in a Django project. Each form needs to display a success message when being successfully submitted by users. The problem is that both forms in the page show the same success message when either of them being submitted.
How can I tie the success message to the submitted form on my HTML page?
forms.py
from dataclasses import field, fields
from logging import PlaceHolder
from socket import fromshare
from django import forms
from .models import ServiceRequest, Contact, Newsletter
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
fields = ['name','email','phone','message']
class NewsletterForm(forms.ModelForm):
class Meta:
model = Newsletter
fields = ['name','email']
views.py
from http.client import HTTPResponse
from multiprocessing import context
from django.shortcuts import render
from django.views.generic import TemplateView
from .forms import ContactForm, NewsletterForm, ServiceRequest, ServiceRequestForm
from django.http import HttpResponseRedirect
from django.contrib import messages
from django.urls import reverse
def Contact(request):
contact_form = ContactForm(request.POST or None)
newsletter_form = NewsletterForm(request.POST or None)
if request.method == 'POST' and contact_form.is_valid():
contact_form.save()
messages.success(request, "Thanks for contacting us!")
return HttpResponseRedirect(request.path_info)
elif request.method == 'POST' and newsletter_form.is_valid():
newsletter_form.save()
messages.success(request, "Thanks for joining our newsletter!")
return HttpResponseRedirect(request.path_info)
context = {
"contact_form":contact_form,
"newsletter_form":newsletter_form,
}
return render(request, "main/contact.html", context)
contact.html
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% load static %}
{% block content %}
<div>
<!-- Message from backend -->
{% for message in messages %}
{% if message.tags == 'success' %}
<div>{{message}}
</div>
{% endif %}
{% endfor %}
<form method="POST">
{% csrf_token %}
<div class="row">
{{ contact_form.name|as_crispy_field }}
{{ contact_form.email|as_crispy_field }}
{{ contact_form.phone|as_crispy_field }}
{{ contact_form.message|as_crispy_field }}
</div>
</div>
<button type="submit">Submit</button>
</form>
</div>
<div>
<!-- Message from backend -->
{% for message in messages %}
{% if message.tags == 'success' %}
<div>{{message}}
</div>
{% endif %}
{% endfor %}
<form method="POST">
{% csrf_token %}
<div class="row">
{{ newsletter_form.name|as_crispy_field }}
{{ newsletter_form.email|as_crispy_field }}
</div>
<button type="submit">Submit</button>
</form>
</div>
{% endblock %}
After submitting one form on this page, both forms show the success message:
You can use extra_tags of messages framework Django docs:
So in view:
messages.success(request, "Thanks for contacting us!", extra_tags='form1')
And in template:
{% for message in messages %}
{% if message.tags == 'success' and message.extra_tags == 'form1' %}
<div>{{message}}
</div>
{% endif %}
{% endfor %}
I have a Django form in which I use crispy-forms along with bootstrap5. Everything was alright until I wanted to changed the Layout of my form. As my form is constructed dynamically, I just wanted to define the value of a set element item which is under the form (field_name, layout_index). The goal was to define it as a FieldWithButton, as I couldn't find another way to do that.
To do that, I modified my helper in the __init__ method of my form :
self.helper[item[1]] = Div(FieldWithButtons(item[0], StrictButton("Add item")), id=f'div_id_{item[0]}', css_class='mb-3 row')
This is rendered nearly correctly in my form, I have the FieldWithButton with Div etc. However, the div which contains my FieldWithButton doesn't take the field_class of my helper that I defined, and instead creates a <divclass='col-10'>...</divclass='col-10'>.
There's juste a space which disappeared and messed everything up. How can I either remove the class='col-10' part of my div and put it as its class or differently define my Field as a FieldWithButton ?
Here's my whole form class if needed :
class ScriptInputForm(forms.Form):
def __init__(self, *args, **kwargs):
variables = kwargs.pop('variables') # All variables to render
variables_names = [*variables] # under the form {'name':['type', 'description']}
super().__init__(*args, **kwargs)
for var in variables_names: # Dynamic creation of the fields
values = variables[var]
field = self.fields[var] = forms.CharField()
field.widget.attrs['placeholder'] = values[1].title()
self.helper = FormHelper(self)
num = 1 # Rough part where I define the tuples ('name', 'index') of all lists in my variables
lists = []
for k,v in variables.items():
if v[0]=='list':
lists.append((k,num))
num+=1
for item in lists: # Part where the problem is coming from
self.helper[item[1]] = Div(FieldWithButtons(item[0], StrictButton("Add item")))
self.helper.add_input(Submit('submit', 'Submit'),)
self.helper.label_class = 'col-2'
self.helper.field_class = 'col-10'
self.helper.form_action = reverse_lazy('scripts:data_input')
And the rendered HTML :
<div>
<div class="mb-3 row">
<label for="id_liste" class="col-form-label col-2">Liste</label>
<divclass="col-10"> <!-- With <div class="col-10"> everything's ok -->
<div class="input-group">
<input type="text" name="liste" placeholder="Your List" class="textinput textInput form-control" id="id_liste">
<button class="btn" type="button">Add item</button>
</div>
</divclass="col-10">
</div>
</div>
Seems like it was an error in crispy-bootstrap5.
The FieldWithButtons display is defined in field_with_buttons.html whose code is the following :
<div{% if div.css_id %} id="{{ div.css_id }}"{% endif %} class="mb-3{% if 'form-horizontal' in form_class %} row{% endif %}{% if wrapper_class %} {{ wrapper_class }}{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}{% if div.css_class %} {{ div.css_class }}{% endif %}" {{ div.flat_attrs }}>
{% if field.label and form_show_labels %}
<label for="{{ field.id_for_label }}" class="{% if 'form-horizontal' in form_class %}col-form-label {% else %}form-label {% endif %}{{ label_class }}{% if field.field.required %} requiredField{% endif %}">
{{ field.label }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}
</label>
{% endif %}
<div{% if field_class %}class="{{ field_class }}"{% endif %}> <!-- Here -->
<div class="input-group{% if input_size %} {{ input_size }}{% endif %}">
{% if field.errors %}
{% crispy_field field 'class' 'form-control is-invalid' %}
{% else %}
{% crispy_field field 'class' 'form-control' %}
{% endif %}
{{ buttons|safe }}
</div>
{% for error in field.errors %}
<p id="error_{{ forloop.counter }}_{{ field.auto_id }}" class="text-danger mb-0"><small><strong>{{ error }}</strong></small></p>
{% endfor %}
{% include 'bootstrap5/layout/help_text.html' %}
</div>
</div>
Just had to add a space at the start of the second div to fix the issue.
I am a super beginner with HTML, however, I am trying to resolve an issue with my website. I am trying to concatenate a wildcard(*) to the end of whatever a consumer tries to search so that it picks up similarly tagged items, however, I cannot figure out where to add said code... Our current search query works well when pulling up items based on partial keywords, but when hitting the 'enter' button it will say it could not find any products.
Additional notes: This is a Shopify website with a theme from halothemes so most of this is coded by them.
{% assign grid_results = true %}
<div class="search-page collection-template" data-search-page>
<div class="container">
{% if search.performed %}
{% comment %}
Avoid accessing search.results before the opening paginate tag.
If you do, the pagination of results will be broken.
{% endcomment %}
{% paginate search.results by 15 %}
{% comment %}
We don't have any results to show. Feel free to show off featured products
or suggested searches here.
{% endcomment %}
{% if search.results_count == 0 %}
<header class="page-header">
<h2>
{% render 'multilang' with settings.search_1 %}
<strong> "{{ search.terms }}" </strong>
{% render 'multilang' with settings.search_2 %}
</h2>
</header>
{% else %}
<header class="page-header">
<h2>
{% render 'multilang' with settings.search_3 %}
<strong> "{{ search.terms }}" </strong>
{% render 'multilang' with settings.search_4 %}
</h2>
</header>
{% comment %}
Each result template, based on the grid_layout variable above
{% endcomment %}
<div class="block-row col-main">
{% if grid_results == false %}
<div class="product-collection products-list product-search row">
{% for product in search.results %}
<div class="grid-item col-12{% if settings.product_image_border%} grid-item-border{% endif %}">
{% render 'search-result' with product as product %}
</div>
{% endfor %}
</div>
{% else %}
<div class="products-grid product-search row product-collection">
{% for product in search.results %}
<div class="grid-item col-6 col-md-4{% unless settings.layout_style == 'layout_style_1170' %} col5 col-lg-3{% endunless %}{% if settings.product_image_border%} grid-item-border{% endif %}">
{% if settings.style_product_grid == 'style_product_grid_2' %}
{% render 'product-grid-item-style-2' with product as product %}
{% else %}
{% render 'product-grid-item' with product as product %}
{% endif %}
</div>
{% endfor %}
</div>
{% endif %}
</div>
{% endif %}
{% if paginate.pages > 1 %}
<div class="padding">
{% render 'pagination-page' paginate: paginate %}
</div>
{% endif %}
{% endpaginate %}
{% else %}
{% comment %}
If search.performed is false, someone either accessed the page without
the q parameter, or it was blank.
Be sure to show a search form here, along with anything else you want to showcase.
{% endcomment %}
<header class="page-header">
<h2 style="text-align:center" {% if settings.enable_multilang %}data-translate="general.search.title"{%endif%}>{{ 'general.search.title' | t }}</h2>
<div class="header-search__form">
<form action="/search" method="get" class="search-bar" role="search">
<input type="hidden" name="type" value="product">
<input type="search" name="q"
{% if settings.enable_multilang %} data-translate="general.search.placeholder" translate-item="placeholder"{% endif %}
placeholder="{{ 'general.search.placeholder' | t }}"
class="input-group-field" aria-label="Search Site" autocomplete="off">
<button type="submit" class="btn icon-search">
{% render 'icon-search' %}
</button>
</form>
</div>
</header>
{% endif %}
Please let me know if you guys need any additional information! Thank you!
You can use a simple script to add a wildcard to the search query on submitting the form e.g:
var searchForm = document.querySelector(".search-bar");
searchForm.addEventListener("submit", function(e) {
var searchInput = searchForm.querySelector("[name=q]");
var q = searchInput.value;
if (!q.match(/\*$/)) {
e.preventDefault();
searchInput.value = q + "*";
searchForm.submit();
}
});
I have been working on a project and one of the functions that it has it to delete posts, when in the imagelist view, I am able to delete those posts but when I am in the profile view which shows the user's posts when I try to delete it, a 404 error page not found shows up. I dont know where the error is but I think it is on the profile view.
views.py
def profile(request, pk=None):
if pk:
post_owner = get_object_or_404(User, pk=pk)
user_posts=Post.objects.filter(user_id=pk)
else:
post_owner = request.user
user_posts=Post.objects.filter(user_id=pk)
return render(request, 'profile.html', {'post_owner': post_owner, 'user_posts': user_posts,})
profile.html
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ post_owner.username }}</h2>
<p class="text-secondary">{{ post_owner.email }}</p>
</div>
</div>
<div>
{% for Post in user_posts %}
<li class="list-group-item">{{ Post.text }}
{{ Post.user }}
{% if Post.posti %}
<img src="{{ Post.posti.url }}" alt="image here" style="max-width: 300px; max-height: 300px">
{% endif %}
{% if Post.user == user %}
<div class="float-right">
<form action="delete_image/{{ Post.id }}/" action="post">
<button type="submit" class="btn btn-outline-danger btn-sm">Delete</button>
</form>
</div>
{% endif %}
</li>
{% endfor %}
</div>
</div>
urls.py
urlpatterns = [
path('profile/<int:pk>/', views.profile, name='profile_pk'),
path('imagepost', views.uimage, name='image'),
path('imagelist', views.imagelist, name='imagelist'),
path('delete_image/<int:image_id>/', views.delete_image, name='delete_image'),
]
All I did for fixing this problem was create add an if statement to my imagelist.html
{% if image.user == user %}
{{ image.user }}
{% else %}
{{ image.user }}
{% endif %}
I had tried several times to fix this but not successfull, likes count are all updating when I use the admin panel but not in html template..
views.py
from common.decorators import ajax_required
#ajax_required
#login_required
#require_POST
def like_post(request):
# image_id = get_object_or_404(Post, id=request.POST.get('id'))
image_id = request.POST.get('id')
action = request.POST.get('action')
if image_id and action:
try:
image = Post.objects.get(id=post_id)
if action == 'like':
image.likes.add(request.user)
else:
image.likes.remove(request.user)
return JsonResponse({'status':'ok'})
except:
pass
return JsonResponse({'status':'error'})
post_view.html
{% extends 'base.html' %}
{% load static %}
{% block title %}Users Posts{% endblock %}
{% block content %}
<div class="container-fluid">
<form method="post" enctype="multipart/form-data">
{{ form.as_p }}
{% csrf_token %}
<input type="submit" value="Post">
</form>
</div>
{% for post in posts %}
<div class="w3-container w3-card w3-white w3-round w3-margin"><br>
<img src="{% if post.user.profile.photo %} {{post.user.profile.photo.url}}
{% else %}{% static 'img/user.png' %}{% endif %}" alt="Avatar" class="w3-left w3-circle w3-margin-right" style="width:60px">
<span class="w3-right w3-opacity">{{ post.created }}</span>
<h4>{{ post.user|title }}</h4><br>
<hr class="w3-clear">
<p>{{ post.title }}</p>
{% if post.image %}
<div style="max-width:100%;height:auto;object-fit: cover;" class="img-fluid">
<img src="{{ post.image.url }}" class="img-fluid" style="max-width:100%;height:auto;object-fit: cover;">
</div>
<p>{{ post.description }}</p>
{% endif %}
{% with total_likes=post.likes.count users_like=post.likes.all %}
<div class="image-info">
<div>
<span class="count">
<span class="total">{{ total_likes }}</span>
like{{ total_likes|pluralize }}
</span>
<a href="#" data-id="{{ post.id }}" data-action="{% if request.user in users_like %}un{% endif %}like" class="like button mb-3">
{% if request.user not in users_like %}
Like
{% else %}
Unlike
{% endif %}
</a>
</div>
</div>
{% endwith %}
</div>
{% endfor %}
{% include 'post/pagination.html' with page=posts %}
{% endblock %}
{% block domready %}
$('a.like').click(function(e){
e.preventDefault();
$.post('{% url "post:like" %}',
{
id: $(this).data('id'),
action: $(this).data('action')
},
function(data){
if (data['status'] == 'ok')
{
var previous_action = $('a.like').data('action');
// toggle data-action
$('a.like').data('action', previous_action == 'like' ?
'unlike' : 'like');
// toggle link text
$('a.like').text(previous_action == 'like' ? 'Unlike' :
'Like');
// update total likes
var previous_likes = parseInt($('span.count .total').text());
$('span.count .total').text(previous_action == 'like' ?
previous_likes + 1 : previous_likes - 1);
}
}
);
});
{% endblock %}
base.html
<script src="{% static 'js/jquery.min.js' %}"></script>
<script src="{% static 'js/js.cookie.min.js' %}"></script>
<script>
var csrftoken = Cookies.get('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$(document).ready(function(){
{% block domready %}
{% endblock %}
});
</script>
urls.py
from django.urls import path
from post import views
from django.conf import settings
from django.conf.urls.static import static
app_name = 'post'
urlpatterns = [
path('',views.post_list,name='post_list_view'),
path('like/',views.like_post,name='like'),
]
This the entire code when I tried to modify the ajax function the like button changes and then it will change all other likes present in the post_view.html, where it contains the all other posts in the same page..