Django-ckeditor showing content as textarea - django

I'm working with django ckeditor now and I can't display content that can be saved normally and is displayed in the admin panel. Content is always displayed as textarea
As you can see at the image, editor is working properly, also if i go to admin panel everything is OK, but if i want to display content of "body" ({{ form.body|safe}}), it will display only textarea of HTML code.
models.py
class Stage(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
game_id = models.ForeignKey(Game,
on_delete=models.CASCADE)
name = models.CharField(max_length=128)
sequence = models.IntegerField(null=False)
body = RichTextUploadingField(config_name='LeftFields', blank=True, null=True)
def get_questions(self):
return Question.objects.filter(stage_id = self.id)
def __str__(self):
return str(self.name)
forms.py
class StageForm(ModelForm):
class Meta:
model = Stage
fields = ['body','name']
widgets = {
'name': TextInput(attrs={
'class': "left_input",
'style': "width: 69.3%;",
}),
}
views.py
#login_required(login_url='/signin')
#user_passes_test(lambda u: u.is_staff)
def edit(request, gameid,id):
stage = Stage.objects.get(pk=id)
if request.method == 'POST':
form = StageForm(request.POST, instance=stage)
if form.is_valid():
form.save()
return redirect('/edit/' + gameid + '/' + id)
form = StageForm(instance=stage)
return render(request, "homeSuperuser/edit_stage.html", {'stage': stage, 'form': form,'gameid':gameid})
edit_stage.html
<!doctype html>
<html>
<head> {% load static %}
<link rel="stylesheet" href="{% static 'css/edit_pages.css' %}" />
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script type="text/javascript" src="{% static 'js/edit.js' %}"></script>
</head>
<body>
<div class="row" id="mainDIV">
<form id="main" method="post" action="{{ request.path }}">
{% csrf_token %}
<div class="divs">
<a>Název: </a>
{{ form.name}}
</div>
<div class="divs"><a>Kontent:</a>
{{ form.media }}
{{ form.body}}
</div>
<div class="div_cent"><input type="submit" value="Uložit" class="subm" /></div>
</form>
</div>
{{ form.body|safe}}
</body>
</html>

form.body is the field itself, so includes the HTML textarea markup.
Instead of
{{ form.body|safe}}
try
{{ form.body.value|safe}}

Related

Django with bootstrap DateTimePicker: inputElement.dataset is undefined

When I try to add options to dateTimePicker it stops working. Website raise "Something went wrong! Check browser console for errors. This message is only visible when DEBUG=True", and when I enter the console on the browser I see this:
Uncaught TypeError: inputElement.dataset is undefined
and the error picks up from https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css
in the datapicker-widget.js file
class Topic(models.Model):
speaker = models.ForeignKey(Profile, on_delete=models.SET(GUEST_ID))
seminar = models.ForeignKey(Seminar, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
description = models.TextField(default='')
speaker_name = models.CharField(max_length=200, default='')
date = models.DateTimeField(null=True, blank=True)
def __str__(self):
return self.title
class TopicCreateView(LoginRequiredMixin, CreateView):
model = Topic
form_class = TopicPageForm
template_name = 'seminar/topic_form.html'
def get_initial(self, *args, **kwargs):
initial = super(TopicCreateView, self).get_initial(**kwargs)
initial = initial.copy()
initial['speaker'] = self.request.user.profile
initial['speaker_name'] = self.request.user
initial['date'] = datetime.datetime.now()
return initial
...
`
{% extends "seminar/base.html" %}
{% load django_bootstrap5 %}
{% load crispy_forms_tags %}
{% block head_content %}
{% endblock %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Topic</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Save</button>
</div>
</form>
</div>
{% endblock content %}
head
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" type='text/css' href="{% static 'users/style.css' %}">
<link rel="stylesheet" type='text/css' href="{% static 'seminar/main.css' %}">
bottom body
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
{{ form.media }}
As long as it doesn't add defaultDate in the options it doesn't display the error. The same is true if I want to add autoclose and many other options. (what type i should use in attrs?)
class TopicPageForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TopicPageForm, self).__init__(*args, **kwargs)
class Meta:
model = Topic
fields = ['speaker', 'title', 'description', 'date', 'speaker_name']
template_name = 'seminar/topic_form.html'
widgets = {
'date': DateTimePickerInput(
attrs={'class': 'form-control input-sm', 'type': 'dataTime'},
options={
"format": "YYYY/MM/DD HH/mm", # moment date-time format
'defaultDate': True,
},
)
}
How to use other options?

Customer registration with dynamic forms django

By entering the phone number in the customer registration form , if the customer already exists then should fill the rest of the fields by fetching it from the backend. if the user does not exists then have to register. help me with the script used for this
this is the model i have.
class Customers(models.Model):
customer_id = models.AutoField(primary_key=True)
cname = models.CharField(max_length=100)
cnumber= models.IntegerField()
caddress= models.CharField(max_length=100)
I m using the modelform here.
class CustForm(forms.ModelForm):
class Meta:
model=Customers
fields = '__all__
this is my view
def customer(request):
form=CustForm()
if request.method=='POST':
form = CustForm(request.POST)
form
if form.is_valid():
form.save(commit=True)
messages.success(request,'successfully customer added')
return render(request,'hello.html')
else:
messages.error(request,'Invalid')
return render(request,'custdata.html',{'form':form})
This is my html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{% block content %}
<div>
<center><h2><b>Add Customer</b></h2></center>
<p><form method='post'>
{% csrf_token %}
<center>
{{form.as_p}}
<button type="submit" style="width:200px; height:30px; font-size: 20px;">ADD</button>
</center>
</form>
</div>
{% endblock %}
</body>
</html>```

Django giving "IntegrityError NOTNULL constraint failed" when submitting django form data

I'm making a simple webapp in django where a user can log in , choose one of the given category and post an article under the chosen category. But when I submit my django form to create a new post, it throws me " IntegrityError NOTNULL constraint failed ". I searched many solutions on internet and implemented the same but still it gives me the same error.
Please help me out as to how I fix this bug??
Here are the code snippets:
Models.py
class Category(models.Model):
name = models.CharField(max_length=128,unique=True)
slug = models.SlugField()
def save(self,*args,**kwargs):
self.slug = slugify(self.name)
super(Category,self).save(*args,**kwargs)
def __unicode__(self):
return self.name
class Post(models.Model):
category = models.ForeignKey(Category,null=True,blank=True)
title = models.CharField(max_length=128,null=True,blank=True)
content = models.TextField(blank=True,null=True)
def __unicode__(self):
return self.title
views.py
def index(request):
category_list = Category.objects.all()
context = {'category_list':category_list}
return render(request,'index.html',context)
def category(request,category_name_slug):
context = {}
try:
category = get_object_or_404(Category,slug=category_name_slug)
context['category_name'] = category.name
post = Post.objects.filter(category=category)
context['post'] = post
context['category'] = category
context['category_name_slug'] = category_name_slug
except Category.DoesNotExist:
pass
return render(request,'category.html',context)
#login_required
def create_post(request,category_name_slug):
created = False
instance = get_object_or_404(Category,slug=category_name_slug)
a = Post(category=instance)
if request.method == 'POST':
form = PostForm(request.POST,instance=a)
if form.is_valid():
post = form.save(commit=False)
post.save()
created = True
else:
print form.errors
else:
form = PostForm()
context={
'form':form,
'instance':instance,
'created':created
}
return render(request,"add_post.html",context)
forms.py
from django import forms
from app.models import Post,Category,UserProfile
from django.contrib.auth.models import User
class CategoryForm(forms.ModelForm):
name = forms.CharField(max_length=128, help_text="Please enter category")
slug = forms.CharField(widget=forms.HiddenInput(), required=False)
class Meta:
model = Category
fields = ('name',)
class PostForm(forms.ModelForm):
title = forms.CharField(max_length=128)
content = forms.CharField(widget=forms.Textarea)
class Meta:
model = Post
fields = ('title','content')
exclude = ('category',)
urls.py
from django.conf.urls import url
from django.contrib import admin
from app import views
urlpatterns = [
url(r'^$',views.index,name='index'),
url(r'^about/$',views.about,name='about'),
url(r'^add_category/$',views.add_category,name="add_category"),
url(r'^category/(?P<category_name_slug>[-\w]+)/create_post/$',views.create_post, name='create_post'),
url(r'^category/(?P<category_name_slug>[-\w]+)/$',views.category, name='category'),
url(r'^(?P<id>\d+)/$',views.post_detail,name='post'),
url(r'^register/$',views.register,name="register"),
url(r'^login/$',views.user_login,name="login"),
url(r'^logout/$',views.user_logout,name="logout"),
url(r'^(?P<username>[-\w]+)/$',views.view_profile,name="profile"),
]
templates/add_post.html
<html>
<head>
<title>Create Post</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
</head>
<body>
<h1>Create Post under {{ instance.name }}</h1>
{% if created %}
<strong>Post created successfully</strong>
<a href='/app/'>Home</a>
{% else %}
<form id='post_form' method='post' action='/app/category/{{ instance.slug }}/create_post/' enctype='multipart/form-data'>
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="submit" value="Create Post" />
</form>
{% endif %}
</body>
</html>
templates/category.html
<!DOCTYPE html>
<html>
<head>
<title>App</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
</head>
<body>
{% if category %}
<h1>{{ category_name }}</h1>
{% if post %}
<ul>
{% for poste in post %}
<li>{{ poste.title }}</li>
{% endfor %}
</ul>
{% else %}
<strong>No posts in this Category</strong>
{% endif %}
{% else %}
<strong>No Category found with {{ category_name }}</strong>
{% endif %}
<a href='/app/category/{{ category.slug }}/create_post/'>Create post</a>
</body>
</html>
It's shows me an error at " post.save() " line in views.py.

"Select a valid choice" error only on first submission try using django-autocomplete-light

I'm getting this weird error using django-autocomplete-light: "Select a valid choice. That choice is not one of the available choices." However, if I stay on the same page and just push Submit again it submits the form no problem, and the data in the form is inserted in the database like it should.
I have an embedded form with addable inlines from another Model. With these models I can make a BookSubmission having multiple different Books (pointed to another Book Models through ForeignKey) on the same BookSumbission page and for every Book their Quantity specified.
When I don't have the widget activated everything works fine. I can select one or more Books from the expected list.
If activate the widget, everything seems to work fine, even the widget shows the expected Books. However, if I push submit I get the error. Push submit again and the form submits flawlessly.
Does anyone have any idea what is going on here? I thought maybe it has something to do with the load order of the .js files, but playing around with it haven't given me any fruitless results.
models.py
class BookSubmission(models.Model):
SubmissionTitle = models.CharField(
max_length=6,
verbose_name="Submission Title",
unique=True)
SubmissionText = models.TextField(
max_length=1500,
null=True,
blank=True,
verbose_name="Submission Text"
)
class BooksAndQuantity(models.Model):
Submission = models.ForeignKey(
'Submission',
null=True,
blank=True,
verbose_name="BookSubmission"
)
Book = models.ForeignKey(
'Books',
to_field='BookTitle',
db_column='BookTitleID',
null=True,
blank=True,
)
Quantity = models.FloatField(verbose_name="Quantity")
class Books(models.Model):
BookTitle = models.CharField(
max_length=6,
unique=True,
db_column='BookTitleID')
BookText = models.TextField(
max_length=1500,
null=True,
blank=True
)
forms.py
class BookSubmissionForm(forms.ModelForm):
class Meta:
model = BookSubmission
fields = '__all__'
BookAndQuantityFormset = inlineformset_factory(
BookSubmission,
BookAndQuantity,
fields='__all__',
extra=1,
widgets={'Book':
autocomplete.ModelSelect2(url='BookAutocomplete')})
views.py
class BookSubmissionView(generic.CreateView):
template_name = 'BookSubmission.html'
model = BookSubmission
form_class = BookSubmissionForm
success_url = 'success/'
def get(self, request, *args, **kwargs):
"""
Handles GET requests and instantiates blank versions of the form
and its inline formsets.
"""
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
BookAndQuantityForm = BookAndQuantityFormset()
return self.render_to_response(
self.get_context_data(form=form,
BookAndQuantityForm=BookAndQuantityForm))
def post(self, request, *args, **kwargs):
"""
Handles POST requests, instantiating a form instance and its inline
formsets with the passed POST variables and then checking them for
validity.
"""
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
BookAndQuantityForm = BookAndQuantityFormset(self.request.POST)
if (form.is_valid() and BookAndQuantityForm.is_valid()):
return self.form_valid(form, BookAndQuantityForm)
else:
return self.form_invalid(form, BookAndQuantityForm)
def form_valid(self, form, BookAndQuantityForm):
"""
Called if all forms are valid. Creates a Recipe instance along with
associated Ingredients and Instructions and then redirects to a
success page.
"""
self.object = form.save()
BookAndQuantityForm.instance = self.object
BookAndQuantityForm.save()
specieandquantityout_form.instance = self.object
specieandquantityout_form.save()
return HttpResponseRedirect(self.get_success_url())
def form_invalid(self, form, BookAndQuantityForm):
"""
Called if a form is invalid. Re-renders the context data with the
data-filled forms and errors.
"""
return self.render_to_response(
self.get_context_data(form=form,
BookAndQuantityForm=BookAndQuantityForm))
class BookAutocomplete(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 Specie.objects.none()
qs = Books.objects.all()
if self.q:
qs = qs.filter(BookTitle__istartswith=self.q)
return qs
With the following html files:
parent.html
<head>
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'personal/css/bootstrap.min.css' %}" type = "text/css"/>
<link rel="stylesheet" href="{% static 'personal/css/navbar-fixed-top.css' %}" >
<link rel="stylesheet" href="{% static 'personal/assets/ie10-viewport-bug-workaround.css' %}" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<meta name="viewport" content = "width=device-width, initial-scale=1.0">
<script src="{% static 'personal/assets/ie10-viewport-bug-workaround.js' %}"></script>
<script src="{% static 'personal/js/bootstrap.min.js' %}"></script>
<style type="text/css">
html,
body {
height:100%
}
</style>
</head>
BookSubmission.html
{% extends "parent.html" %}
{% load staticfiles %}
{% block content %}
<div>
<h1>Add BookSubmissionForm</h1>
<form action="" method="post">
{% csrf_token %}
<div>
<p> BookSubmission Title {{ form.SubmissionTitle }} </p>
<p> BookSubmission Text {{ form.SubmissionText }} </p>
</div>
<fieldset>
<legend>Book and Quantity</legend>
{{ bookandquantity_form.management_form }}
{{ bookandquantity_form.non_form_errors }}
{% for form in bookandquantity_form %}
{{ form.id }}
<div class="inline {{ bookandquantity_form.prefix }}">
{{ form.Book.errors }}
{{ form.Book.label_tag }}
{{ form.Book }}
{{ form.Quantity.errors }}
{{ form.Quantity.label_tag }}
{{ form.Quantity }}
</div>
{{ form.media }}
{% endfor %}
</fieldset>
<input type="submit" value="Add BookSubmission" class="submit" />
</form>
</div>
{% endblock %}
{% block footerContent %}
<script src="{% static 'MM/js/jquery.formset.js' %}"></script>
<script type="text/javascript">
$(function() {
$(".inline.{{ bookandquantity_form.prefix }}").formset({
prefix: "{{ bookandquantity_form.prefix }}",
})
})
</script>
{% endblock %}
urls.py
url(r'^BookAutoComplete/$',
views.BookAutoComplete.as_view(),
name='BookAutoComplete'),
edit
What else is weird is the following, the first time that i push "Add another" in the form it looks bugged.
In the following picture the same Formset is inserted twice (now named "Species and Quanity" In & Out).
"Species and Quantity In" is depicted without clicking "Add Another"
In "Species and Quantity Out" I did click on "Add Another", and you can see that the first row becomes buggy, and in the second row a blank useless field is added.
screenshot
Your form validation code is wrong, that's why the form doesn't validate.
Try without the autocomplete widget if in doubt.
See Django forms documentation for details.

check column value and manipulate css djangotables2

I am using djangotables2 for the first time. I have successfully displayed a table which
is a list of dictonaries,where key and values are calculated from various sources in my
project database.
I have a requirement where i have to check the value of a column and change the background color like css or apply bootstrap badges.
Sample code :-
views.py
data_list = []
#search
query = request.GET.get('q')
if query:
user_list = UserProfile.objects.filter(user__email__icontains=query)
else:
user_list = UserProfile.objects.order_by("-user__date_joined")
for userprofile in user_list:
data_list.append({'user_id': userprofile.id,
'first_name': userprofile.user.first_name,
'last_name': userprofile.user.last_name,
'address': get_city(userprofile),
'dateofbirth': userprofile.dateofbirth,
'anniversary': "NA",
'number_of_orders':
get_total_orders(userprofile),
'total_revenue': get_total_revenue(userprofile),
'highest_order': get_higest_order(userprofile),
'registration_date':
userprofile.user.date_joined.date().strftime("%B %d %Y"),
'last_order_date': get_last_order(userprofile),
'last_order_to_present_day_differene':
get_difference_from_last_order(userprofile)
})
data = ThemedCRMTable(data_list, prefix="3-")
RequestConfig(request, paginate={"per_page": 15}).configure(data)
tables.py
class CRMTable(tables.Table):
user_id = tables.Column()
first_name = tables.Column()
last_name = tables.Column()
address = tables.Column()
dateofbirth = tables.Column()
anniversary = tables.Column()
number_of_orders = tables.Column()
total_revenue = tables.Column()
highest_order = tables.Column()
registration_date = tables.Column()
last_order_date = tables.Column()
last_order_to_present_day_differene = tables.Column()
class ThemedCRMTable(CRMTable):
class Meta:
attrs = {'class': 'paleblue'}
template
{% load static %}
{% load render_table from django_tables2 %}
<!doctype html>
<html>
<head>
<title>CRM Report</title>
<link rel="stylesheet" href="/static/report/css/screen.css" />
<link href="{% static 'css/bootstrap.css' %}" rel="stylesheet">
<script src="{% static 'js/jquery.js' %}"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
</head>
<body>
<div class="container">
<div class="row" style="margin-top:2%;text-align:center;">
<form class="form-search pull-left">
<div class="input-append">
<input type="text" class="span4 search-query" name="q">
<button type="submit" class="btn">Search</button>
</div>
</form>
<strong style="font-size:20px;">CRM Report</strong>
<a class="btn btn-inverse pull-right offset1" href="/">
<span><i class="icon-step-backward icon-white icon-alignment"></i></span>
Go Back
</a>
<a class="btn btn-success pull-right offset1" href="{% url generate_crm_report_csv %}">
<span><i class="icon-download icon-white icon-alignment"></i></span>
CRM Report
</a>
</div>
{% render_table data_list %}
</div>
</body>
</html>
Question:-
I want to make the cell background red where the value of last column last_order_to_present_day_differene is greator than 30