I want to use TinyMCE in my Django project, after doing all the necessary settings, when I visit the page, the form only render normal django form but not TinyMCE rich text form. Below are my settings.
I copied tinymce folder to media folder:
C:/Python27/Scripts/nate/media/js/tiny_mce
Settings.py
TINYMCE_JS_URL = '/media/js/tiny_mce/tiny_mce.js/'
TINYMCE_DEFAULT_CONFIG = {
'plugins': "table,spellchecker,paste,searchreplace",
'theme': "advanced",
'cleanup_on_startup': True,
'custom_undo_redo_levels': 10,
}
TINYMCE_SPELLCHECKER = True
TINYMCE_COMPRESSOR = True
urls.py
(r'^tinymce/', include('tinymce.urls')),
Models
class Finmall(models.Model):
user=models.ForeignKey(User)
name=models.CharField(max_length=250, unique=True)
content1 = models.TextField()
content2 = models.TextField()
def __unicode__(self):
return self.user
Template
<head>
<script type="text/javascript" src="{{ MEDIA_URL }}/js/tiny_mce/tiny_mce.js"></script>
</script>
</head>
{% block content %}
<div id="postcribbody" class="wrapper">
<p class="list">You can make it</p>
<form enctype="multipart/form-data" form action="." method="POST">
{% csrf_token %}
{{ FinmallForm.as_p }}
<input type="submit" class="cribput" value="Submit"/>
</form>
</div>
{% endblock %}
How can I make the content1 and content2 display TinyMCE rich text form?
An Example from the Documentation:
from django import forms
from tinymce.widgets import TinyMCE
class FinmallForm(forms.ModelForm):
...
content = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30}))
...
class Meta:
model = Finmall
The problem is that you are displaying the form as a Django form.
The rich edit text field will be a JS thing which Django will not create. The django.form feature will be create a HTML element.
I suggest manually putting the rich edit in to the template. As long as you give the rich edit the same "name" as the Django form element you can use it in the POST which is returned.
EDIT: You are publishing a models.TextField() when the form is rendered. This will generate a element in the form. This form will have only default properties.
I am not 100% sure how TinyMCE works but you would need to bind it to that element though a "id" or "name" value or just put the forms code in yourself into the template.
I myself do not use Django to render the forms I create forms myself in the template and give them the same names what Django would give them.
Look at the source code for the rendered page and see what the form looks like. Then set up a test page with TinyMCE and get it working and look at the difference between the element.
:)
Try to put above form {{ form.media }} i.e. {{ FinmallForm.media }} in your template
<head>
<script type="text/javascript" src="{{ MEDIA_URL }}/js/tiny_mce/tiny_mce.js"></script>
</script>
</head>
{% block content %}
<div id="postcribbody" class="wrapper">
<p class="list">You can make it</p>
{{ FinmallForm.media }}
<form enctype="multipart/form-data" form action="." method="POST">
{% csrf_token %}
{{ FinmallForm.as_p }}
<input type="submit" class="cribput" value="Submit"/>
</form>
</div>
{% endblock %}
Related
How do I change the login form used by django admin (want to add a captcha field)? I am using the cookiecutter template and have followed the suggestions in other SO answers, and guides:
forms.py
class AuthAdminForm(AuthenticationForm):
captcha = ReCaptchaField(widget=ReCaptchaV3)
show_something_different = forms.TextInput()
class Meta(AuthenticationForm):
fields = ('email', 'password', 'show_something_different', 'captcha')
urls.py
from django.contrib import admin
from myapp.forms import AuthAdminForm
admin.autodiscover()
admin.site.login_form = AuthAdminForm
admin.site.login_template = 'admin/login.html'
urlpatterns = [
# Django Admin, use {% url 'admin:index' %}
path(settings.ADMIN_URL, admin.site.urls),
...]
I was able to add admin/login.html to my templates dir and extend it. This works to add the google js to the header (can see it in source). But the captcha field and my dummy extra field don't show up.
I was on the right track, but what caught me out is that the login.html template doesn't render every field present in the form (this is why my dummy test field never showed up). So instead of extending login.html, I copied the entire contents to my own file in templates/admin/login.html, then added the captcha field manually:
<form action="{{ app_path }}" method="post" id="login-form">{% csrf_token %}
<div class="form-row">
{{ form.captcha }}
{{ form.username.errors }}
{{ form.username.label_tag }} {{ form.username }}
</div>
base.html can be extended like this:
{% block extrahead %}
<script async src="https://www.googletagmanager.com/gtag/js?id=G-xxx"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-xxx');
</script>
{% endblock %}
Now, finally, captcha is on my admin login page.
I'm learning Django and web dev and having difficulty configuring the fields in Django forms.Form so that they come out correctly. Below is my code:
Even if I adjust my attrs rows and cols in forms.Textarea it doesn't make any difference. Also, it doesn't seem to matter what I put in CSS the output is still the same.
class NewPageForm(forms.Form):
title = forms.CharField(label="Title", max_length=100, widget=forms.TextInput)
content = forms.CharField(label="Content", widget=forms.Textarea(attrs{"rows":3,"cols":10}))
My html:
{% block body %}
<div class="form">
<form action="{% url 'create' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type = submit>
</form>
</div>
{% endblock %}
What it looks like:
Please advise.
You may try:
content = forms.CharField(label=False, widget=forms.Textarea(attrs={'rows': 3}))
or even add a CSS class to customize it:
content = forms.CharField(label=False, widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 3}))
I'm working on a django bookstore website and there seems to be an error with stripe integration. I have an orders page that asks for payment information (I'm using the test API for now). I get the same error "You did not set a valid publishable key. Call Stripe.setPublishableKey() with your publishable key."
orders/views.py
from django.conf import settings
from django.views.generic.base import TemplateView
class OrdersPageView(TemplateView):
template_name = 'orders/purchase.html'
def get_context_data(self, **kwargs):
##Stripe.setPublishableKey('PUBLISHABLE_KEY')
context = super().get_context_data(**kwargs)
context['stripe_key'] = settings.STRIPE_TEST_PUBLISHABLE_KEY
return context
templates/orders/purchase.html
{% extends '_base.html' %}
{% block title %}Orders{% endblock title %}
{% block content %}
<h1>Orders page</h1>
<p>Buy for $39.00</p>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ stripe_key }}"
data-description="All Books"
data-amount="3900"
data-locale="auto">
</script>
{% endblock content %}
In your forms you need a {% csrf_token %} and form action that takes you to the charge page.
<form action="{% url 'charge' %}" method="post">
{% csrf_token %}
<h1>Orders page</h1>
<p>Buy for $39.00</p>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ stripe_key }}"
data-description="All Books"
data-amount="3900"
data-locale="auto">
</script>
</form>
Also unless never set your pricing in your templates, this is asking for trouble. Set them in your view.
For almost 5h I can't make detail view.
My app name -movies
My views:
"
def actor_view(request):
actor_list = Actor.objects.all()
context = {'actor_list': actor_list}
return render(request,'movies/actor.html',context)
def actor_detail_view(request,id):
actorrr=get_object_or_404(Actor,id=id)
context={
'actorrr':actorrr,
}
return render(request,"movies/actor_detail_view.html",context)
My model
class Actor(models.Model):
name = models.CharField(max_length=50)
date_of_birth = models.DateField()
age=models.IntegerField( null=True)
net_worth = models.TextField(max_length=140, null=True)
picture=models.URLField(default = '')
children =models.TextField(max_length=140, null=True)
marital_status=models.TextField(max_length=140, null=True)
My actor html:
{% load static %}
{% block mainbody %}
{% for actor in actor_list %}
<!DOCTYPE html>
<html>
<head>
<title>List of actors we have</title>
<link rel="stylesheet" href="{% static 'css/style_actor.css' %}">
</head>
<body>
<div class="card" >
<div class="card-image">
<img src="{{ actor.picture }}" alt="No poster in datebase" width="289" height="345">
</div>
<div class="card-text">
<h2>
{{ actor.name }}
</h2>
<p>{{movie.pilot}}</p>
</div>
<div class="card-imdb-score">
<p
>Age: {{ actor.age }}
</p>
</div>
</div>
</body>
</html>
{% endfor %}
{% endblock %}
My actor_detail html
<h6>TEST</h6>
movies url:
path('actor_detail_view/<int:id>',views.actor_detail_view,name='actor_detail_view'),
and the main url:
path('<int:id>/',views.actor_detail_view,name="actor_detail_view")
So I have no idea how to make urls and what to place in actor.html in href url.I've made many tutorials and still couldn't do it.
First of all, I recommends to you set the name of variable actorrr correctly.
If you're using Pycharm IDEA, the idea helps you to avoid problems with names of variables or spaces, following PEP08.
Some tips:
verify your urls.py file, to see if exists "/movies/actor_detail/{{actor.id }}
Probably, you have to add django template structure to appear the data of actor detail HTML, without for looping, because it's just one data.
your link to the actor detail page must be like this :
<a href={% url 'actor_detail_view' actor.id %}
also it's better to use django generic views to get detailed models.
I recommend you use CBVs, in this case, DetailView, I had same project and I put code here to use:
class DetailedActor(DetailView):
template_name = 'your_template'
model = models.YourModel
def get_context_data(self, *, object_list=None, **kwargs):
context = super().get_context_data(**kwargs)
return context
then in your template, you have an instance of your model whit a specific actor! just don't forget to pass the id when you render to the URL assigned to this view
I am trying to implement django-autocomplete-light in my projects but cannot figure out why it does not show me the autocomplete widget, but keeps showing an empty dropdown.
I followed the tutorial: https://django-autocomplete-light.readthedocs.io/en/3.1.3/tutorial.html.
I found that this problem has occurred in other stackoverflow questions, but none of those answers have helped me so far.
I have the following model:
class Vilt(models.Model):
vilt_title = models.CharField(max_length=200, unique=True)
I created this autocomplete view:
class ViltAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
# Don't forget to filter out results depending on the visitor !
# if not self.request.user.is_authenticated():
# return Vilt.objects.none()
qs = Vilt.objects.all().order_by('vilt_title')
if self.q:
qs = qs.filter(vilt_title__istartswith=self.q)
return qs
I use this ModelForm where I specify the widget.
from .models import Vilt
from dal import autocomplete
class ViltSearchForm(forms.ModelForm):
vilt_title = forms.ModelChoiceField(
queryset = Vilt.objects.all(),
widget = autocomplete.ModelSelect2(url='vilt-autocomplete')
)
class Meta:
model = Vilt
fields = ('vilt_title',)
from .views import (ViltAutocomplete,
)
urlpatterns = [
#other paths
path('vilt/autocomplete/', ViltAutocomplete.as_view(), name='vilt-autocomplete'),
#other paths
]
{% extends "bierviltje/base.html" %}
{% load static %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container">
#other forms
<div>
<form action="" method="post">
{% csrf_token %}
{{ vilt_search_form|crispy }}
<input type="submit" />
</form>
</div>
#other forms
</div>
{% endblock content %}
{% block javascript %}
{{ vilt_search_form.media }}
{% endblock javascript %}
This is the Javascript that is loaded in before the javascript block in base.html:
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
{% block javascript %}
{% endblock javascript %}
It's been sometime since you posted your query. But in case you have not found the answer yet, here is the solution:
In your ModelForm "ViltSearchForm", please change the widget from:
widget = autocomplete.ModelSelect2(url='vilt-autocomplete')
to:
widget = autocomplete.ListSelect2(url='vilt-autocomplete')
However, if I may add here, I can't fathom the reason for using "autocomplete" on a stand alone model.
A feedback would be much appreciated.