Posts from admin panel on different subpages - python

I would like to add post list from main page to another subpages. (main page to subpage called "programowanie")
For example:
I have a website wwww.example.com. On this website I have a post list that is generated from admin panel (I can add, delete a posts using admin panel).
The problem is that when I try to copy templates from start page with post list to other subpage (called: www.example.com/programowanie) it doeasn't work (I see a template from main page but without post list)
I think the problem is in templates/blog/post/list.html in loop {% for post in posts %}
If I solve this problem I would like to add in admin panel different overlap to publish posts only in "programowanie" subpage.
This is my files:
blog/views.py
from django.shortcuts import render, get_object_or_404, HttpResponse
from .models import Post, Posta, Comment
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.generic import ListView
from .forms import EmailPostForm, CommentForm
from django.core.mail import send_mail
from taggit.models import Tag
from django.db.models import Count
def post_share(request, post_id):
# Pobranie posta na podstawie jego identyfikatora.
post = get_object_or_404(Post, id=post_id, status='published')
sent = False
if request.method == 'POST':
# Formularz został wysłany.
form = EmailPostForm(request.POST)
if form.is_valid():
# Weryfikacja pól formularza zakończyła się powodzeniem…
cd = form.cleaned_data
post_url = request.build_absolute_uri(
post.get_absolute_url())
subject = '{} ({}) zachęca do przeczytania "{}"'.format(cd['nick'], cd['email'], post.title)
message = 'Przeczytaj post "{}" na stronie {}\n\n Komentarz dodany przez {}: {}'.format(post.title, post_url, cd['nick'], cd['komentarz'])
send_mail(subject, message, 'admin#myblog.com', [cd['adresat']])
sent = True
else:
form = EmailPostForm()
return render(request, 'blog/post/share.html', {'post': post,
'form': form,
'sent': sent})
class PostListView(ListView):
queryset = Post.published.all()
context_object_name = 'posts'
paginate_by = 3
template_name = 'blog/post/list.html'
def post_list(request, tag_slug=None):
object_list = Post.published.all()
tag = None
if tag_slug:
tag = get_object_or_404(Tag, slug=tag_slug)
object_list = object_list.filter(tags__in=[tag])
paginator = Paginator(object_list, 3) # Trzy posty na każdej stronie.
page = request.GET.get('page')
try:
posts = paginator.page(page)
except PageNotAnInteger:
# Jeżeli zmienna page nie jest liczbą całkowitą,
# wówczas pobierana jest pierwsza strona wyników.
posts = paginator.page(1)
except EmptyPage:
# Jeżeli zmienna page ma wartość większą niż numer ostatniej strony
# wyników, wtedy pobierana jest ostatnia strona wyników.
posts = paginator.page(paginator.num_pages)
return render(request,
'blog/post/list.html',
{'page': page,
'posts': posts,
'tag': tag})
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
comments = post.comments.filter(active=True)
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.post = post
new_comment.save()
else:
comment_form = CommentForm()
# Lista podobnych postów.
post_tags_ids = post.tags.values_list('id', flat=True)
similar_posts = Post.published.filter(tags__in=post_tags_ids)\
.exclude(id=post.id)
similar_posts = similar_posts.annotate(same_tags=Count('tags'))\
.order_by('-same_tags','-publish')[:4]
return render(request,
'blog/post/detail.html',
{'post': post,
'comments': comments,
'comment_form': comment_form,
'similar_posts': similar_posts})
def programowanie(request):
return render(request, 'blog/post/base.html')
blog/models.py
# -*- coding: utf-8 -*-
from taggit.managers import TaggableManager
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager,
self).get_queryset()\
.filter(status='published')
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Roboczy'),
('published', 'Opublikowany'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250,
unique_for_date='publish')
author = models.ForeignKey(User,
related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10,
choices=STATUS_CHOICES,
default='draft')
objects = models.Manager() # Menedżer domyślny.
published = PublishedManager() # Menedżer niestandardowy.
tags = TaggableManager()
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:post_detail',
args=[self.publish.year,
self.publish.strftime('%m'),
self.publish.strftime('%d'),
self.slug])
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
komentarz = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)
class Meta:
ordering = ('created',)
def __str__(self):
return 'Komentarz dodany przez {} dla posta {}'.format(self.name,
self.post)
blog/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
# Widoki posta.
url(r'^$', views.post_list, name='post_list'),
url(r'^programowanie/$', views.programowanie, name='programowanie'),
#url(r'^$', views.PostListView.as_view(), name='post_list'),
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\
r'(?P<post>[-\w]+)/$',
views.post_detail,
name='post_detail'),
url(r'^(?P<post_id>\d+)/share/$', views.post_share,
name='post_share'),
url(r'^tag/(?P<tag_slug>[-\w]+)/$', views.post_list,
name='post_list_by_tag'),
]
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from blog import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^about/', views.about, name="about"),
url(r'^programowanie/', views.programowanie, name="programowanie"),
url(r'^algorytmy/', views.algorytmy, name="algorytmy"),
url(r'^kontakt/', views.kontakt, name="kontakt"),
url(r'', include('blog.urls',
namespace='blog',
app_name='blog')),
]
blog/templates/base.html
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
{% include "navbar.html" with page=posts %}
<title>{% block title %}{% endblock %}</title>
<link href="{% static "admin/css/blog.css" %}" rel="stylesheet">
</head>
<body>
<div id="content">
{% block content %}
{% endblock %}
</div>
<div id="sidebar">
<h2>Mój blog</h2>
<p>To jest mój blog.</p>
</div>
</body>
</html>
blog/templates/post/list.html
{% extends "blog/base.html" %}
{% block title %}Mój blog{% endblock %}
{% block content %}
<h1>Mój blog</h1>
{% if tag %}
<h2>Posty oznaczone tagiem "{{ tag.name }}"</h2>
{% endif %}
{% for post in posts %}
<h2>
<a href="{{ post.get_absolute_url }}">
{{ post.title }}
</a>
</h2>
<p class="tags">
Tagi:
{% for tag in post.tags.all %}
<a href="{% url "blog:post_list_by_tag" tag.slug %}">
{{ tag.name }}
</a>
{% if not forloop.last %}, {% endif %}
{% endfor %}
</p>
<p class="date">
Opublikowany {{ post.publish }} przez {{ post.author }}
</p>
{{ post.body|truncatewords_html:30|linebreaks }}
{% endfor %}
{% include "pagination.html" with page=posts %}
{% endblock %}
blog/templates/post/detail.html
{% extends "blog/base.html" %}
{% block title %}{{ post.title }}{% endblock %}
{% block content %}
<h1>{{ post.title }}</h1>
<p class="date">
Opublikowany {{ post.publish }} przez {{ post.author }}
</p>
{{ post.body|linebreaks }}
<p>
<a href="{% url "blog:post_share" post.id %}">
Udostępnij posta
</a>
</p>
<h2>Podobne posty</h2>
{% for post in similar_posts %}
<p>
{{ post.title }}
</p>
{% empty %}
Nie ma podobnych postów.
{% endfor %}
{% with comments.count as total_comments %}
<h2>
{{ total_comments }} komentarz{{ total_comments|pluralize:"y" }}
</h2>
{% endwith %}
{% for comment in comments %}
<div class="comment">
<p class="info">
Komentarz {{ forloop.counter }} dodany przez {{ comment.name }}
{{ comment.created }}
</p>
{{ comment.komentarz|linebreaks }}
</div>
{% empty %}
<p>Nie ma jeszcze żadnych komentarzy.</p>
{% endfor %}
{% if new_comment %}
<h2>Twój komentarz został dodany.</h2>
{% else %}
<h2>Dodaj nowy komentarz</h2>
<form action="." method="post">
{{ comment_form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Dodaj komentarz"></p>
</form>
{% endif %}
{% endblock %}
Thanks for any help !! (I thinking about this third day )

The problem you have it's in the views.
Django template has to be rendered by a view, from this view is where you get the data to be rendered in the template. It doesn't matter which url you want to use and which template you are using in the views. What this means is that you can have different urls pointing to the same template (www.example.com/blog/ or www.example.com/programming/) and both render the same template.
If i understood you right, all you have to do is change this :
url(r'^$', views.post_list, name='post_list'),
url(r'^programowanie/$', views.programowanie, name='programowanie'),
To this:
url(r'^$', views.post_list, name='post_list'),
url(r'^programowanie/$', views.post_list, name='programowanie'),
You can refer to the official Django website in order to get more information about this : https://docs.djangoproject.com/en/2.0/intro/tutorial03/

Thanks for help :)
I solved this problem. There was a problem in urls.py file.

Related

Django: child model edit comment not working

I got problem with my edit comments when i press the edit comment from the template i get no error but is redirected to the top of the same page. Anyone got any idea how i can get it to allow me to edit the comment?
This post is edited with only the code needed and i fixed the delete comment from before so that code is removed.
Here is my code:
views.py:
from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.db.models.functions import Lower
from .models import Product, Category, Review
from .forms import ProductForm, ReviewForm
def product_detail(request, product_id):
product = get_object_or_404(Product, pk=product_id)
if request.method == 'POST':
rating = request.POST.get('rating', 3)
content = request.POST.get('content', '')
Review.objects.create(
product=product,
rating=rating,
content=content,
created_by=request.user
)
# redirect to the same page
return redirect('product_detail', product_id=product_id)
reviews = Review.objects.filter(product=product)
context = {
'product': product,
'reviews': reviews
}
return render(request, 'products/product_detail.html', context)
#login_required
def edit_review(request, review_id):
"""
Saves review form edited by user
"""
review = get_object_or_404(Review, pk=review_id)
product = Product.objects.get(name=review.product)
if request.method == 'POST':
review_form = ReviewForm(request.POST or None, instance=review)
if review_form.is_valid():
review_form.save()
messages.success(request, 'Successfully updated product!')
return redirect(reverse('product_detail', args=[product.id]))
# Success message if added
messages.success(request, 'Thank You! Review was edited')
else:
# Error message if form was invalid
messages.error(request, 'Something went wrong. '
'Make sure the form is valid.')
form = ReviewForm(instance=review)
messages.info(request, f'You are editing {review_id}')
template = 'products/edit_review.html'
context = {
'form': form,
'product': review,
}
return redirect(reverse('product_detail', args=[product.id]))
models.py:
from django.db import models
from django.contrib.auth.models import User
class Review(models.Model):
product = models.ForeignKey(Product, related_name='reviews', on_delete=models.CASCADE)
rating = models.IntegerField(default=3)
content = models.TextField()
created_by = models.ForeignKey(User, related_name='reviews', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s - %s' % (self.product.name, self.created_by)
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.all_products, name='products'),
path('<int:product_id>/', views.product_detail, name='product_detail'),
path('add/', views.add_product, name='add_product'),
path('edit/<int:product_id>/', views.edit_product, name='edit_product'),
path('delete/<int:product_id>/', views.delete_product, name='delete_product'),
path('delete_review/<int:review_id>/delete_review', views.delete_review, name='delete-review'),
path('edit_review/<review_id>', views.edit_review, name="edit_review"),
]
forms.py:
from django import forms
from .widgets import CustomClearableFileInput
from .models import Product, Category, Review
class ReviewForm(forms.ModelForm):
class Meta:
model = Review
fields = ('content', 'rating')
widgets = {
'content': forms.Textarea(attrs={'class': 'form-control'}),
'rating': forms.Select(attrs={'class': 'form-control'}),
}
edit_review.html template
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="overlay"></div>
<div class="container">
<div class="row">
<div class="col-12 col-md-6">
<hr>
<h2 class="logo-font mb-4">Reviews</h2>
<h5 class="text-muted">Edit you're Review</h5>
<hr>
</div>
</div>
<div class="row">
<div class="col-12 col-md-6">
<form method="POST" action="{% url 'edit_review' review.id %}" class="form mb-2" enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
{% if field.name != 'image' %}
{{ field | as_crispy_field }}
{% else %}
{{ field }}
{% endif %}
{% endfor %}
<div class="text-right">
<a class="btn btn-outline-black rounded-0" href="{% url 'reviews' %}">Cancel</a>
<button class="btn btn-black rounded-0" type="submit">Update Review</button>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
for the first problem in the delete view you must refer to the model with capital Review
#login_required
def delete_review(request, review_id):
review = Review.objects.filter(review_id).last()
For the second problem you can see detailed information about this error and how to handle it, from Here

Django Model and Form for Comment system

I have made a comment system under my books where only the authenticated user can comment. When I use the form to add a comment, it doesn't work! why ?
here is my models
models.py
class Books(models.Model):
author = models.ManyToManyField(Authors)
title = models.CharField(max_length=250)
number_of_pages = models.PositiveIntegerField(validators=[MaxValueValidator(99999999999)])
date_added = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now=True)
publication_date = models.PositiveIntegerField(default=current_year(), validators=[MinValueValidator(300),
max_value_current_year])
cover = models.ImageField(upload_to='pics/covers/', default='pics/default-cover.jpg')
pdf_file = models.FileField(upload_to='pdfs/books/', default='pdfs/default-pdf.pdf')
category = models.ForeignKey(Categories, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Comments(models.Model):
book = models.ForeignKey(Books, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '{} - {}'.format(self.livre.title, self.user)
here is my forms
forms.py
class BookForm(ModelForm):
class Meta:
model = Books
fields = '__all__'
class CommentForm(ModelForm):
class Meta:
model = Comments
fields = ['body']
here is my views
views.py
#login_required(login_url='login')
def book_detail_view(request, book_id):
books = get_object_or_404(Books, pk=book_id)
context = {'books': books,}
return render(request, 'book_detail.html', context)
#login_required(login_url='login')
def add_comment(request, comment_id):
form = CommentForm()
books = get_object_or_404(Books, pk=comment_id)
user = request.user
if request.method == "POST":
form = CommentForm(request.POST, instance=books)
if form.is_valid():
comment = form.save(commit=False)
comment.user = user
comment.books = books
comment.save()
return redirect('book_detail', books.id)
context = {'form': form}
return render(request, 'comment_form.html', context)
here is my book detail page
book_detail.html
{% extends 'base.html' %}
{% block title %} {{ books.title }} {% endblock %}
{% block content %}
<div class="row">
<div class="col-lg-4">
<p><img src="{{ books.cover.url }}"></p>
</div>
<div class="col-lg-8">
<h2>{{ books.title }}</h2>
<b>Author : </b>
{% for author in books.author.all %}
{{ author.name }}
{% if not forloop.last %},{% endif %}
{% endfor %}<br/>
<b>Catégory : </b>{{ books.category }}<br/>
<b>Pages : </b>{{ books.number_of_pages }}<br/>
<b>Publication : </b>{{ books.publication_date }}<br/>
<b>Date added : </b>{{ books.date_added }}<br/>
<b>Updated : </b>{{ books.updated }}<br/>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<p><button class="btn btn-outline-dark btn-sm"><i class="far fa-eye"></i> Read</button></p>
</div>
</div>
<hr/>
<div class="container-fluid">
<h2>Comments</h2>
</div>
<div class="container-fluid">
{% if not books.comments.all %}
<p>No comments yet ! <a class="text-primary" href="{% url 'add_comment' books.id %}">Add comment...</a></p>
{% else %}
<a class="text-primary" href="{% url 'add_comment' books.id %}">Add comment !</a><br/><br/>
{% for comment in books.comments.all%}
<b>{{ comment.user }}</b> - <span class="text-muted" style="font-size: 13px;">{{ comment.date }}</span>
<p>{{ comment.body }}</p>
{% endfor %}
{% endif %}
</div>
{% endblock %}
here is my form for comment model
comment_form.html
{% extends 'base.html' %}
{% block title %} Add a comment {% endblock %}
{% block content %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Add this comment</button>
</form>
{% endblock %}
here is my urls
urls.py
urlpatterns = [
# BOOKS
path('book/<int:book_id>/', views.book_detail_view, name='book_detail'),
# COMMENTS
path('book/<int:comment_id>/comment/', views.add_comment, name='add_comment'),
]
Your form is currently set to edit the book, not the comment, you should remove the instance=books:
if request.method == "POST":
# no instance=books &downarrow;
form = CommentForm(request.POST)
If you use instance=books, the form will set attributes to the Books object, and then the comment = form.save(commit=False) will result in the fact that comment is a Books object that is already saved and thus updated in the database.
You also made a typo when setting the book of a Comments object: it is book, not books:
if form.is_valid():
comment = form.save(commit=False)
comment.user = user
comment.book = books # &leftarrow; .book, not .books
comment.save()
Note: normally a Django model is given a singular name, so Book instead of Books.

Unable to show user specific link to specific page in django

I would like to create user specific links. I mean, when user signed up and logged in, he has redirected to create/ page. In that page user fills out the form and after pressing button, user has to redirect to list/ page, where there are user specific links to specific page, which contain schedule. Schedul appered from data, which user provided in create/ form.
So my problem is, when I filled out the form and redirect to list/ page, there are no links.
My code:
models.py
from django.db import models
from django.contrib.auth.models import User
class File(models.Model):
file = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
#Further, they are fileds, which is nececary to create schedule.
#title = models.CharField('Название Графика', max_length = 50)
#x_title = models.CharField('Название Оси Х', max_length = 50)
#y_title = models.CharField('Название Оси Y', max_length = 50)
#etc...
views.py:
def create(request):
error = ''
if request.method == 'POST':
form = FileForm(request.POST)
if form.is_valid():
form.save()
return redirect('grafic:list')
else:
error = 'Форма была неверной('
form = FileForm()
data = {
'form': form,
'error': error,
}
return render(request, 'graf/create.html', data)
def list(request):
qs = File.objects.filter(file=request.user)
context = {
'user': request.user,
'qs': qs,
}
return render(request, 'graf/list.html', context)
list.html
{% extends 'base.html' %}
{% block content %}
{% if user.is_authenticated %}
<h2>{% block title %} Profile {% endblock %}</h2>
<p>Username: {{ user }}</p>
{% for b in qs %}
<article class="card">
<div class="card_wrapper">
<figure class="card_feature">
</figure>
<div class="card_box">
<a href="{% url 'grafic:index' b.id %}">
<header class="card_item card_header">
<h6 class="card__item card__item--small card__label">Твой график</h6>
<a class="card__item card__item--small card__title" href="{% url 'grafic:index' b.id %}">
{{b.graf_title}}
</a>
</header>
<hr class="card__item card__divider">
</a>
</div>
</div>
</article>
{% endfor %}
{% endif %}
{% endblock %}
urls.py
from django.urls import path
from . import views
app_name = 'grafic'
urlpatterns = [
path('', views.first, name = 'first'),
path('create/', views.main, name = 'main'),
path('list/', views.list, name = 'list'),
path('files/<int:grafics>', views.index, name = 'index'),
path('login/', views.loginpage, name = 'loginpage'),
path('register/', views.registerpage, name = 'registerpage'),
]
That's all. Sorry if my code is such inconvenient. Thank you in advance for your cooperation)
enter image description here
That is my problem. In the 'file' field there are no user.

django error: django.urls.exceptions.NoReverseMatch

I am creating a stock management system for my company. I don't know why the error: NoReverseMatch keeps coming for item_edit and item_delete views or urls. Because of these errors, I am not able to comple my CRUD views and modify or delete a exisiting item.
The Error: "django.urls.exceptions.NoReverseMatch: Reverse for 'stock_management.views.item_edit' not found. "
I have already tried going through my code a lot of time. I have also tried calling reverse() function for item_edit and item_delete from the shell and I also have also tried to manually enter the URLs in the browser but still the same error keeps showing.
My models:
class Item(models.Model):
GOLD_PURITY_CHOICES = (
...
)
COLOUR_CHOICES = (
...
)
DIAMOND_PURITY_CHOICES = (
...
)
RATING_CHOICES = (
...
)
code = models.CharField(max_length=25, db_index=True, unique=True)
gold_purity = models.CharField(
max_length=3, choices=GOLD_PURITY_CHOICES, default='14K')
labour = models.PositiveIntegerField()
certification_no = models.CharField(max_length=35, null=True, blank=True)
diamond_colour = models.CharField(
max_length=4, choices=COLOUR_CHOICES, default='F')
diamond_purity = models.CharField(
max_length=10, choices=DIAMOND_PURITY_CHOICES, default='IF')
rating = models.CharField(
max_length=3, default='A', choices=RATING_CHOICES)
gross = models.DecimalField(max_digits=6, decimal_places=3)
image = models.ImageField(blank=True, null=True,
upload_to=user_directory_path)
def __str__(self):
...
class Color(models.Model):
item = models.ForeignKey(
Item, on_delete=models.CASCADE, related_name='colors', help_text='Item to which the colors belong.')
shade = models.DecimalField(...)
price = models.IntegerField(...)
class Diamond(models.Model):
item = models.ForeignKey(
Item, on_delete=models.CASCADE, related_name='diamonds', help_text='Item to which the diamond belong.')
weight = models.DecimalField(...)
rate = models.IntegerField(...)
urls.py:
from django.urls import path, include
from .views import *
from django.conf import settings
app_name = 'stock_management'
urlpatterns = [
path('', index, name='homepage'),
path('stock/', stock_list, name='stock_list'),
path('stock/add', stock_create_view, name='add_stock'),
# Item:
path('item/edit/<pk>', item_edit, name='item_edit'),
path('item/delete/<pk>', ItemDeleteView.as_view(), name='item_delete'),
]
if settings.DEBUG:
# test mode
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
views.py:
def item_edit(request, pk=1):
item = get_object_or_404(Item, pk=pk)
ColorInlineFormSet = inlineformset_factory(
Item, Color, fields=('shade', 'price'), extra=1)
DiamondInlineFormSet = inlineformset_factory(
Item, Diamond, fields=('weight', 'rate'), extra=1)
if request.method == 'POST':
color_inline_formset = ColorInlineFormSet(
request.POST, instance=item)
diamond_inline_formset = DiamondInlineFormSet(
request.POST, instance=item)
item_form = ItemForm(request.POST, instance=item)
if item_form.is_valid() and color_inline_formset.is_valid() and diamond_inline_formset.is_valid():
item = item_form.save()
color_formset = color_inline_formset.save()
diamond_formset = diamond_inline_formset.save()
return redirect('stock_management:homepage')
else:
messages.error(request, item_form.errors)
messages.error(request, color_inline_formset.errors)
messages.error(request, diamond_inline_formset.errors)
else:
color_inline_formset = ColorInlineFormSet(
instance=item)
diamond_inline_formset = DiamondInlineFormSet(
instance=item)
item_form = ItemForm(instance=item)
return render(request, 'forms/add_stock.html', {'title': 'Edit Item Form', 'item': item, 'item_form': item_form, 'item_colour_forms': color_inline_formset, 'item_diamond_forms': diamond_inline_formset, })
def item_delete(request, pk):
item = get_object_or_404(Item, pk=pk)
if request.method == 'POST':
item.delete()
return redirect('stock_list')
return render(request, 'forms/utils/confirm_delete.html', {'title': item})
templates:
list.html:
{% extends 'index.html' %}
{% block title %} Stock {% endblock %}
{% block pageheading %} Stock List {% endblock %}
{% block content %}
{% for stock in stocks %}
<div class="card-body">
<div class="item pb-1">
<h5>{{ stock.item.code }}</h5>
{% if stock.item.image %}
<image src = " {{ stock.item.image.url }} " ></image>
{% endif %}
<a href=" {% url 'item_delete' stock.item.id %} " class="btn btn-danger btn-circle">
<i class="fas fa-trash"></i>
</a>
<a href="{% url 'item_edit' pk=stock.item.id %}" class="btn btn-info btn-circle">
<i class="far fa-edit"></i>
</a>
</div>
{% endfor %}
{% endblock %}
I want the error to be resolved so that I can complete my CRUD views and also can access my list.html again.
You need to add your appname with used urls in your html files when using urls.
Also update
<a href=" {% url 'stock_management:item_delete' pk=stock.item.id %}
to
<a href=" {% url 'stock_management:item_delete' stock.item.id %}
You code should looks like that:
{% extends 'index.html' %}
{% block title %} Stock {% endblock %}
{% block pageheading %} Stock List {% endblock %}
{% block content %}
{% for stock in stocks %}
<div class="card-body">
<div class="item pb-1">
<h5>{{ stock.item.code }}</h5>
{% if stock.item.image %}
<image src = " {{ stock.item.image.url }} " ></image>
{% endif %}
<a href=" {% url 'stock_management:item_delete' stock.item.id %} " class="btn btn-danger btn-circle">
<i class="fas fa-trash"></i>
</a>
<a href="{% url 'stock_management:item_edit' stock.item.id %}" class="btn btn-info btn-circle">
<i class="far fa-edit"></i>
</a>
</div>
{% endfor %}
{% endblock %}

Django navbar links disappearing in the post

So sorry probably this is very easy but i learn django and have a problem. My navbar working on index page is perfectly. but when i go contact form or another post url, navbar links disappear.
When i go some post page or my contact form page
1- {{ article.title }} and href links are disappear
Can i ask help ?
my navbar.html
{% load i18n %}
<!-- Menu -->
<div class="menu-wrapper center-relative">
<nav id="header-main-menu">
<div class="mob-menu">Menu</div>
<ul class="main-menu sm sm-clean">
<li>{% trans "HomePage" %}</li>
<li>{% trans "Services" %}</li>
<li>
{% for article in articles %}
{% if article.slug == 'about_us' %}
<a href="{% url 'article:detail' slug=article.slug %}">
{{ article.title }}</a>
{% endif %}
{% endfor %}
</li>
<li>{% trans "HELLO WORLD" %}</li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-1643 dropdown">
<a title="" href="">{% trans "Producs" %}</a>
<ul role="menu" class=" dropdown-menu">
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-1644 dropdown">
<a title="Level 2" href="">{% trans "Consult" %}</a>
<ul role="menu" class=" dropdown-menu">
<li >
{% for category in category %}
{% if category.name == 'consult' %}
{% for article in category.get_article %}
<a title="{{ article.title }}" href="{% url 'article:detail' slug=article.slug %}"> <p> {{ article.title }}</p></a>
{% endfor %}
{% endif %}
{% endfor %}</li>
</ul>
</li>
<li>
{% for category in category %}
{% if category.name == 'header' %}
{% for article in category.get_article %}
<a title="{{ article.title }}" href="{% url 'article:detail' slug=article.slug %}"> <p> {{ article.title }}</p></a>
{% endfor %}
{% endif %}
{% endfor %}
</li>
</ul>
</li>
<li>{% trans "İletişim" %}</li>
</ul>
</nav>
</div>
article/views.py
from django.shortcuts import render, get_object_or_404
from .models import Article, Category
from django.core.paginator import Paginator
from django.utils.translation import gettext as _
# Create your views here.
def articles(request):
keyword = request.GET.get("keyword")
if keyword:
articles = Article.objects.filter(title__contains=keyword)
paginator = Paginator(articles, 1)
page = request.GET.get('page')
articles = paginator.get_page(page)
return render(request,"articles.html",{"articles":articles})
articles = Article.objects.all()
paginator = Paginator(articles, 10)
page = request.GET.get('page')
articles = paginator.get_page(page)
return render(request, "articles.html", {"articles":articles})
def index(request):
articles = Article.objects.all()
category = Category.objects.all()
context = {
"articles": articles,
"category": category,
}
return render(request, 'index.html', context)
def detail(request,slug):
# article = Article.objects.filter (id = id).first()
article = get_object_or_404(Article, slug = slug)
category = Category.objects.all()
return render(request, "detail.html", {"article":article, "category":category,})
def category_detail(request,slug):
template = "category_detail.html"
category=get_object_or_404(Category,slug=slug)
article=Article.objects.filter(category=category)
context = {
'category' : category,
'article' : article,
}
return render(request,template,context)
def category_page(request):
object_list = Category.objects.all()
context = {'object_list': object_list,}
return render(request, 'detail.html', context)
contact_form/views.py
from django.views.generic.edit import FormView
from .forms import ContactForm
try:
from django.urls import reverse
except ImportError: # pragma: no cover
from django.core.urlresolvers import reverse # pragma: no cover
class ContactFormView(FormView):
form_class = ContactForm
recipient_list = None
template_name = 'contact_form/contact_form.html'
def form_valid(self, form):
form.save()
return super(ContactFormView, self).form_valid(form)
def get_form_kwargs(self):
if self.recipient_list is not None:
kwargs.update({'recipient_list': self.recipient_list})
return kwargs
def get_success_url(self):
return reverse('contact_form_sent')

Categories

Resources