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 (?)
Related
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?
I have a model with Usuario where the profile foto goes and it saves perfectly in the database, so to be able to add more images as if it were a gallery, I created another model called Gallery, I copied the same specificiation of what was already working in the model Usuario, however he is not saving the photos in the database, and I do not know where I am going wrong.
I appreciate any help.
and I need the Gallery model to receive the foreign Usuario key
Erro:
IntegrityError at /gallery-novo/
null value in column "usuario_id_id" violates not-null constraint
DETAIL: Failing row contains (3, IMG_20180622_101716179_BURST006.jpg, eu e meu amor, null).
views.py
def gallery(request):
gallery = Gallery.objects.all()
form = GalleryForm()
data = {'gallery': gallery, 'form': form}
return render(request, 'gallery.html', data)
def gallery_novo(request):
if request.method == 'POST':
form = GalleryForm(request.POST, request.FILES)
if form.is_valid():
form.save(user=request.user)
return redirect('sistema_perfil')
else:
form = GalleryForm
return render(request, 'gallery.html', {'form': form})
models.py
class Gallery(models.Model):
gallery = StdImageField( blank=False, variations={
'large': (600, 400),
'thumbnail': (100, 100, True),
'medium': (300, 200),
})
titulo = models.CharField(max_length=50, blank=False)
usuario_id = models.ForeignKey(User, on_delete=models.CASCADE, blank=False)
forms.py
class GalleryForm(forms.ModelForm):
gallery = forms.FileField(
widget=forms.ClearableFileInput(attrs={'multiple': 'True'}))
titulo = forms.CharField()
class Meta:
model = Gallery
fields = ( 'gallery', 'titulo')
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
return super(GalleryForm, self).__init__(*args, **kwargs)
def save(self, commit=True, user=None):
form = super(GalleryForm, self).save(commit=False)
form.usario_id = user
if commit:
form.save()
return form
gallery.html
{%extends 'bases/base.html' %}
{% load static %}
{% load bootstrap %}
{% load widget_tweaks %}
{% load crispy_forms_tags %}
{% block main %}
<div class="card text-white bg-primary">
<div class="card-header"><p class="card-text">
<small class="text-muted">
Home /
<a class="text-white">Cadastro</a>
</small></a></p> Cadastro de Usúario
</div>
<div class="card title ">
<div class="card-body text-secondary">
<form class="exampleone" action="{% url 'sistema_gallery_novo' %}" method="POST" enctype="multipart/form-data" id="form" name="form" validate >
{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-4">
{{ form.gallery | as_crispy_field }}
</div>
<div class="form-group col-md-4">
{{ form.titulo | as_crispy_field }}
</div>
<div class="form-group col-md-4">
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block">Cadastrar</button>
</form>
</div>
</div>
</div>
{% endblock %}
{% block rightcol %}
{% include 'bases/rightcol.html' %}
{% endblock %}
{% block footer %}
{% include 'bases/footer.html' %}
{% endblock %}
urls.py
url(r'gallery/$', gallery, name='sistema_gallery'),
url(r'gallery-novo/$', gallery_novo, name='sistema_gallery_novo'),
In my opinion, you are reinventing the wheel, the django right approach is to use commit=False on save method:
def gallery_novo(request):
if request.method == 'POST':
form = GalleryForm(request.POST, request.FILES)
if form.is_valid():
my_novo_gallery = form.save(commit=False) #save no commit
my_novo_gallery.user=request.user #set user
my_novo_gallery.save() #save to db
return redirect('sistema_perfil')
I want to know how to upload and display the image.
I do have the classes in views.py.
class ArticleUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Article
fields = ('title', 'body', 'image', 'source_url')
template_name = 'article_edit.html'
def test_func(self):
obj = self.get_object()
return obj.author == self.request.user
class ArticleCreateView(LoginRequiredMixin, CreateView):
model = Article
template_name = 'article_new.html'
fields = ('title', 'body', 'image', 'source_url')
login_url = 'login'
def test_func(self):
obj = self.get_object()
return obj.author == self.request.user
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
And the relevant classes in the models.py are like as follow.
class Article(models.Model):
title = models.CharField(max_length=255)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
image = models.ImageField(
upload_to='media/', null=True, blank=True)
source_url = models.URLField(blank=True, null=True, max_length=300)
author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('article_detail', args=[str(self.id)])
class Comment(models.Model):
article = models.ForeignKey(Article,
on_delete=models.CASCADE, related_name='comments', )
comment = models.CharField(max_length=140)
author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE),
def __str__(self):
return self.comment
def get_absolute_url(self):
return reverse('article_list')
The article_list.html file is:
{% extends 'base.html' %}
{% load static %}
{% block title %}Articles{% endblock title %}
{% block content %}
{% for article in object_list %}
<div class="card">
<div class="card-header">
<span class="font-weight-bold">{{ article.title }}</span> ·
<span class="text-muted">by {{ article.author }} |
{{ article.date }}</span>
</div>
<div class="card-body">
{{ article.body|linebreaks}}
{% comment %} {% if article.image.url|length > 0 %}
<img src="{{ article.image.url }}" width="200px">
{% else %}
<img src="{% static '/media/mrDoctor.jpg' %}" width="200px" />
{% endif %} {% endcomment %}
<img src="{% static 'articles/mrDoctor.jpg' %}" alt="Image" width="200px" />
Link
Edit
Delete
</div>
<div class="card-footer">
{% for comment in article.comments.all %}
<p>
<span class="font-weight-bold">
{{ comment.author }} ·
</span>
{{ comment }}
</p>
{% endfor %}
</div>
</div>
<br />
{% endfor %}
{% endblock content %}
The user can select the image file from the form.
I can not display the image selected from the input form shown above on the screen shot. I want to display the images dynamically, i.e., when the user choose the image file from the input form. I know I should change the part:{% static '/media/mrDoctor.jpg' %}. When I tried the commented part of article_list.html, i.e., {% if article.image.url|length > 0 %}, it did not work. I will appreciate it if you help me to fix the problem. Many thanks.
After reflecting #Hybrid suggestions, I was able to show the image on the first article but the second and the third one show only the file names.
You can do this by using JavaScript to detect when a user selects an image, and then replacing an <img /> tags src dynamically.
Example code:
<img id="image" />
<input id="files" type="file" />
<script>
document.getElementById("files").onchange = function () {
var reader = new FileReader();
reader.onload = function (e) {
// get loaded data and render thumbnail.
document.getElementById("image").src = e.target.result;
};
// read the image file as a data URL.
reader.readAsDataURL(this.files[0]);
};
</script>
I have a situation where I want to have published functionality for articles, and I have it. The problem is that I can't get my unit test to work properly, trying to post True to the published field.
Here's what my tests look like.
class ArticleDetailViewTest(TestCase):
def setUp(self):
email = 'testuser#gmail.com'
first_name = 'test'
last_name = 'user'
password = 'test15146'
user = User.objects.create_user(email, first_name, last_name, password)
self.client = Client()
self.client.login(username='testuser#gmail.com', password='test15146')
def test_can_publish_article_from_POST(self):
other_article_two = Article.objects.create(name='Test Name One', author=User.objects.get(email='testuser#gmail.com'))
correct_article_two = Article.objects.create(name='Test Name Two', author=User.objects.get(email='testuser#gmail.com'))
response = self.client.post(reverse('publish_article', kwargs={'pk' : correct_article_two.pk}))
self.assertEqual(response.status_code, 302)
self.assertRedirects(response, f'/articles/{correct_article_two.pk}/')
self.assertEqual(correct_article_two.published, True)
Here's what my publish article view looks like.
def publish_article(request, pk):
article = get_object_or_404(models.Article, pk=pk)
if request.method == "POST":
article.published = True
article.save(update_fields=['published'])
return redirect('article_detail_view', pk=article.pk)
else:
raise Http404
Here are my urls.
from django.urls import path
from . import views
urlpatterns = [
path('', views.HomePageView.as_view(), name='home'),
path('new/', views.ArticleCreateView.as_view(), name='article_new'),
path('<int:pk>/', views.ArticleDetailView.as_view(), name='article_detail_view'),
path('<int:pk>/publish/', views.publish_article, name='publish_article'),
path('<int:pk>/unpublish/', views.unpublish_article, name='unpublish_article'),]
Here are my models.
from django.conf import settings
from django.db import models
from django.urls import reverse
from django import forms
class Article(models.Model):
name = models.CharField(max_length=255, blank=False)
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
published = models.BooleanField(default=False)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('article_detail_view', args=[str(self.id)])
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ['name',]
Lastly, here is the template.
{% extends 'base.html' %}
{% block title %}{{ article.name }}{% endblock %}
{% block content %}
{% if article.author_id == user.pk %}
<div class="row">
<div class="col-6 col-centered">
<h2 class="text-center">{{ article.name }}</h2>
<p class="text-center">by {{ article.author.first_name }} {{ article.author.last_name }}</p>
{% if article.published %}
<small class="form-text text-muted mb-1">This article is public.</small>
<form method="post" action="/articles/{{ article.pk }}/unpublish/">
{% csrf_token %}
<input type="submit" name="unpublish" value="Unpublish Article" id="id_unpublish_button" class="btn btn-primary btn-md"/>
</form>
{% else %}
<small class="form-text text-muted mb-1">This article is private.</small>
<form method="post" action="/articles/{{ article.pk }}/publish/">
{% csrf_token %}
<input type="submit" name="publish" value="Publish Article" id="id_publish_button" class="btn btn-primary btn-md"/>
</form>
{% endif %}
</div>
</div>
{% elif article.published %}
<div class="row">
<div class="col-6 col-centered">
<h2 class="text-center">{{ article.name }}</h2>
<p class="text-center">by {{ article.author.first_name }} {{ article.author.last_name }}</p>
</div>
</div>
{% else %}
<div class="row">
<div class="col-6 col-centered">
<p class="text-center">This article is private.</p>
</div>
</div>
{% endif %}
{% endblock %}
This is the error message I'm getting from my test. The issue seems to be I can post to the URL with self.client.post . Any help would be greatly appreciated.
FAIL: test_can_publish_article_from_POST (articles.tests.ArticleDetailViewTest)
Traceback (most recent call last):
File "/Users/christopher.chough/article_directory/articles/tests.py", line 126, in test_can_publish_article_from_POST
self.assertEqual(correct_article_two.published, True)
AssertionError: False != True
Ran 17 tests in 2.340s
FAILED (failures=1)
Object in your test method not updated. You can use refresh_from_db method to update it after changes:
def test_can_publish_article_from_POST(self):
other_article_two = Article.objects.create(name='Test Name One', author=User.objects.get(email='testuser#gmail.com'))
correct_article_two = Article.objects.create(name='Test Name Two', author=User.objects.get(email='testuser#gmail.com'))
response = self.client.post(reverse('publish_article', kwargs={'pk' : correct_article_two.pk}))
correct_article_two.refresh_from_db() # Add this line
self.assertEqual(response.status_code, 302)
self.assertRedirects(response, f'/articles/{correct_article_two.pk}/')
self.assertEqual(correct_article_two.published, True)
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">