Django with bootstrap DateTimePicker: inputElement.dataset is undefined - django

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?

Related

Django-ckeditor showing content as textarea

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}}

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.

Django blog post doesn't update it just creates another object

This view is supposed to find a blog post and change it's information, but instead of that it just makes a new Blog object with the new (and old) information.
The update view
#login_required
def view_updatepost(request, blog_id):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
#post = Blog.objects.get(pk=blog_id)
post_to_be_changed = get_object_or_404(Blog, pk=blog_id)
form = BlogForm(request.POST or None, instance=post_to_be_changed)
if form.is_valid():
post_to_be_changed = form.save(commit=False)
#
#
post_to_be_changed.save()
#messages.success(request, "<a href='#'>Item</a> Saved", extra_tags='html_safe')
return HttpResponseRedirect(post_to_be_changed.get_absolute_url())
context = {
'post_to_be_changed': post_to_be_changed,
'form': form,
}
return render(request, 'blog/makepost.html', context)
The template used by the view makepost.html
{% extends "base.html" %}
{% load staticfiles %}
{% block main_content %}
<!-- Page Header -->
<!-- Set your background image for this header on the line below. -->
<header class="intro-header" style="background-image: url('{% static "img/about-bg.jpg" %}')">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="page-heading">
<h1>Make a Post</h1>
<hr class="small">
<span class="subheading">Share with the World.</span>
</div>
</div>
</div>
</div>
</header>
<!-- Main Content -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
{% if not user.is_authenticated %}
You must be <u>logged in</u> to make a post.
{% else %}
<form action="{% url "makepost" %}" method="post">
{% csrf_token %}
{{form.as_p}}
<div align="center">
<input class="btn btn-default" type="submit" value="Post to Blog" onclick="window.location='{% url "" %}';"/>
{# Home #}
</div>
</form>
{% endif %}
</div>
</div>
</div>
<hr>
{% endblock main_content %}
The models.py
from django.db import models
import datetime
# Create your models here.
class Blog(models.Model):
title = models.CharField(max_length=250)
subtitle = models.CharField(max_length=250, null = True, blank=True)
date_added = models.DateTimeField(default=datetime.datetime.now())
image = models.TextField(max_length=1000, null = True, blank=True)
tags = models.TextField(max_length=500, null=True, blank=True)
article = models.TextField(max_length=15000, null=True, blank=True)
author = models.CharField(max_length=150, null=True, blank=True)
def get_absolute_url(self):
return "/blog/%i" % self.pk
The forms.py
from django import forms
from .models import Blog
import datetime
class PostForm(forms.Form):
title = forms.CharField()
subtitle = forms.CharField(required=False)
date_added = forms.DateTimeField()
image = forms.URLField(required=False)
tags = forms.CharField(required=False)
article = forms.CharField()
author = forms.CharField()
class BlogForm(forms.ModelForm):
class Meta:
model = Blog
fields = ('title', 'subtitle',
'image', 'tags', 'article')
It seems that you are not referring to your update view in your form action url:
<form action="{% url **"makepost"** %}" method="post">

Django cannot get dialog box to display relevant information

I have two forms that I am using on one (html page below) page. One form (create_task_form) create's tasks, and the other (edit_task_form) should edit/show tasks. To make things more difficult on myself I decided to display the tasks in a list, and when a user clicks on a task, it should display a form with the task details in a dialog box. Again, the create dialog box works as should, however I cannot figure out how to populate the (edit_task_form) edit/show form for a existing task from a list in a dialog box with the relevent task info.
Views.py: Edited
def status(request, project_id, task_id=None):
need_owner_list = Task.objects.filter(project__id=project_id, status=0)
in_progresss_list = Task.objects.filter(project__id=project_id, status=1)
pending_review_list = Task.objects.filter(project__id=project_id, status=2)
t = get_object_or_404(Task, pk=task_id)
p = get_object_or_404(Project, pk=project_id)
if project_id:
p = get_object_or_404(Project, pk=project_id)
else:
p = None
# if task_id:
# t = get_object_or_404(Task, pk=task_id)
# else:
# t = None
if request.method == 'POST':
p = get_object_or_404(Project, pk=project_id)
post_task = PostTaskForm(request.POST)
if post_task.is_valid():
task = post_task.save(commit=False)
task.project = p
task.save()
url = reverse('status', args=[project_id])
return HttpResponseRedirect(url)
else:
post_task = PostTaskForm()
if request.method == 'POST':
t = get_object_or_404(Task, pk=task_id)
tform = PostTaskForm(request.POST, instance = t)
if form.is_valid():
task = tform.save()
url = reverse('status', args=[project_id])
return HttpResponseRedirect(url)
else:
tform = PostTaskForm(instance=t)
c = Context({
'need_owner_list': need_owner_list,
'in_progresss_list': in_progresss_list,
'pending_review_list': pending_review_list,
'project': p,
'request': request,
'pform': post_task,
'task_id': task_id,
'project_id': project_id,
'task': t,
'tform': tform,
})
return render_to_response('project/status.html', c, context_instance=RequestContext(request))
HTML Page
{% extends "base.html" %}
{% block title %} project status {% endblock %}
{%block content %}
<body>
<head>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/status.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/create_task.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/status_box.css" />
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/list_items.css">
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/ownerless_task_list.css">
<!-- These are the scripts for the drag and drop functionality. -->
<script language="JavaScript" type="text/javascript" src="{{ STATIC_URL }}javascript/jquery.sortable.js"></script>
</head>
<div id=lists_box>
{% if need_owner_list %}
<ul id="needs_owner" class="connected list">
{% for task in need_owner_list|slice:":20" %}
<li class="row1"><a href="#divModalDialog1" >{{ task.title }} {% url task task.id%}</a></li>
{% endfor %}
</ul>
<div id="divModalDialog1" class="divModalDialog" type="hidden">
<div id=task_div>
X
<form id="edit_task_form" action="{{ task }}" value="{{ task }}" method="POST">
<input type="hidden" name="task" value="{{ task }}"/>
{% csrf_token %}
{{ pform }}
<input type="SubmitEdit" value="Submit Edit" onclick="self.close()">
<input type="Reset" value="Reset">
</form>
</div>
</div>
{% else %}
<ul id="needs_owner" class="connected list">
<li class="row1">No tasks are available.</li>
</ul>
{% endif %}
{% if in_progresss_list %}
<ul id="in_progress" class="connected list">
{% for task in in_progresss_list|slice:":20" %}
<li class="row1">{{ task.title }}</li>
{% endfor %}
</ul>
{% else %}
<ul id="in_progress" class="connected list">
<li class="row1">No tasks are available.</li>
</ul>
{% endif %}
{% if pending_review_list %}
<ul id="pending_status" class="connected list">
{% for task in pending_review_list|slice:":20" %}
<li class="row1">{{ task.title }}</li>
{% endfor %}
</ul>
{% else %}
<ul id="pending_status" class="connected list">
<li class="row1">No tasks are available.</li>
</ul>
{% endif %}
</div>
<!-- START:This section below is deals with the submit task popup window -->
{% if user.is_authenticated %}
<script>
$(function() {
$('.sortable').sortable();
$('.handles').sortable({
handle: 'span'
});
$('.connected').sortable({
connectWith: '.connected'
});
$('.exclude').sortable({
items: ':not(.disabled)'
});
});
</script>
<!-- The JS is added here to load after login. If this is added the the top of the page it conflicts with login_link.js -->
<script src="{{ STATIC_URL }}javascript/create_task.js" type="text/javascript"></script>
<a id="submit_task">submit task</a>
<div id="task_popout">
<a id="task_popoutClose">X</a>
{% if form.has_errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form id="create_task_form" action="" value="submit_task" method="POST">
<input type="hidden" name="project" value="{{ project_id }}"/>
{% csrf_token %}
{{ pform }}
<input type="Submit" value="Submit Task" onclick="self.close()">
<input type="Reset" value="Reset">
</form>
</div>
<div id="taskbackgroundPopup"></div>
{% else %}
<p id="login_message">Please <a style="color:blue;" href="#authenticate" id="task_chat">log in</a> to submit/edit tasks or particapate in chats.</p>
{% endif %}
<div id="ticket_stats">
<div id="owner_label" class="text">Owner:</div>
<div id="owner" class="text">{{project.owner|safe}}</div>
<div id="tags_label" class="text">Tags:</div>
<div id="tags" class="text">{{project.tags|safe}}</div>
<div id="created_label" class="text">Created:</div>
<div id="created_date" class="text">{{project.date_created|date:"d/m/Y"}}</div>
<div id="updated_label" class="text">Updated:</div>
<div id="last_updated" class="text">{{project.date_updated|date:"d/m/Y"}}</div>
</div>
</body>
{%endblock%}
models.py
class Project(models.Model):
title = models.CharField(max_length=50, verbose_name='')
slug = models.SlugField(max_length=50, editable=False)
owner = models.ForeignKey(User, editable=False)
problem = tinymce_models.HTMLField(verbose_name='')
date_created = models.DateTimeField(editable=False)
date_updated = models.DateTimeField(editable=False)
tags = TagField(verbose_name='')
def set_tags(self, tags):
Tag.objects.update_tags(self, tags)
def __unicode__(self):
return self.tags
def __unicode__(self):
return self.id
def __unicode__(self):
return self.title
#This overrides the save function in the project/views.py module. It checks the
#created date against the updated date, and updates the updated date if needed.
#Also this takes the title and slugifies it so it can be rendered in the URL.
def save(self, *args, **kwargs):
if not self.id:
self.date_created = datetime.now()
self.date_updated = datetime.now()
self.slug = slugify(self.title)
super(Project, self).save(*args, **kwargs)
class PostProjectForm(ModelForm):
class Meta:
model = Project
STATUS_CHOICES = (
('0', 'Needs Owner'),
('1', 'In Progress'),
('2', 'Comp/Pend/Review'),
('3', 'Complete')
)
class Task(models.Model):
title = models.CharField(max_length=50)
project = models.ForeignKey(Project, editable=False)
assignee = models.ForeignKey(User, null=True, blank=True)
task_desc = models.TextField()
solution = models.TextField(blank=True)
status = models.CharField(max_length=1, default='0', choices=STATUS_CHOICES)
date_created = models.DateTimeField(editable=False)
date_updated = models.DateTimeField(editable=False)
def save(self, *args, **kwargs):
if not self.id:
self.date_created = datetime.now()
self.date_updated = datetime.now()
super(Task, self).save(*args, **kwargs)
def __unicode__(self):
return self.id
def __unicode__(self):
return "%s" % self.object_pk
class PostTaskForm(ModelForm):
class Meta:
model = Task
URLs.py
url(r'^status/(?P<idea_id>\d+)$', 'status', name='status'),
url(r'^status/(?P<idea_id>\d+)/(?P<task_id>\d+)$', 'status', name='status_task'),
TL;DR
How can I get a the edit_task_form to display the relevant data from Tasks so that a user can edit/view a task?
Thanks in advance!
not sure but, you have...
if request.method == 'POST':
p = get_object_or_404(Project, pk=project_id)
post_task = PostTaskForm(request.POST)
...
else:
post_task = PostTaskForm()
^ so from the above it looks like it might not populate the form if you are making the dialog with a javascript GET request (?)