I'm confused with why my HTML template is not showing up.
I'm trying to learn Class base views instead of functions on Django.
I know the URL is working because {% extend base.html %} is showing, but anything else like the h1 tags aren't showing up in the render?
Can anyone help please.
views.py
from django.shortcuts import render
from django.views import View
from django.views.generic import (
CreateView,
DetailView,
ListView,
UpdateView,
ListView,
DeleteView
)
from .models import Article
class ArticleListView(ListView):
template_name = 'article/article_list.html'
queryset = Article.objects.all()
url.py
from django.contrib import admin
from django.urls import path
from .views import (
ArticleListView
)
app_name = 'article'
urlpatterns = [
path('', ArticleListView.as_view(), name = 'article_list'),
article_list.html
{%extends 'base.html'%}
<h1> Test </h1>
<h1> Test </h1>
{%block content%}
{% for instance in object_list %}
<p>{{instance.id}} - <a href = '{{instance.get_absolute_url}}'> {{instance.title}} </a></p>
{%endfor%}
{%endblock%}
[This is the outcome when i request get html, The current html is coming from base.html][1]
[1]: https://i.stack.imgur.com/W09EE.png
Use this code in the view:
context_object_name = 'article'
model = models. Article
And use this is in the template:
article. Id
{{article.get_absolute_url}}
Related
I am making a simple site to experiment with manipulating user data. I have a form where the user enters in some info and once they hit submit they get redirected to a new page. On this new page, the info they entered is supposed to be displayed. I am under the impression that you use this {{ Modle_Name.Fild_name}} to inject the info into the HTML. However, it is not working. If any of y'all have a solution I would much appreciate it.
sucseus.html
{% extends "base.html" %}
{% block content %}
<h1>success</h1>
<h2>{{ post.message }}</h2>
{% endblock %}
views.py
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views import generic
from . import forms
from forums_simple.models import Post
# Create your views here.
class Form(generic.CreateView):
model = Post
template_name = 'forums_simple/form.html'
fields = ['message']
success_url = reverse_lazy('forums:sucsseus')
class Sucsessus_view(generic.TemplateView):
template_name = 'forums_simple/sucseus.html'
model = Post
models.py
from django.db import models
# Create your models here.
class Post(models.Model):
message = models.TextField(blank=True, null=False)
created_at = models.DateTimeField(auto_now=True)
You need to pass it as a context. The best way to do it is via DetailView.
class Sucsessus_view(generic.DetailView):
template_name = 'forums_simple/sucseus.html'
model = Post
urls:
urlpatterns = [
...
path('post/<int:pk>/', Sucsessus_view.as_view(), name='sucsseus'),
...
]
here are my URLs
from django.contrib import admin
from django.urls import path, include
from . import views
app_name = 'forums'
urlpatterns = [
path('sucseuss/<int:pk>/', views.Sucsessus_view.as_view(), name='working'),
path('forum/', views.Form.as_view(), name='form')
]
Ignore the title. I got problem on displaying text written and save on admin page.
I just create new app with name about. using command python manage.py startapp about
and all the below files are inside this app.
Models.py
from django.db import models
# Create your models here.
class About(models.Model):
title = "About me"
discription = models.TextField()
def __str__(self):
return self.title
admin.py
from django.contrib import admin
from .models import About
# Register your models here.
admin.site.register(About)
# Register your models here
views.py:
from django.shortcuts import render
from django.http import HttpRequest
from .models import About
# Create your views here.
def about(request):
abouts = About.objects.all()
return render(request, 'about/about.html', {'abouts': abouts})
urls.py
from django.urls import path
from . import views
app_name = 'about'
urlpatterns = [
path('', views.about, name='about'),
]
about.html
<p style="color: white;">{{ abouts.discription }}</p>
Problem is that the text written inside discription didn't showing on about.html page. please help me.
{{ abouts }} is a queryset. The following code iterates over each item inside the queryset, thus creating a list.
<ul>
{% for about in abouts %}
<li>{{ about.description }}</li>
{% endfor %}
</ul>
How does the CreatePostView in views.py link to the post_form.html.
It does not have "template_name" in it still how does the createpostview links to the post_form.html?
Please look into the following codes that i have added below, and let me know if you can help, Thankyou!
Views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from .models import Post, Comment
from .forms import PostForm, CommentForm
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
class CreatePostView(LoginRequiredMixin,CreateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
form_class = PostForm
model = Post
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('post/new/', views.CreatePostView.as_view(), name='post_new'),
]
post_form.html
{% extends 'blog/base.html' %}
{% block content %}
<h1>New post</h1>
<form method="POST" class="post-form">
{% csrf_token %}
{{form.as_p}}
<button type="submit" class="save btn btn-default">Save</button>
</form>
<script>var editor = new MediumEditor('.editable');</script>
{% endblock %}
Please help me understand this.
For a model Post in app myapp, the CreateView will use the template myapp/post_form.html.
This is just the documented behaviour of CreateView.
You might find it useful to look at the get_template_names method on the ccbv website to understand how the code works.
What I would like to have is an admin panel that I create where only users with permissions set to "admin" in the UserLevel model can edit certain aspects of the website. However, while I think I have everything coded out properly it isn't working. The way I'm trying to implement this already work on the main content section of my site. My best guess is that since I'm trying to cross-use views between apps something got mixed up, although that may be wrong. Also please keep in mind that while I definitely started with clean code which emulated the code from the working parts of the site this code may not so clean because I have been playing around with it so much that I'm just flat out confused... so any help would be much appreciated.
To be clear, there's no error with the site which is why I think the code is written correctly. However, I made a test widget which is not displaying on the home page at all (it's supposed to), nor will it display on the admin panel page I setup (which is supposed to display any widgets there may be), and I can't get the form for adding a new widget to display on the admin panel page either (it gives me a button to go to another page that has the form on it).
Project urls.py:
"""colors URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from accounts import views
from colorsets import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',views.PostListView.as_view(),name='index'),
url(r'^accounts/',include('accounts.urls',namespace='accounts')),
url(r'^colorsets/',include('colorsets.urls',namespace='colorsets')),
url(r'^adminpanel/',include('adminpanel.urls',namespace='adminpanel')),
]
Adminpanel app urls.py:
from django.conf.urls import url
from adminpanel import views
app_name = 'adminpanel'
urlpatterns = [
url(r'^settings/',views.SettingsListView.as_view(),name='settings'),
url(r'^new/$',views.CreateWidgetView.as_view(),name='create-widget'),
url(r'^delete/$',views.DeleteWidget.as_view(),name='delete-widgets'),
]
Adminpanel app views.py:
from django.shortcuts import render
from adminpanel.forms import WidgetForm
from adminpanel.models import Widget
from django.utils import timezone
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse,reverse_lazy
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from braces.views import SelectRelatedMixin
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
# Create your views here.
class CreateWidgetView(LoginRequiredMixin,CreateView):
login_url = '/login/'
redirect_field_name = 'index.html'
form_class = WidgetForm
model = Widget
def form_valid(self,form):
self.object = form.save(commit=False)
self.object.save()
return super().form_valid(form)
class SettingsListView(ListView):
login_url = '/login/'
redirect_field_name = 'index.html'
form_class = WidgetForm
model = Widget
def form_valid(self,form):
self.object = form.save(commit=False)
self.object.save()
return super().form_valid(form)
def get_query(self):
return Widget.object.filter(order_by('widget_order'))
class DeleteWidget(LoginRequiredMixin,SelectRelatedMixin,DeleteView):
model = Widget
select_related = ('Widget',)
success_url = reverse_lazy('settings')
def get_queryset(self):
queryset = super().get_query()
return queryset.filter(user_id=self.request.user.id)
def delete(self):
return super().delete(*args,**kwargs)
Colorsets app views.py (Where I started mixing things):
from django.shortcuts import render
from colorsets.forms import ColorForm
from colorsets import models
from colorsets.models import ColorSet
from adminpanel.models import Widget
from django.utils import timezone
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse,reverse_lazy
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from braces.views import SelectRelatedMixin
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
# Create your views here.
#def index(request):
# return render(request,'index.html')
class PostListView(ListView):
model = ColorSet
model = Widget
def get_queryset(self):
return ColorSet.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
return Widget.objects.filter(order_by('widget_order'))
class CreateColorSetView(LoginRequiredMixin,CreateView):
login_url = '/login/'
redirect_field_name = 'index.html'
form_class = ColorForm
model = ColorSet
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 DeletePost(LoginRequiredMixin,SelectRelatedMixin,DeleteView):
model = models.ColorSet
select_related = ('user',)
success_url = reverse_lazy('index')
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(user_id=self.request.user.id)
def delete(self,*args,**kwargs):
return super().delete(*args,**kwargs)
Adminpanel app models.py:
from django.db import models
# Create your models here.
class Widget(models.Model):
name = models.CharField(max_length=50)
widget_order = models.IntegerField(default=0)
body = models.TextField(max_length=500)
def __str__(self):
return self.name
widget_list.html:
{% extends "base.html" %}
{% block content %}
<div class="container">
<div class="content">
{% for widget in widget_list %}
<p>{{ widget.body }}</p>
{% endfor %}
</div>
</div>
{% endblock %}
_post.html:
<div class="post media">
<div class="media-body">
<strong>{{ colorset.user.username }}</strong>
<div class="media-footer">
{% if user.is_authenticated and UserLevels.access_level == 'admin' %}
<a href="{% url 'colorsets:delete' pk=colorset.pk %}" title="delete" class="btn btn-simple">
Delete
</a>
{% endif %}
</div>
</div>
</div>
widget_form.html:
{% block content %}
<div class="colorset-base">
<h2>Create new widget</h2>
<form id="postForm" action="{% url 'adminpanel:create-widget' %}" method="POST">
{% csrf_token %}
{{ form }}
<button type="submit" class="submit btn btn-primary btn-large">Add Widget</button>
</form>
</div>
{% endblock %}
settings.html:
{% extends "base.html" %}
{% block content %}
<div class="container">
<h2>Settings:</h2>
</div>
{% endblock %}
widget_confirm_delete.html:
{% extends 'base.html' %}
{% block content %}
<h3>Are you sure you want to delete this widget?</h3>
<div class="posts">
{% include "adminpanel/_post.html" with post=object hide_delete=True %}
</div>
<form method="POST">
{% csrf_token %}
<input type="submit" value="Confirm Delete" class="btn btn-danger btn-large" />
<a class="btn btn-simple btn-large" href="{% url 'adminpanel/settings'%}">Cancel</a>
</form>
{% endblock %}
I know not everything is being used by things but this is everything I have.
So I've got a basic Django website setup that displays dynamic info from the database.
I would like to be able to manipulate the text coming out of the database so I can create BBCode parsers or whatever else I want. I'm pretty new to Django so I'm a little confused as to where this should be done.
These are my files so far...
Models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=140)
body = models.TextField()
date = models.DateTimeField()
def __str__(self):
return self.title
Urls.py
from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from forum.models import Post
urlpatterns = [
url(r'^$', ListView.as_view(queryset=Post.objects.all().order_by("-date")[:25], template_name="forum/forum.html")),
url(r'^(?P<pk>\d+)$', DetailView.as_view(model = Post, template_name = 'forum/post.html')),
]
Forum.html
{% extends "layout.html" %}
{% block body %}
{% for post in object_list %}
<p>{{ post.date|date:"Y-m-d" }} {{ post.title }}</p>
{% endfor %}
{% endblock %}
Functions.py
def bbcode(data):
data2 = data + "some random text"
return data2
All of those files are located inside of the "forum" directory located in the root project folder which is "coolsite".
So my understanding is that I need to import functions.py somewhere and use the bbcode() method to manipulate text being pulled from the database. That way it has been parsed once displayed on the "forum.html" template.
Sorry if this is a duplicate question. I searched around and couldn't quite find what I was looking for.
How should I go about doing this exactly?
You need to override the ListView methods. You will need to do some changes in your code:
Set a custom view to your url config
urls.py
from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from forum.models import Post
from forum.views import PostList
urlpatterns = [
url(r'^$', PostList.as_view(), name='post_list'),
url(r'^(?P<pk>\d+)$', DetailView.as_view(model = Post, template_name = 'forum/post.html')),
]
Create a custom view in your app (forum.views) based in a ListView
# views.py
from django.views.generic import ListView
from forum.models import Post
class PostList(ListView):
model = Post
template_name = "forum/forum.html"
# here is where magic happens
def get_context_data(self, *args, **kwargs):
context = super(PostList, self).get_context_data(*args, **kwargs)
# context has the same context that you get in your template before
# so you can take data and work with it before return it to template
return context
You can found docs for Class-Based Views here