Create new post - django

I have a blog website and I have New Post button
this is my post list function
def PostList(request):
post_list = Post.objects.all()
context = {'post_list' : post_list}
return render(request, 'blog/home.html', context)
this is my post detail function
def post_detail(request, slug):
post_detail = Post.objects.get(slug=slug)
context = {'post_detail' : post_detail}
return render(request, 'blog/post_detail.html', context)
and I want to create this function but I dont know how
def post_new(request):
post_new = Post.objects.get()
Can anyone help me I am new to django

Related

No Post matches the given query. django blog

everything is ok in the model but when I try to retrieve the object the error "No Post matches the given query." is shown.
I don't know what is the problem that shows this error?
**Model**
class Post(CoreField):
....
slug = models.SlugField(max_length=250, unique_for_date='publish')
tags = TaggableManager()
publish = models.DateTimeField(default=timezone.now)
def get_absolute_url(self):
return reverse('news:post_detail',
args=[self.publish.year,
self.publish.month,
self.publish.day,
self.slug])
**url**
path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'),
**views**
def post_detail(request, year, month, day, post):
single_post = get_object_or_404(Post,
publish__year=year,
publish__month=month,
publish__day=day,
slug=post
)
# List of active comments for this post
comments = post.comments.filter(active=True)
# Form for users to comment
form = CommentForm()
return render(request, 'news/post_detail.html', {'post': single_post, 'comments': comments, 'form': form})
when I remove the remove the "int:year/int:month/int:day/" form url it works.
but when I pass the "int:year/int:month/int:day/slug:post/" it does't work.
What is the proble and where it happens????
In your post_detail view, I think you should pass "slug" as an argument to the view instead of "post" because post is not a model field nor is it defined anywhere. And the "slug=post" kwarg should probably be reversed to avoid further errors.
So the post_detail view should probably look like this:
def post_detail(request, year, month, day, slug):
single_post = get_object_or_404(Post,
publish__year=year,
publish__month=month,
publish__day=day,
post=slug
)

Can't work modal form with method POST in Django

Thats my first project in Django. I want to make table and add items with modal form. I use Mysql database. items which addes manually from phpmyadmin already exist on table but when i try add from modal form it cant added.
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Client
def viewpost(request):
post_list = Client.objects.all()
context = {
'posts': post_list
}
return render(request, 'mysite/viewtable.html', context)
def add_client(request):
if request.method == 'POST':
post = Client()
post.name = request.POST.get('name')
post.surname = request.POST.get('surname')
post.address = request.POST.get('address')
post.gender = request.POST.get('gender')
post.age = request.POST.get('age')
post.save()
return render(request, 'mysite/viewtable.html')
else:
return render(request, 'mysite/viewtable.html')
url.py:
from django.urls import path
from . import views
urlpatterns = {
path('viewtable/', views.viewpost, name='viewpost'),
path('viewtable/#add_data_Modal', views.add_client, name='add_client'),
}
Before the table and modal form didnt work together. If table worked then modal form didnt add to database or conversely. Now the're work together: Modal form add to database then table show data on page. But when i refresh page data add to databse twice.
views.py:
def viewpost(request):
post_list = Persona.objects.all()
context = {
'posts': post_list
}
if request.method == 'POST':
if request.POST.get('name') and request.POST.get('surname') and request.POST.get('address'):
post = Client()
post.name = request.POST.get('name')
post.surname = request.POST.get('surname')
post.address = request.POST.get('address')
post.age = request.POST.get('age')
post.save()
return render(request, 'mysite/viewtable.html', context)
else:
return render(request, 'mysite/viewtable.html')
Thats SOLVED. Here's view
def viewpost(request):
post_list = Persona.objects.all()
if request.method == 'POST':
if request.POST.get('name') and request.POST.get('surname') and
request.POST.get('address'):
post = Persona()
post.name = request.POST.get('name')
post.surname = request.POST.get('surname')
post.address = request.POST.get('address')
post.age = request.POST.get('age')
post.save()
return HttpResponseRedirect('/viewtable')
else:
return render(request, 'mysite/viewtabel.html', {'posts': post_list}

Submit two forms in a single submit in Django

I have two forms in template. At the moment I have two submit buttons.
Would like to combine those to a single submit button.
Below code is now updating only one form, that's AnswerForm.
How i can update AnswerReplyForm along with that?
class AnswerView(ObjectEditView):
form_class = forms.AnswerReplyForm
answer_form = forms.AnswerForm
model = AnswerReply
def get(self, request, pk):
answer = get_object_or_404(Answer, pk = pk)
answer_reply = AnswerReply.objects.filter(answer_id = pk).order_by('-id')
self.answer_form = self.answer_form(instance=answer)
return render(request, 'helpdesk/answer.html', {
'answer': answer,
"answer_reply" : answer_reply,
'obj_type': 'answer reply',
'form': self.form_class,
"form2":self.answer_form,
"pre_reply_from" : self.predefined_reply_form
})
def post(self, request, pk, *args, **kwargs):
answer = get_object_or_404(Answer, id=pk)
answer_reply = AnswerReply.objects.filter(answer_id = pk).order_by('-id')
self.answer_form = self.answer_form(instance=answer)
obj = self.model()
obj = self.alter_obj(obj, request, args, kwargs)
form = self.form_class(request.POST, request.FILES, instance=obj)
if form.is_valid():
form.instance.answer_id = pk
obj_created = not form.instance.pk
obj = form.save()
return render(request, 'helpdesk/answer.html', {
'answer': answer,
"answer_reply" : answer_reply,
'obj_type': 'answer reply',
'form': self.form_class,
"form2":self.answer_form,
})
In general:
if request.method == 'POST':
form_1 = FormOne(request.POST)
form_2 = FormTwo(request.POST)
if form_1.is_valid() and form_2.is_valid():
form_1.save()
form_2.save()
return #Write your return here, something like HttpResposeRedirect or whatever you need to do after saving both form successfully
else:
form_1 = FormOne()
form_2 = FormTwo()
context = {
'form1': form_1,
'form2': form_2
}
return render(request, 'template.html', context)
In your template file
<form>
{{ form1 }}
{{ form2 }}
<input type="submit" value= "submit">
</form>
It will work.
It's better to define a structure for each one (View, route and template)
Then, based on desired condition, display one of the structures (redirect to one of them):
for example decision view:
def decisionView(request):
route = '/route/1'
if condition:
route = '/route/2'
return redirect(route)
i hope this could help you

getting object with slug or pk in querysets

In django doc says that
>>> entry = Entry.objects.get(id=10)
is faster than this:
>>> entry = Entry.object.get(headline="News Item Title")
So I changed my view from this:
def myview(request, slug):
post = get_object_or_404(Post, slug=slug)
#...
to this:
def myview(request, id, slug):
post = get_object_or_404(Post, pk=pk)
#...
But my slug is not used in my view. In that case both urls below get the correct post because of valid regex:
127.0.0.1:8000/posts/5/my-first-post/
127.0.0.1:8000/posts/5/mylblablabalg/
And I dont want this. Then I canged my view to this:
def myview(request, id, slug):
post = get_object_or_404(Post, pk=pk)
if post.slug == slug:
return render(request, 'blog/index.html', {'post': post})
else:
return HttpResponseRedirect(reverse('blog:index', args=(id, post.slug)))
It does what I want which redirects the same page with the corrected slug but I doubt if it is ok in terms of performanse. What about db_index? Should I use it in SlugField?
If you are going to pull posts from the database via the SlugField, then yes, you should tell the database to index that field for performance increase. You should also set it to unique.

How to pass a value to a Pluggable View?

I am trying to implement a template for adding VIEW, ADD and EDIT webpages with pluggable views. How do I use a url value like ?
This is the code I am trying to translate into pluggable views.
#app.route('/edit/category/<category>', methods=['GET', 'POST'])
def editCategory(category):
form = forms.AddCategory()
form.name.data = category
if form.validate_on_submit():
newName = form.name.data
database.editCategory(name = category, newName = newName)
#view single category?
return redirect('/view/categories/')
return render_template('edit-category.html', category = category, form = form)
Pluggable View Code
class ListView(View):
def getTemplate_name(self):
raise NotImplementedError()
def render_template(self, context):
return render_template(self.get_template_name(), **context)
def dispatch_request(self):
context = self.get_context()
return self.render_template(context)
class CategoryView(ListView):
def get_template_name(self):
return 'categories.html'
def get_objects(self):
return models.Category.query.all()
def get_form(self):
return forms.AddCategory()
def get_context(self):
return {'categories': self.get_objects(), 'form': self.get_form()}
app.add_url_rule('/view/categories', view_func=CategoryView.as_view('category'))
class EditCategory(ListView):
def get_template_name(self):
return 'edit-category.html'
def get_form(self, category):
form = forms.AddCategory()
form.name.data = category
return form
def get_context(self):
return {'form': self.get_form()}
app.add_url_rule('/edit/category/<category>', view_func=EditCategory.as_view('category'))
You need to override the dispatch_request method in the EditCategory class as this method has the url values passed to it.
class EditCategory(View):
...
def get_context(self, category):
return {'form': self.get_form(category)}
def dispatch_request(self, category):
context = self.get_context(category)
return self.render_template(context)
app.add_url_rule('/edit/category/<category>', view_func=EditCategory.as_view('category'))
As an aside, I think you are better off with the original decorated view functions in this case is there is very little commonality between the viewCategory and editCategory functionality