So when I go to the url: http://127.0.0.1:8000/post/2/. instead of showing me the post detail view, it gives me an error. I am so confused about it. However I can see it in list view and in profile page.
Edited: added error image and detail.html
posts views.py
class PostDetailView(LoginRequiredMixin, DetailView):
model = Posts
template_name = 'posts/detail.html'
models.py
class Posts(models.Model):
caption = models.CharField(max_length=2200)
date_posted = models.DateTimeField(default=timezone.now())
image = models.ImageField( upload_to='PostsImages')
user = ForeignKey(User, on_delete=models.CASCADE ,related_name='userposts')
def __str__(self):
return f"Post {self.id} ({self.user.username})'s"
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
img = Image.open(self.image.path)
img.save(self.image.path)
the main urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('posts.urls')),
path('user/', include('users.urls')),
path('comments/', include('comments.urls'))
]
posts urls.py
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from .views import PostsListView, PostCreatView, PostDeleteView, PostDetailView
urlpatterns = [
path('', PostsListView.as_view(), name='homepage'),
path('delete/<int:pk>/', PostDeleteView.as_view(), name='delete-post'),
path('creat-post', PostCreatView.as_view(), name='create-post'),
path('post/<int:pk>/', PostDetailView.as_view(), name='detail-post')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
users urls.py
from django.urls import path
from django.contrib.auth import views as auth_views
from .views import ProfileDetailView
from .views import SignUp, LogOut
urlpatterns = [
path('signup/', SignUp, name='signup'),
path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), #template_name'xx' tells it where to find the log in url
path('logout/', LogOut, name='logout'),
path('<int:pk>/profile', ProfileDetailView.as_view(), name='profile')
]
detail.html
{% extends "posts/base.html" %}
{% block content %}
{{object.user.username}}
<div>
<img class="rounded-circle article-img" src="{{ objetc.user.profile.picture.url }}" />
</div>
{% if user == object.user %}
<div>
Delete Post
</div>
{% endif %}
<img src="{{ object.image.url }}" />
<div>
{{object.user.username}}
</div>
<p>{{object.caption}}</p>
<h6>Comments</h6>
{% for comment in object.comments.all %}
<hr class="bg-danger border-2 border-top border-primary">
{{comment.user.username}}
<p>{{comment.text}}</p>
{% if user == comment.user %}
Delete
Edit
{% endif %}
{% endfor %}
<div>
Add Comment
</div>
{% endblock %}
Change this
{{object.user.username}}
to
{{object.user.username}}
that should work.
Related
I was working on a django project. I made a userprofiles app to manage(create, update) user's profile in my website, but it is not working properly. I am getting 'This field is required' &
'no file chosen' while making profile as a user and if I do blank=True in models profile_picture user pictures are not saving in the media url.
I have tried so many tips from stackoverflow but they are not working.
here is my code:
# settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = str(BASE_DIR.joinpath('media'))
# models.py
from django.db import models
from django.contrib.auth import get_user_model
import uuid
class UserProfile(models.Model):
author = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
profile_picture = models.ImageField(upload_to='images/')
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
bio = models.TextField(blank=True)
occupation = models.CharField(max_length=100)
hobbies = models.TextField(blank=True)
date_of_birth = models.TimeField()
def __str__(self):
return self.author.username + ("'s profile")
# views.py
from django.views.generic import CreateView
from .forms import CustomUserCreationForm
from django.urls import reverse_lazy
class SignUpView(CreateView):
form_class = CustomUserCreationForm
template_name = "registration/signup.html"
success_url = reverse_lazy("profile_create")
# project-level urls.py
from django.contrib import admin
from django.conf import settings
from django.urls import path, include
from django.conf.urls.static import static
from django.views.generic.base import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
path("accounts/", include("accounts.urls")),
path("accounts/", include("django.contrib.auth.urls")),
path("profile/", include("userprofiles.urls")),
path("", TemplateView.as_view(template_name="home.html"), name="home"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# app-level urls.py
from django.urls import path
from .views import ProfileCreateView
urlpatterns = [
path("create/", ProfileCreateView.as_view(), name="profile_create")
]
# profile_create.html
{% extends 'base.html' %}
{% block title %}Create Your Profile{% endblock title %}
{% block content %}
<h2>Create Your Profile</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Create my profile</button>
</form>
{% endblock content %}
tell me what is the problem with it, I am stucked out of it, Thank you
I believe you missed enctype in html form,
enctype="multipart/form-data"
from docs,
Note that request.FILES will only contain data if the request method
was POST, at least one file field was actually posted, and the
that posted the request has the attribute
enctype="multipart/form-data". Otherwise, request.FILES will be empty.
HTML form should be,
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Create my profile</button>
</form>
this my approach if you know how to do it please help
my views.py
def profile(request, username):
return render(request, 'profile.html')
my urls.py
from django.conf.urls import url
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
# Template Urls!
app_name = 'accounts'
urlpatterns = [
path('Skolar/',views.base, name= 'base'),
path('Register/',views.register,name='register'),
path('login/', views.my_login_view, name='login'),
path('logout/',views.user_logout,name='logout'),
path('<slug:username>',views.profile, name='profile'),
path('EditProfile/',views.update_profile,name='editprofile'),
]
error showing
Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['(?P<username>[-a-zA-Z0-9_]+)$']
in my html i use
<a class="dropdown-item" href="{% url 'accounts:profile' %}">My Account</a>
adding profile html which i want ot show user after clickin gon that link
{% extends 'masteraccount.html' %}
{% block content %}
{% load static %}
<link rel="stylesheet" href="{% static 'css/accountscss/profile.css'%}">
<div class="">
<div class="page-content">
<label class="name" for="NAME">NAME:</label>
<p>{{user.first_name}} {{user.last_name}}</p>
<label for="Email">Email:</label>
<p>{{user.email}}</p>
<label for="Twitter">Twitter:</label>
<p>{{user.profile.twitter}}</p>
<label for="Facebook">Facebook:</label>
<p>{{user.profile.Facebook}}</p>
<label for="Facebook">About:</label>
<p>{{user.profile.about}}</p>
<label for="Facebook">Date of Birth:</label>
<p>{{user.profile.dob}}</p>
</div>
<button type="button" class="btn btn-primary btn-lg">Edit Profile</button>
</div>
{% endblock %}
views.py let us assume your model is 'Profile' and your have 'user' related to one-to-one to User you should use something like:
from django.shortcuts import render,get_object_or_404
def profile(request, username):
profile = get_object_or_404(Profile,user = username)
return render(request, 'profile.html',{'profile':profile})
urls.py:
from django.conf.urls import url
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
# Template Urls!
app_name = 'accounts'
urlpatterns = [
path('Skolar/',views.base, name= 'base'),
path('Register/',views.register,name='register'),
path('login/', views.my_login_view, name='login'),
path('logout/',views.user_logout,name='logout'),
path('<slug:username>/',views.profile, name='profile'),
path('EditProfile/',views.update_profile,name='editprofile'),
]
html
<a class="dropdown-item" href="{% url 'accounts:profile' request.user.username %}">My Account</a>
Note:it is always better to use pk for the profile.but slug it is also fine
I'm getting a NoReverseMatch error in my home page. It is from the html that I injected from my announcement app. It says that the reverse of the link is cannot be found. When I removed that line It shows the card but the text with template tag.
_announcement_home.html:
<div class="container">
<div class="card announcement-card" style="width: 18rem;">
<h5 class="card-header">Announcement</h5>
<div class="card-body">
<h5 class="card-title">{{announcement.title}}</h5>
<p class="card-text">{{announcement.text}}</p>
<span class="announcement-date">{{announcement.date}}</span>
{% if user.is_authenticated %}
Change
{% endif %}
</div>
</div>
<br>
</div>
index.html:
{% extends 'base.html' %}
{% block content %}
<div class="w3-container w3-teal">
<h1>BANNER HERE</h1>
<p>Dito yung banner</p>
</div>
{% include 'announcement/_announcement_home.html' %}
{% endblock %}
urls.py:
from django.urls import path
from . import views
app_name = 'announcement'
urlpatterns = [
path('create/', views.AnnouncementCreateView.as_view(), name='create'),
path('', views.AnnouncementListView.as_view(), name='list'),
path('posts/<int:pk>/', views.AnnouncementDetailView.as_view(), name='single'),
path('delete/<int:pk>/', views.AnnouncementDeleteView.as_view(), name='destroy'),
path('edit/<int:pk>/', views.AnnouncementUpdateView.as_view(), name='edit')
]
main urls.py:
"""urcipro URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from home import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.Home.as_view(), name='home'),
path('bod/', views.BOD.as_view(), name='bod'),
path('announcement/', include('announcement.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
views.py:
from django.shortcuts import render
from django.views import generic
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy, reverse
from django.contrib import messages
from . import forms
from . import models
# Create your views here.
class AnnouncementListView(LoginRequiredMixin, generic.ListView):
model = models.Announcement
class AnnouncementDetailView(LoginRequiredMixin, generic.DetailView ):
model = models.Announcement
class AnnouncementUpdateView(LoginRequiredMixin, generic.UpdateView):
model = models.Announcement
form_class = forms.AnnouncementForm
class AnnouncementCreateView(LoginRequiredMixin, generic.CreateView ):
model = models.Announcement
form_class = forms.AnnouncementForm
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
class AnnouncementDeleteView(LoginRequiredMixin, generic.DeleteView ):
model = models.Announcement
def get_success_url(self):
return reverse('home')
def delete(self, *args, **kwargs):
messages.success(self.request, "Post Deleted")
return super().delete(*args, **kwargs)
home app views.py:
from django.shortcuts import render
from django.views.generic import TemplateView
# Create your views here.
class Home(TemplateView):
template_name = 'index.html'
class BOD(TemplateView):
template_name = 'bod.html'
This is what I see when I remove the a tag:
Error traceback:
It looks like the context has announcement to display this information, and then you used self in the url tag which isn't defined.
So change the url param to announcement.pk which we can assume will exist because that's the object in use with this block.
<div class="card-body">
<h5 class="card-title">{{announcement.title}}</h5>
<p class="card-text">{{announcement.text}}</p>
<span class="announcement-date">{{announcement.date}}</span>
{% if user.is_authenticated %}
Change
{% endif %}
</div>
How can I display images from django models on tis page datat.ru/shop ?
I the source page code see <img class='img-fluid w-100' src="/media/images/2.png" alt="img" />
But only http://datat.ru/static/media/images/2.png returns image
How can I convert src="{{ shop.cover.url }}" to static/media/images/ ???
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'),
path('shop/', views.shop_list, name='shop'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
]
models.py
from django.conf import settings
from django.db import models
from django.utils import timezone
class Company(models.Model):
title = models.TextField()
cover = models.ImageField(upload_to='images/')
def __str__(self):
return self.title
shop_list.html
{% extends 'blog/base.html' %}
{% load staticfiles%}
{% block content %}
{% for shop in shops %}
<div class="container">
<div class="row">
<img class='img-fluid w-100' src="{{ shop.cover.url }}" alt="img" />
</div>
</div>
{% endfor %}
<!-- <img class="scale-with-grid" src="{{ shop.cover.url }}"/> -->
{% endblock %}
add this to settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/
and this to urls
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I created a simple login logout app using the Out of the box django LoginView and LogoutView. In my app, I can signup using CreateView, list the users using ListView and get user details using DetailView.
I am seeing issues with login and logout when I click the browser's back button.
Issues:
Upon login, I am redirected to index page. However when I click the back button, I land back at login page and can login with other valid user.
Upon logout, I am redirected to index page. However when I click the back button, I can view the logged-in data such as the list page and details page.
The code for my app (accounts) is :
settings.py
<code>
LOGIN_REDIRECT_URL = "/accounts/"
LOGOUT_REDIRECT_URL = "/accounts/"
project urls.py
<code>
urlpatterns = [
path("admin/", admin.site.urls),
path("accounts/", include("django.contrib.auth.urls")),
path("accounts/", include("accounts.urls")),
]
app urls.py
<code>
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
app_name = 'accounts_app'
urlpatterns = [
path("", views.IndexPage_cview.as_view(), name="index_curl"),
path("login/", auth_views.LoginView.as_view(),name='login'),
path("logout/", auth_views.LogoutView.as_view(), name="logout"),
path("signup/", views.SignUp_cview.as_view(), name="signup_curl"),
path("super/", views.adminlist_cview.as_view(), name="super_curl"),
path("superdetail/<int:pk>", views.admindetail_cview.as_view(),
name="super_detail_curl"),
]
app views.py
<code>
from django.contrib.auth import login, logout
from django.urls import reverse_lazy
from django.views.generic import TemplateView,CreateView, ListView,
DetailView
from django.contrib import auth
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import get_object_or_404
from . import forms
class IndexPage_cview(TemplateView):
template_name = "accounts/index.html"
class SignUp_cview(CreateView):
form_class = forms.UserCreate_cform
success_url = reverse_lazy("login") #redirect to /accounts/login/
template_name = "accounts/signup.html"
class adminlist_cview(LoginRequiredMixin,ListView):
template_name = 'accounts/super_list.html'
model= auth.models.User
def get_queryset(self):
return auth.models.User.objects.order_by('username')
class admindetail_cview(LoginRequiredMixin,DetailView):
template_name = 'accounts/super_detail.html'
model= auth.models.User
def get_object(self):
return get_object_or_404(auth.models.User, pk=self.kwargs.get("pk"))
app model.py
<code>
from django.contrib import auth
from django.db import models
class User_cmodel(auth.models.User):
def __str__(self):
return "#{}".format(self.username)
app form.py
<code>
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
class UserCreate_cform(UserCreationForm):
class Meta:
fields = ("username", "email", "password1", "password2")
model = get_user_model()
base.html
<div class="container">
Home
<ul >
{% if user.is_authenticated %}
{% if request.user.is_superuser %}
<li><a href="{% url 'admin:index' %}" >Admin</a></li>
<li><a href="{% url 'accounts_app:super_curl' %}>Db List</a></li>
{% endif %}
<li><a href="{% url 'accounts_app:logout' %}>Log out</a></li>
{% else %}
<li><a href="{% url 'accounts_app:login'%}" >Log in</a></li>
<li>Sign up</li>
{% endif %}
</ul>
</div>
<div class="container mycontent">
{% block content %}
{% endblock %}
</div>
login.html
{% extends "base.html" %}
{% block content %}
<div class="container">
<h1>Login</h1>
<form method="POST" >
{% csrf_token %}
{% form %}
<input type="submit" value="Login" >
</form>
</div>
{% endblock %}
No where in the code, you are making the views available only for logged in user. All your views are accessible by anybody.
If you are using custom Auth backend you can use #login_required decorator from django.contrib.auth.decorators. To ensure the user is logged in before going to the view.
You should read this. https://docs.djangoproject.com/en/2.1/topics/auth/default/#authenticating-users