I have setup django-summernote on my project and everything is great, it works very good on admin , but i want to use it on my templates.
Note :
in django-summernote documentation they only explain how to use it if you have forms.py file but I dont
my main urls.py :
urlpatterns = [
path('games/', include('core.urls', namespace='core')),
path('summernote/', include('django_summernote.urls')),
]
my app(name=core) urls.py :
from django.urls import path
from . import views
app_name = 'core'
urlpatterns = [
path('new/', views.GameCreate.as_view(), name='game_new'),
path('<int:pk>/edit/', views.GameUpdate.as_view(), name='game_edit'),
]
my views.py :
class GameCreate(LoginRequiredMixin, CreateView):
model = Game
template_name = 'core/game_new.html'
fields = '__all__'
redirect_field_name = 'home'
class GameUpdate(LoginRequiredMixin, UpdateView):
model = Game
template_name = 'core/game_edit.html'
fields = '__all__'
my template file "game_new.html" :
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %} Add New Game {% endblock %}
{% block main %}
<section class="main-section">
<div class="container">
<h1>New Game</h1>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form|crispy }}
<input type='submit' value="Save" />
</form>
</div>
</section>
{% endblock %}
my template file "game_edit.html":
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %} Game Info {% endblock %}
{% block main %}
<section class="main-section"></section>
<div class="container">
<h1>Edit Game Info</h1>
<form action="" method="post">
{% csrf_token %}
{{ form|crispy }}
<input type="submit" value="Update" />
</form>
</div>
</section>
{% endblock %}
my Models.py :
from django.db import models
from django.urls import reverse
# Create your models here.
class Game(models.Model):
name = models.CharField(max_length=140)
developer = models.CharField(max_length=140)
game_trailer = models.CharField(max_length=300, default="No Trailer")
game_story = models.TextField(default='No Story')
Firstly in your template dont forgate to add this:
{{ form.media }} <<<------ To load all js and css attached
In the document your models you must herit summernote widget. Example:
from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget
class FormFromSomeModel(forms.ModelForm):
class Meta:
model = SomeModel
widgets = {
'foo': SummernoteWidget(),
'bar': SummernoteInplaceWidget(),
}
Related
I'm a beginner Django. And I got a problem with rendering to the template.
I have a model(models.py) which has the class "FuelInfo"; includes ForeignKey.
from django.db import models
class Traveler(models.Model):
traveler_name = models.CharField(max_length=10)
def __str__(self):
return self.traveler_name
class FuelInfo(models.Model):
name = models.ForeignKey(Traveler, on_delete=models.SET_NULL, null=True)
car = models.CharField(null=True, max_length=50)
efficiency = models.FloatField()
def __str__(self):
return str(self.name)
Also views.py is like :
from django.shortcuts import render, get_object_or_404
from .models import FuelInfo
def traveler_list(request):
travelers = FuelInfo.objects.all()
context = {'travelers':travelers}
return render(request, 'fuelcost/home.html', context)
def traveler_detail(request, pk):
traveler = get_object_or_404(FuelInfo, pk=pk)
return render(request, 'fuelcost/calfuel.html', {'traveler': traveler})
And urls.py is :
from django.urls import path
from . import views
app_name = 'fuelcost'
urlpatterns = [
path('', views.traveler_list, name='home'),
path('<int:pk>/', views.traveler_detail, name='calfuel'),
]
I want to make a dropdown that is render to template "calfuel.html" in home.html.
So I made a template("home.html") like :
{% extends "base_generic.html" %}
{% block content %}
<body>
{% if travelers %}
<form method="POST" action="{% url 'fuelcost:calfuel' pk=traveler.pk %}">
{% csrf_token %}
<select name="traveler">
{% for traveler in travelers %}
<option value="{{ traveler.id }}">{{ traveler.name }}</option>
{% endfor %}
</select>
<input type="submit" value="Select" />
</form>
{% else %}
<p>No travelers are available</p>
{% endif %}
</body>
{% endblock %}
But it doesn't works and i received error.
(My urlpattern is fuelcost/.)
Actually I can go into fuelcost/1 or fuelcost/2 that is views.traveler_detail named "calfuel". But I can't go into fuelcost/ that is views.traveler_list named "home".
I don't know what I have to do more. plz, tell me what is wrong with this.
{% block content %}
<body>
{% if travelers %}
{% for traveler in travelers %}
<form method="POST" action="{% url 'fuelcost:calfuel' pk=traveler.pk %}">
{% csrf_token %}
<select name="traveler">
<option value="{{ traveler.id }}">{{ traveler.name }}</option>
</select>
<input type="submit" value="Select" />
</form>
{% endfor %}
{% else %}
<p>No travelers are available</p>
{% endif %}
</body>
{% endblock %}
you have to keep the form inside loop so that it can get pk of traveler
I am using tinymce for my web blog that allows me to post my blogs, but as I post they are shown in rawHTML format like below:
this is my template
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block styler %}
{% endblock styler%}
{% block content %}
<div class="content-section">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset>
<legend class="border-bottom pb-3 mb-3">Post blog</legend>
{{ form|crispy }}
</fieldset>
<button class="btn btn-outline-info" type="submit">Post</button>
</form>
</div>
{% endblock content %}
and my forms.py
class PostCreateForm(forms.ModelForm):
title = forms.CharField()
content = forms.CharField(
widget=TinyMCEWidget(
attrs={'required': False, 'cols': 30, 'rows': 10}
)
)
thumbnail = forms.ImageField()
class Meta:
model = Post
fields = ['title', 'content', 'thumbnail']
and associated views.py
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
form_class = PostCreateForm
help me how to solve this problem, I searched a bit and find out this could be due to #Html.Raw(#Model.LongDescription) but I don't know either where do I have to add that? and please check if you can do any improvement for my code.
thank you for your help.
Usually you just need to add safe tag: {{ content|safe }}
Or you can wrap html in autoescape tag:
{% autoescape off %}
{{ content }}
{% endautoescape %}
This is my forms:
class signup_form(forms.ModelForm):
bio = forms.TextInput()
class Meta:
model = User
fields = ['username',
'password',
'first_name',
'last_name',
'email',
'date_joined']
And This one is my template page:
urlpatterns = [
......
url(r'^profile/(?P<username>[\w\-]+)/$', user_profile, name='user_profile'),
]
And this is signup template page:
{% extends parent_template|default:"tick/base_tick.html" %}
{% block title %}
{{ block.super }} ---> Sign Up HERE!!
{% endblock %}
{% block content %}
<div>
<div>
<form action="{% url 'user_profile' username={{ form.username }} %}" method="post">
{% csrf_token %}
{{form.as_p}}
<button type="submit">Create User</button>
</form>
</div>
</div>
{% endblock %}
As you can see in the 'action' part of the form i want to access to the 'username' field of 'form' but i can't and the Django get me some error.
What Should I do?
Edit: This is the Error
Value of a field is accessed by form.field_name.value. Use can update your code by below code
<form action="{% url 'user_profile' username=from.username.value %}" method="post">
{% csrf_token %}
{{form.as_p}}
<button type="submit">Create User</button>
</form>
I have a lots of apps, but I want to generate all app's data on my homepage. Here's my apps:blog,members
I want to show blogs and my members on my homepage
I know that if I want to generate one app's data,I can do this:
blog/urls.py:
urlpatterns = [
url(r'^$', ListView.as_view(
queryset=Post.objects.all().order_by("-date")[:10],
template_name='blog1.html')),
and in blog1.html:
{% extends "index.html" %}
{% block blog %}
{% for post in blog_post %}
<div id="blog-wrapper" class="bgrid-third s-bgrid-half mob-bgrid-whole group">
<article class="bgrid">
<h5>{{ post.date }} </h5>
<h3><div class = "entry-title">{{ post.title }}</div></h3>
<p>{{ post.user }}</p>
<p><div class = "post_body">{{ post.body|safe|linebreaks }}</div></p>
</article>
</div>
{% endfor %}
{% endblock %}
{% block member %}
Here when I go to the url,I can see all blogs I write,but now I want to see blogs and members(another app) on one page, so how can I do this?
I would suggest you to use ListView's get_context_data method.
Create view in your project's views.py:
from django.views.generic import ListView
# Import your models here.
class HomepageView(ListView):
model = Post
ordering = '-date'
template_name = 'blog1.html'
context_object_name = 'posts'
def get_context_data(self, **kwargs):
context = super(HomepageView, self).get_context_data(**kwargs)
context['members'] = Member.objects.all()
return context
def get_queryset(self):
return super(HomepageView, self).get_queryset()[:10]
Then, change urls.py:
from django.conf.urls import url
# Import ``HomepageView`` here.
urlpatterns = [
url(r'^$', HomepageView.as_view(), name='homepage'),
# Other patterns here.
]
Now you can access posts using posts variable and members using members variable.
from .models import Post
from member.models import UserProfile
def get_data():
return {
"post": Post.objects.all().order_by("-date")[:10],
"user": UserProfile.objects.all()[:10]
}
then in my blog1.html:
{% extends "index.html" %}
{% block blog %}
{% for post in object_list.post %}
<div id="blog-wrapper" class="bgrid-third s-bgrid-half mob-bgrid-whole group">
<article class="bgrid">
<h5>{{ post.date }} </h5>
<h3><div class = "entry-title">{{ post.title }}</div></h3>
<p>{{ post.user }}</p>
<p><div class = "post_body">{{ post.body|safe|linebreaks }}</div></p>
</article>
</div>
{% endfor %}
{% endblock %}
{% block member %}
{% for post in object_list.user %}
<div class="bgrid member">
<div class="member-header">
<div class="member-pic">
<img src="{{ post.portrait }}" alt=""/>
</div>
<div class="member-name">
<h3>{{ post.user }}</h3>
<span>Creative Director</span>
</div>
</div>
<p>{{ post.intro }}</p>
<ul class="member-social">
<li><i class="fa fa-google-plus"></i></li>
<li><i class="fa fa-github"></i></li>
</ul>
</div> <!-- /member -->
{% endfor %}
{% endblock %}
I can't make my homepage show data from both my HomePage and IconBlurb models. I've been stucked on this problem for two days and couldn't figure it our. Please help me. Thanks.
This is my models.py
class HomePage(models.Model):
heading = models.CharField(max_length=200,
help_text="The heading under the icon blurbs")
subheading = models.CharField(max_length=200,
help_text="The subheading just below the heading")
introduction = models.TextField(help_text="首页的欢迎文字。")
introLink = models.URLField(max_length=200, blank=True)
class Meta:
verbose_name= _("Home page")
verbose_name_plural = _("Home pages")
This is my views.py
from django.shortcuts import get_object_or_404, render
from homepage.models import HomePage, IconBlurb
def index(request):
homepage = get_object_or_404(HomePage)
return render(request, 'homepage/index.html', {'homepage':homepage})
def blurb(request):
latest_iconblurb = IconBlurb.objects.all()
context = {'latest_iconblurb': latest_iconblurb}
return render(request, 'homepage/blurb.html', context)
This is my urls.py
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
)
This is my index.html
{% extends "base.html" %}
{% block all_content %}
<div class="jumbotron">
<div class="container">
<h1>{{ homepage.heading }}</h1>
<p>{{ homepage.introduction }}</p>
<p><a class="btn btn-primary" href="/courses">开始学习</a></p>
</div>
</div>
<div class="container">
<div class="row">
{% block blurb %}{% endblock %}
</div>
</div>
{% endblock %}
This is my blurb.html
{% extends "homepage/index.html" %}
{% block blurb %}
{% if latest_iconblurb %}
{% for blurb in latest_iconblurb %}
<div class="col-md-4">
<h2>{{ blurb.title }}</h2>
<p>{{ blurb.content }}</p>
</div>
{% endfor %}
{% endif %}
{% endblock %}
This is simple. Write both function code in a single function.
def index(request):
homepage = get_object_or_404(HomePage)
latest_iconblurb = IconBlurb.objects.all()
context = {'latest_iconblurb': latest_iconblurb; 'homepage':homepage}
return render(request, 'homepage/blurb.html', context)