I am new to Django. I created a simple createview and then tried the updateview likewise but I got the NoReverseMatch Error. I tried many ways suggested online but still they didnt seem to work.
This is the screenshot of the error I am getting NoReverseMatchError
Below are my files
urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import url,include
from mapp import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^$',views.AboutView.as_view(),name='about'),
url(r'^blogs/$',views.BlogsView.as_view(),name='blog'),
url(r'^project/$',views.ProjectListView.as_view(),name='project_list'),
url(r'^project/(?P<pk>\d+)/$',views.ProjectDetailView.as_view(),name='project_detail'),
url(r'^project/create/$',views.ProjectCreateView.as_view(),name='project_create'),
url(r'^project/(?P<pk>\d+)/$',views.ProjectUpdateView.as_view(),name='update'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Views.py
from django.shortcuts import render,redirect
from django.views.generic import TemplateView,ListView,DetailView,CreateView,UpdateView
from mapp.models import Project
from mapp.forms import ProjectCreateForm,ProjectUpdateForm
# Create your views here.
class AboutView(TemplateView):
template_name='about.html'
class BlogsView(TemplateView):
template_name='blogs.html'
class ProjectListView(ListView):
model=Project
class ProjectDetailView(DetailView):
model=Project
class ProjectCreateView(CreateView):
model=Project
form_class=ProjectCreateForm
redirect_field_name='mapp/project_detail.html'
class ProjectUpdateView(UpdateView):
model=Project
form_class=ProjectUpdateForm
redirect_field_name='mapp/project_detail.html'
Project_detail.html
{% extends 'base.html'%}
{% block content %}
<h1>Project Details</h1>
<div class="container">
<h2>{{project.pname}}</h2>
<img src="{{project.pimage.url}}"></img>
<h2>{{project.ptech}}</h2>
<h2>{{project.pdetails}}</h2>
</div>
<div class="container">
<p>Update
</div>
{% endblock %}
Forms.py
from django import forms
from mapp.models import Project
class ProjectCreateForm(forms.ModelForm):
class Meta:
model=Project
fields=('pname','pimage','ptech','pdetails')
class ProjectUpdateForm(forms.ModelForm):
class Meta:
model=Project
fields=('pname','pimage','ptech','pdetails')
Project_form.html
{% extends 'base.html' %}
{% block content %}
<form class="project-form" method="POST" enctype="multipart/form-data">
<div class="jumbotron">
{% csrf_token %}
{{form.as_p}}
<button type="submit" class="save btn btn-default">Save</button>
</div>
</form>
{% endblock %}
Looks like your kwargs are not being passed to the view. Try changing self.id in your template to project.id
{% extends 'base.html'%}
{% block content %}
<h1>Project Details</h1>
<div class="container">
<h2>{{project.pname}}</h2>
<img src="{{project.pimage.url}}"></img>
<h2>{{project.ptech}}</h2>
<h2>{{project.pdetails}}</h2>
</div>
<div class="container">
<p>Update
</div>
{% endblock %}
Also your Detail and Update Views have the same url. Try adding something to make them different like
url(r'^project/detail/(?P<pk>\d+)/$',views.ProjectDetailView.as_view(),name='project_detail'),
url(r'^project/create/$',views.ProjectCreateView.as_view(),name='project_create'),
url(r'^project/update/(?P<pk>\d+)/$',views.ProjectUpdateView.as_view(),name='update'),
Or else it won't find the updateview.
Related
I tried several ways to upload images to a specific destination. Showing no error but the image is not uploading to the destination.
views.py
from django.views.generic.edit import CreateView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
fields = ['name', 'weblink', 'image']
success_url = reverse_lazy('posts')
template_name = 'base/post.html'
def form_valid(self, form):
# form.instance.post_id = self.kwargs['pk']
form.instance.author = self.request.user
return super().form_valid(form)
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
name = models.CharField(max_length=200)
weblink = models.CharField(max_length=200)
image = models.ImageField(default='default.png', upload_to='uploads/%Y/%m/%d/')
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return f'Added {self.name} Profile'
urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
.....
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
template
{% extends 'base/base.html' %}
{% block content %}
<div class="row justify-content-md-center home">
<div class="col-md-6 create-form">
← Back
</div>
</div>
<div class="row justify-content-md-center">
<div class="col-md-6 submit-form">
<form action="" method="POST">
{% csrf_token %}
{{form.as_p}}
<button class="btn btn-info" type="submit">Submit</button>
</form>
</div>
</div>
{% endblock content %}
I added also the media root and URL in the settings file. I didn't any clue but unable to upload the file to the specific location.
When your form is supposed to submit files you must set the enctype attribute on the form tag to multipart/form-data otherwise files won't be submitted:
{% extends 'base/base.html' %}
{% block content %}
<div class="row justify-content-md-center home">
<div class="col-md-6 create-form">
← Back
</div>
</div>
<div class="row justify-content-md-center">
<div class="col-md-6 submit-form">
<!-- Set it here ↓ -->
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<button class="btn btn-info" type="submit">Submit</button>
</form>
</div>
</div>
{% endblock content %}
I have been working on to make the website which people can post their review on restaurants. I finished creating urls.py, views.py, models.py and html file.
I tried to connect the list page with the detailed page on each restaurants. Therefore, I used str:pk tag to connect list page with detail page.
However it does't work and however times I check, I can't find why the error happens.
settings and other settings are already done. I only have to adjust app files.
My Goal:
List of restaurants are already created. I want user to be able to go to the detail page by clicking the button below the "{{ list.outline}}"
models.py
from django.db import models
from django.utils import timezone
stars = [
(1,"☆"),
(2,"☆☆"),
(3,"☆☆☆"),
(4,"☆☆☆☆"),
(5,"☆☆☆☆☆")
]
# Create your models here.
class Tabelog(models.Model):
store_name = models.CharField("店名",max_length = 124,primary_key=True)
title = models.CharField("タイトル",max_length = 124,null=True,blank=True)
evaluation = models.IntegerField("評価",choices = stars)
comment = models.TextField("口コミ")
create_date = models.DateField("口コミ投稿日",default=timezone.now)
price = models.PositiveIntegerField("値段",help_text='円',default=0)
def outline(self):
return self.comment[:10]
def __str__(self):
return ("{},{},{}".format(self.store_name,self.evaluation,self.comment[:10]))
urls.py
from django.urls import path,include
from Tabelog import views
from Tabelog.views import ReviewList,ReviewDetail,ReviewForm,ReviewFix,ReviewDelete,ReviewContact,ReviewContactComplete
app_name = "Tabelog"
urlpatterns = [
path("lp/", views.lp,name="lp"),
path("list/", ReviewList.as_view(),name="list"),
path("detail/<str:pk>/",ReviewDetail.as_view(),name="detail"),
path("form/",ReviewForm.as_view(),name="form"),
path("form/fix/<str:pk>/",ReviewFix.as_view(),name="form_fix"),
path("form/delete/<str:pk>/",ReviewDelete.as_view(),name="delete"),
path("contact/",ReviewContact.as_view(),name="contact"),
path("contact/complete/",ReviewContactComplete.as_view(),name="ContactComplete")
]
forms.py
from django.shortcuts import render,redirect,get_object_or_404
from Tabelog.models import Tabelog
from Tabelog.forms import CreateTabelogForm
from django.views import generic
from Tabelog.forms import CreateTabelogForm,ContactForm
from django.urls import reverse_lazy
from django.core.mail import send_mail
from django.template.loader import render_to_string
# Create your views here.
def lp(request):
return render(request,"Tabelog/lp.html")
class ReviewList(generic.ListView):
model = Tabelog
class ReviewDetail(generic.DetailView):
model = Tabelog
class ReviewForm(generic.CreateView):
model = Tabelog
form_class = CreateTabelogForm
success_url = reverse_lazy("Tabelog:list")
class ReviewFix(generic.UpdateView):
model = Tabelog
fields = "__all__"
success_url = reverse_lazy("Tabelog:list")
class ReviewDelete(generic.DeleteView):
model = Tabelog
success_url = reverse_lazy("Tabelog:list")
class ReviewContact(generic.FormView):
template_name = "Tabelog/tabelog_contact.html"
form_class = ContactForm
success_url = reverse_lazy("Tabelog:ContactComplete")
def form_valid(self,form):
subject = "お問い合わせがありました"
message = render_to_string('Tabelog/mail.txt',form.cleaned_data,self.request)
from_email = "toiawase#gmail.com"
recipient_list = ["yutotennisnowboard#gmail.com"]
send_mail(subject,message,from_email,recipient_list)
return redirect('Tabelog:list')
class ReviewContactComplete(generic.TemplateView):
template_name = "Tabelog/tabelog_contact_complete.html"
tabelog_list.html
<!DOCTYPE html>
{% extends 'diary/base.html' %}
{% block title %}お店リスト{% endblock %}
{% block content %}
{% for list in object_list %}
<div class="card border-primary mb-3">
<div class="card-body text-primary">
<h1 class="card-title">{{list.store_name}}</h1>
<h2 class="card-text">{{ list.get_evaluation_display}}</h2>
<span class="card-text">{{ list.outline}}</span><br>
<button type="button" class="btn btn-light"> See More Detail! </button>
</div>
</div>
{% endfor %}
{% endblock %}
tabelog_detail.html
<!DOCTYPE html>
{% extends 'diary/base.html' %}
{% load static %}
{% block title %}Detail Page{% endblock %}
{% block design %}
<link rel="stylesheet" href="{% static 'css/detail.css' %}">
{% endblock %}
{% block content %}
<div class="container">
<div class="card border-info mb-3">
<div class="card-body">
<h1 class="card-title">{{object.title}}</h1>
<p class="card-text">投稿者:{{ object.writer }}</p>
<p class="card-text">作成日:{{ object.created_at}}</p>
<p class="card-text">更新日:{{ object.last_modefied}}</p>
<p class="card-text">カテゴリ:{{ object.category}}</p>
<p class="card-text">タグ:{% for tag in object.tag.all %}{{tag}},{% endfor %}</p>
<div class="card-text">
{{object.text| linebreaks | urlize }}
</div><br>
<button type="button" class="btn btn-light"> Change the post </button>
</div>
</div>
</div>
<div class="container">
<button type="button" class="btn btn-light"> コメントする</button>
</div>
<div class="container">
<article class="card border-info mb-3" id="comment">
<div class="card-body">
{% for comment in article.comment_set.all %}
<p class="card-text">{{comment | linebreaks | urlize}}</p>
{% endfor %}
</div>
</article>
</div>
{% endblock %}
The problem was caused by the detail page connected from list page. I realized that the error message doesn't necessarily show the specific cause.
I'm new in Django. My problem is when I click the title which is in a.html, it's directing me to this URL; http://localhost:8000/aba/R%C3%BCyada%20Aba%20G%C3%B6rmek
in this URL I'm getting an error message; Page not found 404
Here is I wanna do; When I click the title, I wanna show my article details dynamically
dreamarticle/urls.py
from django.contrib import admin
from django.urls import path, re_path
from dreamarticle import views
app_name = "Dreamarticle"
urlpatterns = [
re_path('/aba/(.*?)/',views.aba,name="aba"),
path('a/',views.a,name="a"),
]
blog/urls.py
from django.contrib import admin
from django.urls import path,include
from article import views
from dreamarticle import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name="index"),
path('articles/',include("article.urls")),
path('user/',include("user.urls")),
path('dreamarticle/',include("dreamarticle.urls")),
]
dreamarticle/views.py
def aba(request, title):
context = dict()
context.update(
dreamarticlesaba=get_object_or_404(dreamarticle, title=title),
)
return render(request, "aba.html", context)
aba.html
{% extends "layout.html" %}
{% block body%}
<!-- Content here -->
<br>
<div class="container">
<div class="row">
{% if dreamarticlesaba %}
{% for dreamarticle in dreamarticlesaba %}
<div class="col-md-12 dreamdetail">
<h1>{{dreamarticle.title}}</h1>
<hr>
<p>{{dreamarticle.content|safe|escape}}<p>
</div>
{% endfor %}
{% endif %}
</div>
</div>
a.html
{% extends "layout.html" %}
{% block body%}
{% include "includes/searchbar.html" %}
<!-- Content here -->
<br>
<div class="container">
<div class="row">
{% if dreamarticles %}
{% for dreamarticle in dreamarticles %}
<div class="col-md-4 text-center bg-primary">
<br><b>{{dreamarticle.title}}</b>
<b>{{dreamarticle.title}}</b>
</a>
</div>
{% endfor %}
{% endif %}
</div>
</div>
{% endblock body%}
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/aba/R%C3%BCyada%20Aba%20G%C3%B6rmek
Using the URLconf defined in blog.urls, Django tried these URL patterns, in this order:
admin/
[name='index']
articles/
user/
dreamarticle/
The current path, aba/Rüyada Aba Görmek, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
I have setup django-summernote on my project and everything is great, it works very good on admin , but i want to use it on my templates.
Note :
in django-summernote documentation they only explain how to use it if you have forms.py file but I dont
my main urls.py :
urlpatterns = [
path('games/', include('core.urls', namespace='core')),
path('summernote/', include('django_summernote.urls')),
]
my app(name=core) urls.py :
from django.urls import path
from . import views
app_name = 'core'
urlpatterns = [
path('new/', views.GameCreate.as_view(), name='game_new'),
path('<int:pk>/edit/', views.GameUpdate.as_view(), name='game_edit'),
]
my views.py :
class GameCreate(LoginRequiredMixin, CreateView):
model = Game
template_name = 'core/game_new.html'
fields = '__all__'
redirect_field_name = 'home'
class GameUpdate(LoginRequiredMixin, UpdateView):
model = Game
template_name = 'core/game_edit.html'
fields = '__all__'
my template file "game_new.html" :
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %} Add New Game {% endblock %}
{% block main %}
<section class="main-section">
<div class="container">
<h1>New Game</h1>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form|crispy }}
<input type='submit' value="Save" />
</form>
</div>
</section>
{% endblock %}
my template file "game_edit.html":
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %} Game Info {% endblock %}
{% block main %}
<section class="main-section"></section>
<div class="container">
<h1>Edit Game Info</h1>
<form action="" method="post">
{% csrf_token %}
{{ form|crispy }}
<input type="submit" value="Update" />
</form>
</div>
</section>
{% endblock %}
my Models.py :
from django.db import models
from django.urls import reverse
# Create your models here.
class Game(models.Model):
name = models.CharField(max_length=140)
developer = models.CharField(max_length=140)
game_trailer = models.CharField(max_length=300, default="No Trailer")
game_story = models.TextField(default='No Story')
Firstly in your template dont forgate to add this:
{{ form.media }} <<<------ To load all js and css attached
In the document your models you must herit summernote widget. Example:
from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget
class FormFromSomeModel(forms.ModelForm):
class Meta:
model = SomeModel
widgets = {
'foo': SummernoteWidget(),
'bar': SummernoteInplaceWidget(),
}
I have this code on my template:
{% extends "base.html" %}
{% block content %}
<div style="padding:40px;margin:40px;border:1px solid #ccc">
<h1>picture</h1>
<form action="" method="post" enctype="multipart/form-data"> <!--{% url 'imageupload' %}-->
{% csrf_token %} {{form}}
<input type="submit" value="Upload" />
</form>
{% for img in images %}
{{forloop.counter}}.{{ img.pic.name }}
({{img.upload_date}})<hr />
{% endfor %}
</div>
{% endblock content %}
Although I have doubts with the form action but anyways.
The problem is that when I click on submit button, it takes me to a blank page, no pop-up to actually upload the image, nothing.
Is there some example I should follow to accomplish this?
Also, this is just a proof test, but I'd like to know if a model and/or form is actually needed for it to work?
EDIT
Okay, by editing the input line like this <input type="file" name='input_name' /> it actually opens the file pop-up, but obviously it doesn't upload anything, it needs like a submit button or something, so, now it looks like this:
{% extends "base.html" %}
{% block content %}
<div style="padding:40px;margin:40px;border:1px solid #ccc">
<h1>picture</h1>
<form action="" method="post" enctype="multipart/form-data"> <!--{% url 'imageupload' %} -->
{% csrf_token %} {{form}}
<input type="file" name='input_name' />
<input type="submit" value="Upload" />
</form>
{% for img in images %}
{{forloop.counter}}.{{ img.pic.name }}
({{img.upload_date}})<hr />
{% endfor %}
{% endblock content %}
But when I click on submit, it keeps sending me to a blank page, so, the value on submit, which is Upload, comes from this model:
from django.db import models
from django.forms import ModelForm
class Upload(models.Model):
pic = models.FileField(upload_to="static/")
upload_date=models.DateTimeField(auto_now_add =True)
class UploadForm(ModelForm):
class Meta:
model = Upload
fields = ('pic',)
And on my views.py:
from django.shortcuts import render
from uploader.models import UploadForm,Upload
from django.http import HttpResponseRedirect
from django.urls import reverse
def home(request):
if request.method=="POST":
img = UploadForm(request.POST, request.FILES)
if img.is_valid():
img.save()
return HttpResponseRedirect(reverse('imageupload'))
else:
img=UploadForm()
images=Upload.objects.all()
return render(request,'image_upload.html',{'form':img,'images':images})
And in my urls.py:
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
from uploader import views as uploader_views
urlpatterns = [...
some patterns...
url(r'^image_upload/', uploader_views.home, name='imageupload'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)