Django Form Code not saving - django

/deneme.html
<!DOCTYPE html>
<html>
<head>
<title>Doktor Ekleme</title>
<link rel="stylesheet" type="text/css" href="/dosyalar/base.css" />
</head>
<body>
<h1>Doktor Ekle</h1>
<form action="/deneme/" method="POST">
{% csrf_token %}
<input maxlength="50" name="adi" type="text" value=""/>
<input type="submit" value="Gönder" class="default" name="save">
</form>
</body>
</html>
/views.py
from django.http import *
from django.template import RequestContext
def deneme(request):
if request.method=='POST':
adi=request.POST.get('adi')
kaydet=doktor(adi=adi)
kaydet.save()
return render_to_response('deneme.html',context_instance = RequestContext(request))
thats code is not error but not saving
/models.py
from django.db import models
class doktor(models.Model):
adi = models.CharField(max_length='50')
def __str__(self):
return 'adi :%s' %(self.adi)
not error but not saving
/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
import portal_site.views
import yonetim.views
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'DernekPortali.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'', include('portal_site.urls')),
url(r'', include('yonetim.urls')),
url(r'^deneme/',yonetim.views.deneme),
)
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
where is error ? that's code. not save database !!
help me plsss
help me plsss
help me plsss
that's code not error but code not saving

dissolved :))))
/.views.py
def deneme(request):
replace
def xx(request):
/.urls.py
url(r'^deneme/',yonetim.views.deneme),
replace
url(r'^deneme/',yonetim.views.xx),
that's error => same variable

Related

Page not foung 404 error - Slug id not displaying (found) : http://127.0.0.1:8000/postscommentapp/6/how-learn-anything-very-easily

Sir, I'm developing a slug project in Django. When I try to print the slug id post it will not display shows 404 error. Tried n number of times. Anyone, please help me to fix this in urls.py.
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/postscommentapp/6/how-learn-anything-very-easily
Using the URLconf defined in postscommentpro.urls, Django tried these URL patterns, in this order:
admin/
postscommentapp/(?P\d+)/(?P[\w-]+)/$ [name='post_detail']
The current path, postscommentapp/6/how-learn-anything-very-easily, didn't match any of these.
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'draft'),
('published', 'published')
)
title = models.CharField(max_length=50)
slug = models.CharField(max_length=50)
author = models.ForeignKey(User, on_delete = models.CASCADE)
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft')
def __str__(self):
return self.title
admin.py
from django.contrib import admin
from .models import Post
# Register your models here.
class AdminPost(admin.ModelAdmin):
list_display = ['title', 'slug', 'body', 'author', 'created', 'updated', 'status']
prepopulated_fields = {'slug':('title',)}
list_editable = ('status',)
admin.site.register(Post, AdminPost)
views.py
from django.shortcuts import render
from .models import Post
# Create your views here.
def post_List(request):
posts = Post.objects.all()
return render(request, 'postscommentapp/post_list.html', {'posts':posts})
def post_detail(request, id, slug):
post = Post.objects.get(id=id)
return render(request, 'postscommentapp/post_detail.html', {'post':post})
url.py - postscommentapp
from django.urls import path
from postscommentapp import views
urlpatterns = [
path('', views.post_List, name=''),
path('postscommentapp/(?P<id>\d+)/(?P<slug>[\w-]+)/$', views.post_detail, name='post_detail'),
]
urls.py
"""postscommentpro URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('postscommentapp.urls')),
]
post_detail.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h2>{{ post.title }}</h2>
</body>
</html>
post_list.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<!-- Bootstrap CDN Lines -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght#600;700&display=swap" rel="stylesheet">
</head>
<style>
.col-md-6{
text-align: justify;
}
.img-thumbnail{
border:1px solid #6b6b47;
}
.title{
font-family: 'Poppins', sans-serif;
}
</style>
<body style="font-family: 'Poppins', sans-serif;">
<div class="container-fluid">
<br>
<h2 class="text-center" style="font-weight:bold; color: #0040ff;">Post Comments Python/Django Project:</h2>
<div class="row">
{% for each_item in posts %}
<div class="col-md-6">
<br>
<div class="img-thumbnail">
⭐ {{ each_item.title }}<small style="float:right">{{ each_item.created }}</small><br>
➟ Author: {{ each_item.author }}<br><br>
{{ each_item.body }}<br>
</div>
<br>
</div>
{% endfor %}
</div>
</div>
</body>
</html>
I solved this error in my own way. In urls.py postscommentapp
from django.urls import path
from postscommentapp import views
urlpatterns = [
path('', views.post_List, name=''),
path('postscommentapp/(?P<id>\d+)/(?P<slug>[\w-]+)/$', views.post_detail, name='post_detail'),
]
change this url code in to this urls.py - postscommentapp
from django.urls import path
from postscommentapp import views
urlpatterns = [
path('', views.post_List, name=''),
path('post/<int:id>/<slug:slug>/', views.post_detail, name='post_detail'),
]
Write this line in views.py
from django.shortcuts import render, get_object_or_404
from .models import Post
# Create your views here.
def post_List(request):
posts = Post.objects.all()
return render(request, 'postscommentapp/post_list.html', {'posts':posts})
def post_detail(request, id, slug):
# post = Post.objects.get(id=id)
post = get_object_or_404(Post, id=id, slug=slug)
return render(request, 'postscommentapp/post_detail.html', {'post':post})

I'm getting a NoReverseMatch error in my home page

I'm getting a NoReverseMatch error in my home page. It is from the html that I injected from my announcement app. It says that the reverse of the link is cannot be found. When I removed that line It shows the card but the text with template tag.
_announcement_home.html:
<div class="container">
<div class="card announcement-card" style="width: 18rem;">
<h5 class="card-header">Announcement</h5>
<div class="card-body">
<h5 class="card-title">{{announcement.title}}</h5>
<p class="card-text">{{announcement.text}}</p>
<span class="announcement-date">{{announcement.date}}</span>
{% if user.is_authenticated %}
Change
{% endif %}
</div>
</div>
<br>
</div>
index.html:
{% extends 'base.html' %}
{% block content %}
<div class="w3-container w3-teal">
<h1>BANNER HERE</h1>
<p>Dito yung banner</p>
</div>
{% include 'announcement/_announcement_home.html' %}
{% endblock %}
urls.py:
from django.urls import path
from . import views
app_name = 'announcement'
urlpatterns = [
path('create/', views.AnnouncementCreateView.as_view(), name='create'),
path('', views.AnnouncementListView.as_view(), name='list'),
path('posts/<int:pk>/', views.AnnouncementDetailView.as_view(), name='single'),
path('delete/<int:pk>/', views.AnnouncementDeleteView.as_view(), name='destroy'),
path('edit/<int:pk>/', views.AnnouncementUpdateView.as_view(), name='edit')
]
main urls.py:
"""urcipro URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from home import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.Home.as_view(), name='home'),
path('bod/', views.BOD.as_view(), name='bod'),
path('announcement/', include('announcement.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
views.py:
from django.shortcuts import render
from django.views import generic
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy, reverse
from django.contrib import messages
from . import forms
from . import models
# Create your views here.
class AnnouncementListView(LoginRequiredMixin, generic.ListView):
model = models.Announcement
class AnnouncementDetailView(LoginRequiredMixin, generic.DetailView ):
model = models.Announcement
class AnnouncementUpdateView(LoginRequiredMixin, generic.UpdateView):
model = models.Announcement
form_class = forms.AnnouncementForm
class AnnouncementCreateView(LoginRequiredMixin, generic.CreateView ):
model = models.Announcement
form_class = forms.AnnouncementForm
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
class AnnouncementDeleteView(LoginRequiredMixin, generic.DeleteView ):
model = models.Announcement
def get_success_url(self):
return reverse('home')
def delete(self, *args, **kwargs):
messages.success(self.request, "Post Deleted")
return super().delete(*args, **kwargs)
home app views.py:
from django.shortcuts import render
from django.views.generic import TemplateView
# Create your views here.
class Home(TemplateView):
template_name = 'index.html'
class BOD(TemplateView):
template_name = 'bod.html'
This is what I see when I remove the a tag:
Error traceback:
It looks like the context has announcement to display this information, and then you used self in the url tag which isn't defined.
So change the url param to announcement.pk which we can assume will exist because that's the object in use with this block.
<div class="card-body">
<h5 class="card-title">{{announcement.title}}</h5>
<p class="card-text">{{announcement.text}}</p>
<span class="announcement-date">{{announcement.date}}</span>
{% if user.is_authenticated %}
Change
{% endif %}
</div>

Why "Page not found" when I click on login button in bms_homepage.html?

URLS.PY
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.homepage, name='homepage'),
path('login', views.login, name='login'),
]
VIEWS.PY
from django.http import HttpResponse
from django.shortcuts import render
def homepage(request):
return render(request, 'bms_homepage_template/bms_homepage.html')
def login(request):
return render(request, 'bms_homepage_template/login_page.html')
login_page.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<h1>LOGIN INTO YOUR ACCOUNT</h1>
<form action="">
Account Number:
<input type="text"> <br>
Password:
<input type="text"> <br>
<input type="submit" value="submit">
</form>
</body>
</html>
bms_homepage.html
<button id="login">LOGIN</button>
What i want to do is from homepage.html, when i click on login button it should open login_page.html
but it is showing me this error.
Page not found
Please explain in simple words.
You should refer url pattern name rather then template name.
In your case url pattern name is login:
urlpatterns = [
..
path('login', views.login, name='login'), <<<--- "name" argument value
]
To refer to this pattern you should use url-reversion template tag like this:
...

Request is not getting into views, but its shows the corret url

Form is loaded in html page but when i click submit button,it shows nothing(No HttpResponse which i used in views). But it show url(http://localhost:8000/datainsert )as i described in urls.py. Please point out what's wrong in my code.
forms.py
from django import forms
from .models import Test
class TestForm(forms.ModelForm):
class Meta:
model = Test
fields = '__all__'
views.py
def datainsert(request):
if request.method == 'POST':
form = TestForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse('Saved')
return HttpResponse('Not saved')
urls.py
from django.conf.urls import url
from . import views
from .views import index, datainsert, testing
urlpatterns = [
url(r'^', views.index, name='index'),
url(r'^datainsert', views.datainsert, name='datainsert'),
]
index.html
<html>
<head>
<title>My Web</title>
</head>
<body>
<form action="{% url 'myapp:datainsert' %}" method="POST">
{% csrf_token %}
{{form}}
<button type="submit">Submit</button>
</form>
</body>
</html>
You didn't terminate your empty URL.
url(r'^$', views.index, name='index')
Currently it matches every possible path.

Image is not showing in django template but other tag is working

I am trying to show up my image in django template. But the image is not showing. There is a headline tag which is working fine. I don't know where I am stuck. I searched it here and got a lot of solution, but none of this are not solving my issue.
Here is my views.py:
from django.shortcuts import render
from .models import Post
from django.utils import timezone
# Create your views here.
def home(request):
posts = Post.objects.order_by('id')
return render(request, 'home.html')
Here is my urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from Picture import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.home, name='home')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And this is home.html:
{% load static %}
<html>
<head>
<title>Home Page</title>
<meta charset='utf-8'>
</head>
<body>
<h1>{{ posts.title }}</h1>
<img src="{{ posts.image.url }}" alt="image-{{ post.title }}">
</body>
Images are in the media directory. Please help me to fix my problem.
I see two problems with your code
return render(request, 'home.html') does not have posts context parameter
In your template file posts object is likely to be a queryset, you need to loop through it to render its properties
def home(request):
posts = Post.objects.order_by('id')
return render(request, 'home.html', {"posts":posts})