I have followed an online tutorial to add a like button to my website/index html file, but for some reason it is not showing on the site. It must be witht the url or views files, but I can not figure it out. Below is the code. The models that I am trying to pull are migrated and work. If anybody has any tips that I could try I woudl greatly apprechiate it.
views file:
**from django.shortcuts import render, redirect
from django.http import JsonResponse
import json
import datetime
from .models import *
from .utils import cookieCart, cartData, guestOrder
from .models import Post, Like
# Create your views here.
def index(request):
return render(request, 'index.html', {})
def post_view(request):
qs = Post.objects.all()
user = request.user
context = {
'qs': qs,
'user': user,
}
return render(request, 'posts/postlike.html', context)
def like_post(request):
user = request.user
if request.method == 'POST':
post_id = request.POST.get('post_id')
post_obj = Post.objects.get(id=post_id)
if user in post_obj.liked.all():
post_obj.liked.remove(user)
else:
post_obj.liked.add(user)
like, created = Like.objects.filter(user=user, post_id=post_id)
if not created:
if like.value == 'Like':
like.value = 'Unlike'
else:
like.value = 'Like'
like.save()
return redirect('post-list')**
urls file:
**from django.urls import path
from . import views
from .views import post_view, like_post
urlpatterns = [
path('', views.index, name='index'),
path('store/', views.store, name='store'),
path('postlike/', post_view, name='post-list'),
path('like/', like_post, name='like-post'),
]**
This is the postlike.html that I am extending into the main index website to create the like button for some of my picture, but it is not pulling.
*
*{% extends 'index.html' %}
{% block title %}
{% endblock title %}
{% block content %}
{% for obj in qs %}
<h1>{{ obj.title }}</h1>
<p>{{ obj.body }}</p>
<form action="{% url 'like-post' %}" method='POST' class="ui form">
{% csrf_token %}
<input type='hidden' name='post_id' value="{{ obj.id }}">
{% if user not in obj.liked.all %}
<button class="UI button positive" type='submit'>Like</button>
{% else %}
<button class="ui button negative" type='submit'>Unlike</button>
{% endif %}
</form>
<strong>{{ obj.liked.all.count }}</strong>
{% endfor %}
{% endblock content %}**
Index.html (which is my main homepage). I added the extends blocks to clarify where to add as well.
**{% block title %}
{% endblock title %}
{% block content %}
{% endblock content %}**
Related
When I try to edit a post I see this error:
TypeError at /edit_post/
edit_post() missing 1 required positional argument: 'post_id'
blogs/models.py
from django.db import models
# Create your models here.
class BlogPost(models.Model):
"""Creating blog topics and text"""
title = models.CharField(max_length=200)
text = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
"""Retunrning title"""
return self.title
def __str__(self):
"""retunrning text"""
return self.text
blogs/views.py
from django.shortcuts import render, redirect
from .models import BlogPost
from .forms import PostForm
# Create your views here.
def index(request):
"""Homepage for blogs"""
return render(request, 'blogs/index.html')
def posts(request):
"""Shows the blogposts list"""
posts = BlogPost.objects.order_by('-date_added')
context = {'posts': posts}
return render(request, 'blogs/posts.html', context)
def new_post(request):
"""Creating new topic"""
if request.method != 'POST':
#Data didn't sent; create empty form
form = PostForm()
else:
# Data sent POST; process data
form = PostForm(data=request.POST)
if form.is_valid():
form.save()
return redirect('blogs:posts')
# Show empty or invalid form
context = {'form': form}
return render(request, 'blogs/new_post.html', context)
def edit_post(request, post_id):
"""Edit post"""
post = BlogPost.objects.get(id=post_id)
if request.method != 'POST':
# Request; form is filled with the data from current post
form = PostForm(instance=post)
else:
# Sending POST data; process data
form = EntryForm(instance=post, data=request.POST)
if form.is_valid():
form.save()
return redirect(request, 'blogs:posts')
context = {'post': post, 'form': form}
return render(request, 'blogs/edit_post.html', context)
blogs/urls.py
from django.urls import path
from .import views
app_name = 'blogs'
urlpatterns = [
# Homepage
path('', views.index, name='index'),
# Posts
path('posts/', views.posts, name='posts'),
# # View a single post
# path('posts/<int:post_id>/', views.post, name="post"),
# Creating new post
path('new_post/', views.new_post, name='new_post'),
# Edit post
path('edit_post/', views.edit_post, name='edit_post'),
blog/blogs/templates/blogs/base.html
<p>
Blog -
Posts
</p>
{% block content %}{% endblock content %}
</p>
blog/blogs/templates/blogs/posts.html
{% extends "blogs/base.html" %}
{% block content %}
<p>Blogposts</p>
<ul>
{% for post in posts %}
<li>
{{ post }}-
Edit post
</li>
<!-- <li>{{ post }}</li>
--> {% empty %}
<li>No posts have been created yet</li>
{% endfor %}
</ul>
Add a new post:
{% endblock content %}
blog/blogs/templates/blogs/new_post.html
{% extends "blogs/base.html" %}
{% block content %}
<p>Add a new post:</p>
<form action="{% url 'blogs:new_post' %}" method='post'>
{% csrf_token %}
{{ form.as_p }}
<button name="submit">add post</button>
</form>
{% endblock content %}
blog/blogs/templates/blogs/edit_post.html
{% extends "blogs/base.html" %}
{% block content %}
<p>{{ post }}</p>
<p>Edit post</p>
<form action="{% url 'blogs:edit_post' post.id %}"method='post'>
{% csrf_token %}
{{ form.as_p }}
<button name="submit">edit post</button>
</form>
{% endblock content %}
I think you need the post id in your url so as to know which post to edit. Try this in your urls.py:
# Edit post
path('edit_post/<post_id>', views.edit_post, name='edit_post'),
I am doing a Product application for fun, to which I got an error.
The error says that redirect is not defined at line 29 in my views.py file. Here is my views.py file
from django.contrib.auth.models import User
from django.shortcuts import render,get_object_or_404
from .forms import NewProductForm
from .models import Product
# Create your views here.
def home(request):
products = Product.objects.all()
return render(request, 'home.html', {'products': products})
def product_topics(request, pk):
product = get_object_or_404(Product, pk=pk)
return render(request, 'topics.html', {'product': product})
def new_product(request, pk):
product = get_object_or_404(Product, pk=pk)
user = User.objects.first()
if (request.method == 'POST'):
form = NewProductForm(request.POST)
if(form.is_valid()):
product = form.save(commit = False)
product.starter = user
product.save()
return redirect('product_topics',pk=product.pk)
else:
form = NewProductForm()
return render(request, 'new_product.html', {'product': product, 'form': form})
Here's my urls.py file
from django.conf.urls import url
from django.contrib import admin
from inventories import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^products/(?P<pk>\d+)/$', views.product_topics, name='product_topics'),
url(r'^products/(?P<pk>\d+)/new/$', views.new_product, name='new_product'),
url(r'^admin/', admin.site.urls),
]
And here's the form that I used to create a new product
{% extends 'base.html' %}
{% load widget_tweaks %}
{% block title %}Start a New Topic{% endblock %}
{% block breadcrumb %}
<li class="breadcrumb-item">Products</li>
<li class="breadcrumb-item">{{ product.name }}</li>
<li class="breadcrumb-item active">New topic</li>
{% endblock %}
{% block content %}
<form method="post" novalidate>
{% csrf_token %}
{% for field in form %}
<div class="form-group">
{{ field.label_tag }}
{% render_field field class="form-control" %}
{% if field.help_text %}
<small class="form-text text-muted">
{{ field.help_text }}
</small>
{% endif %}
</div>
{% endfor %}
<button type="submit" class="btn btn-success">Post</button>
</form>
{% endblock %}
What does this error mean, and can you show me how to fix it?
You haven't imported the redirect function. Add this to your views
from django.shortcuts import redirect
I'm currently going through "Python Crash Course" by Eric Matthes. I'm on Chapter 19 trying to add a page to a web app where users can enter data. If working correctly, the user can write an entry about a topic that he/she is learning about. I wrote the code exactly how the book told me. Sadly I keep getting the following error:
File "/Users/jakeziegelbein/Desktop/crashCoursePython/learning_log/11_env/lib/python3.8/site-packages/django/urls/resolvers.py", line 685, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'learning_logs/new_entry' not found. 'learning_logs/new_entry' is not a valid view function or pattern name.
Here are the files of code:
views.py
from django.shortcuts import render, redirect
from .models import Topic, Entry
from .forms import TopicForm, EntryForm
def index(request):
"""The home page for Learning Log."""
return render(request, 'learning_logs/index.html')
def topics(request):
"""Show all topics."""
topics = Topic.objects.order_by('date_added')
context = {'topics': topics}
return render(request, 'learning_logs/topics.html', context)
def topic(request, topic_id):
"""Show a single topic and all its entries."""
topic = Topic.objects.get(id=topic_id)
entries = topic.entry_set.order_by('-date_added')
context = {'topic': topic, 'entries': entries}
return render(request, 'learning_logs/topic.html', context)
def new_topic(request):
"""Add a new topic."""
if request.method != 'POST':
# No data submitted; create a blank form.
form = TopicForm()
else:
# POST data submitted; process data.
form = TopicForm(data=request.POST)
if form.is_valid():
form.save()
return redirect('learning_logs:topics')
# Display a blank or invalid form.
context = {'form': form}
return render(request, 'learning_logs/new_topic.html', context)
def new_entry(request, topic_id):
"""Add a new entry for a particular topic."""
topic = Topic.objects.get(id=topic_id)
if request.method != 'POST':
# No data submitted; create a blank form.
form = EntryForm()
else:
# POST data submitted; process data.
form = EntryForm(data=request.POST)
if form.is_valid():
new_entry = form.save(commit=False)
new_entry.topic = topic
new_entry.save()
return redirect('learning_logs:topic', topic_id=topic_id)
# Display a blank or invalid form.
context = {'topic': topic, 'form': form}
return render(request, 'learning_logs/new_entry.html', context)
urls.py
"""Defines URL patterns for learning_logs."""
from django.urls import path
from . import views
app_name = 'learning_logs'
urlpatterns = [
# Home page
path('', views.index, name='index'),
# Page that shows all topics.
path('topics/', views.topics, name='topics'),
# Detail page for a single topic.
path('topics/<int:topic_id>/', views.topic, name='topic'),
# Page for adding a new topic
path('new_topic/', views.new_topic, name='new_topic'),
# Page for adding a new entry
path('new_entry/<int:topic_id>/', views.new_entry, name='new_entry'),
]
topic.html
{% extends 'learning_logs/base.html' %}
{% block content %}
<p>Topic: {{ topic }}</p>
<p>Entries:</p>
<p>
Add new entry
</p>
<ul>
{% for entry in entries %}
<li>
<p>{{ entry.date_added|date:'M d, Y H:i' }}</p>
<p>{{ entry.text|linebreaks }}</p>
<p>
Edit entry
</p>
</li>
{% empty %}
<li>There are no entries for this topic yet.</li>
{% endfor %}
</ul>
{% endblock content %}
topics.html
{% extends "learning_logs/base.html" %}
{% block content %}
<p>Topics</p>
<ul>
{% for topic in topics %}
<li>
{{ topic }}
</li>
{% empty %}
<li>No topics have been added yet.</li>
{% endfor %}
</ul>
Add a new topic
{% endblock content %}
newtopic.html
{% extends "learning_logs/base.html" %}
{% block content %}
<p>Add a new topic:</p>
<form action="{% url 'learning_logs:new_topic' %}" method='post'>
{% csrf_token %}
{{ form.as_p }}
<button name="submit">Add topic</button>
</form>
{% endblock content %}
base.html
<p>
Learning Log -
Topics
</p>
{% block content %}{% endblock content %}
new_entry.html
{% extends "learning_logs/base.html" %}
{% block content %}
<p>{{ topic }}</p>
<p>Add a new entry:</p>
<form action="{% url 'learning_logs:new_entry' topic.id %}" method='post'>
{% csrf_token %}
{{ form.as_p }}
<button name='submit'>Add entry</button>
</form>
{% endblock content %}
In your main app's (learning_log project folder) urls.py do you have:
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('learning_logs.urls')),
]
Currently I have a user log in page and a user sign up page, how can I have both of these on one single page?
Base.html:
<!doctype html>
<head>
{% block head %}
<title>base</title>
{% endblock %}
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>
signup.html:
{% extends 'core/base.html' %}
{% block head %}
<title> Sign Up</title>
{% endblock %}
{% block body %}
<h2>Sign up</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Sign up</button>
</form>
{% endblock %}
login.html:
{% extends 'core/base.html' %}
{% block head %}
<title> Login</title>
{% endblock %}
{% block body %}
<h1>Login</h1>
<form method = 'post'>
{% csrf_token %}
{{ form.as_p }} <!--'form' comes from login view imported in urls-->
<button type = 'submit'>Login</button>
</form>
{% endblock %}
urls.py:
from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth.views import login
from core import views as core_views
urlpatterns = [
url(r'^$', core_views.login_redirect, name = 'login_redirect'),
url(r'^admin/', admin.site.urls),
url(r'^login/$', login, {'template_name': 'core/login.html'}, name='login'),
url(r'^signup/$', core_views.signup, name='signup'),
url(r'^account/$', core_views.account_page, name = 'account_page')
]
views.py:
from django.shortcuts import render
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.forms import UserCreationForm
def login_redirect(request):
return redirect('login')
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('/account')
else:
form = UserCreationForm()
args = {'form': form}
return render(request, 'core/signup.html', args)
def account_page(request):
return HttpResponse('success')
How would I put both the log in and sign up on one page, if they are handled by separate views? Thank you in advance for your response! I have no more details to add and it is making me add more details i apologize for this unnecessary text.
In any scenario where you need multiple forms in the same page the following technique can be applied.
For example currently you need two forms 'Sign In' and 'Sign Up' on the same page.
index.html
<!-- Sign In Form -->
<form>
<button type='submit' name='submit' value='sign_in'></button>
</form>
<!-- Sign Up Form -->
<form>
<button type='submit' name='submit' value='sign_up'></button>
</form>
views.py
def index(request):
if request.method == "POST":
if request.POST.get('submit') == 'sign_in':
# your sign in logic goes here
elif request.POST.get('submit') == 'sign_up':
# your sign up logic goes here
I have this code on my template:
{% extends "base.html" %}
{% block content %}
<div style="padding:40px;margin:40px;border:1px solid #ccc">
<h1>picture</h1>
<form action="" method="post" enctype="multipart/form-data"> <!--{% url 'imageupload' %}-->
{% csrf_token %} {{form}}
<input type="submit" value="Upload" />
</form>
{% for img in images %}
{{forloop.counter}}.{{ img.pic.name }}
({{img.upload_date}})<hr />
{% endfor %}
</div>
{% endblock content %}
Although I have doubts with the form action but anyways.
The problem is that when I click on submit button, it takes me to a blank page, no pop-up to actually upload the image, nothing.
Is there some example I should follow to accomplish this?
Also, this is just a proof test, but I'd like to know if a model and/or form is actually needed for it to work?
EDIT
Okay, by editing the input line like this <input type="file" name='input_name' /> it actually opens the file pop-up, but obviously it doesn't upload anything, it needs like a submit button or something, so, now it looks like this:
{% extends "base.html" %}
{% block content %}
<div style="padding:40px;margin:40px;border:1px solid #ccc">
<h1>picture</h1>
<form action="" method="post" enctype="multipart/form-data"> <!--{% url 'imageupload' %} -->
{% csrf_token %} {{form}}
<input type="file" name='input_name' />
<input type="submit" value="Upload" />
</form>
{% for img in images %}
{{forloop.counter}}.{{ img.pic.name }}
({{img.upload_date}})<hr />
{% endfor %}
{% endblock content %}
But when I click on submit, it keeps sending me to a blank page, so, the value on submit, which is Upload, comes from this model:
from django.db import models
from django.forms import ModelForm
class Upload(models.Model):
pic = models.FileField(upload_to="static/")
upload_date=models.DateTimeField(auto_now_add =True)
class UploadForm(ModelForm):
class Meta:
model = Upload
fields = ('pic',)
And on my views.py:
from django.shortcuts import render
from uploader.models import UploadForm,Upload
from django.http import HttpResponseRedirect
from django.urls import reverse
def home(request):
if request.method=="POST":
img = UploadForm(request.POST, request.FILES)
if img.is_valid():
img.save()
return HttpResponseRedirect(reverse('imageupload'))
else:
img=UploadForm()
images=Upload.objects.all()
return render(request,'image_upload.html',{'form':img,'images':images})
And in my urls.py:
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
from uploader import views as uploader_views
urlpatterns = [...
some patterns...
url(r'^image_upload/', uploader_views.home, name='imageupload'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)