Django - missing 1 required positional argument: '_id' - django

im getting an error
BlogDetailView() missing 1 required positional argument: '_id'
when im trying to access the function BlogDetailView.
views.py :
from django.http.response import Http404
from .models import BlogModel,CommentModel
from .forms import SearchForm,CommentForm
from django.shortcuts import render,redirect
def BlogDetailView(request,_id):
try:
data = BlogModel.objects.get(id = _id)
comments = CommentModel.objects.filter(blog = data)
except BlogModel.DoesNotExist:
raise Http404('Data does not exist')
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
Comment = CommentModel(your_name= form.cleaned_data['your_name'],
comment_text=form.cleaned_data['comment_text'],
blog=data)
Comment.save()
return redirect(f'/blog/{_id}')
else:
form = CommentForm()
context = {
'data': data,
'form': form,
'comments': comments,
}
return render(request,'Test_one/detailview.html',context)
urls.py :
from django.conf.urls import url
from django.urls.conf import path
from blogapp.views import BlogDetailView, BlogListView
from . import views
app_name = "Blogapp"
urlpatterns = [
url(r'^blogs/', views.BlogDetailView, name="blogs"),
url(r'^blog/<int:_id>', views.BlogListView, name="blog"),
]
Can anyone solve this problem?

I think you wrote code wrongly, logically a blog list doesn't need an id to fetch (you want all blog posts so probably don't need id) and you need to fetch a specific blog post so you need an id to fetch this. so I think this is the right code that you tried to write:
from django.conf.urls import url
from django.urls.conf import path
from blogapp.views import BlogDetailView, BlogListView
from . import views
app_name = "Blogapp"
urlpatterns = [
url(r'^blogs/<int:_id>', views.BlogDetailView, name="blogs"),
url(r'^blog/', views.BlogListView, name="blog"),
]

Related

Django redirect another view from another app form

contact/views.py
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from .forms import ContactForm
def contactView(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(subject, message, from_email, ['admin#example.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
# return redirect('success')
return redirect('PostList') #another view from another app
return render(request, "contact.html", {'form': form})
# def successView(request):
# return HttpResponse('Success! Thank you for your message.')
contact/urls.py
from django.contrib import admin
from django.urls import path
from .views import contactView
urlpatterns = [
path('contact/', contactView, name='contact'),
# path('success/', successView, name='success'),
]
blog/views.py
from django.views import generic
from .models import Post, PostImage
# Create your views here.
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'index.html'
class PostDetail(generic.DetailView):
model = Post
template_name = 'post_detail.html'
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
# Add in a QuerySet of all the books
# context['image_list'] = PostImage.objects.all()
# context['image_list'] = self.get_object().postimage_set.all()
context['image_list'] = PostImage.objects.filter(post__slug=self.kwargs.get('slug'))
return context
blog/urls.py
from . import views
from django.urls import path
urlpatterns = [
path('', views.PostList.as_view(), name='home'),
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
]
I need the following in the SIMPLEST DRY manner possible; how do I write this redirect inside contact/views.py?
return redirect('PostList') #another view from another app
PostList is a class-based view from another app called blog. It is the homepage essentially.
for reference..
https://ordinarycoders.com/blog/article/django-messages-framework
In your project folder (eg, my_project/my_project) you should have a urls.py with something like this
path("admin/", admin.site.urls),
path("", include("blog.urls")),
path("", include("contact.urls"))
This allows django to look through all url files in the order listed. So long as all your url names and patterns are unique, then your view should be able to simply do
from django.shortcuts import redirect
from django.urls import reverse
return redirect(reverse('home'))
'home' being the name value of the ListView.
(NB: if you have various applevel urls.py files with path(''... django will take the first one it hits)

django.core.exceptions.ImproperlyConfigured error

Here is the error message:
django.core.exceptions.ImproperlyConfigured:
The included URLconf '<module 'basicsiteApp' from '/Users/msa/trydjango/basicsite/basicsiteApp/__init__.py'>'
does not appear to have any patterns in it.
If you see valid patterns in the file then the issue is probably
caused by a circular import.
I don't have anything written in init.py because I don't know what I need to write in it so it can work.
Below is what I have in views.py:
from django.shortcuts import render
from .forms import SignUpForm
from django.contrib import messages
def signup(request):
if request.method == 'POST'
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Account Created')
return render(request, 'signup.html')
else:
form = SignUpForm()
render(request, 'signup.html')
Basicsite/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('basicsiteApp')),
path('admin/', admin.site.urls)
]
basicsiteApp/urls.py:
from django.urls import path
from . import views
app_name = 'basicsiteApp'
urlpatterns = [
path('', views.signup, name='signup')
]
I know it comes late, but if someone (like me) faces the same problem:
In your "Basicsite/urls.py"
path('', include('basicsiteApp')),
it should be
path('', include('basicsiteApp.urls')),
implying django to use the basicsiteApp/urls.py file instead of basicsiteApp/init.py

why I have issues in importing views in the urls.py file?

from employee import views
does not work!...the server is giving a page not found (404) response
here is the project structure:
employee
migrations folder
....other files
views.py
hrdjango
__init__.py
settings.py
urls.py
I feel like the urls can't access my views
this is the views.py
from .models import Employee
# Create your views here.
def emp(request):
if request.method == "POST":
form = EmployeeForm(request.POST)
if form.is_valid():
try:
form.save()
return redirect('/show')
except:
pass
else:
form = EmployeeForm()
return render(request,'index.html',{'form':form})
def show(request):
employees = Employee.objects.all()
return render(request,"show.html",{'employees':employees})
def edit(request, id):
employee = Employee.objects.get(id=id)
return render(request,'edit.html', {'employee':employee})
def update(request, id):
employee = Employee.objects.get(id=id)
form = EmployeeForm(request.POST, instance = employee)
if form.is_valid():
form.save()
return redirect("/show")
from django.contrib import admin
from django.urls import path
from employee import views
urlpatterns = [
path('admin/', admin.site.urls),
path('emp', views.emp),
path('show',views.show),
path('edit/<int:id>', views.edit),
path('update/<int:id>', views.update),
path('delete/<int:id>', views.destroy),
]
urls.py
I am having unresolved import 'employee'message
Is this the project urls.py or the app-level urls.py? If this is your app level urls.py, then the import should be from . import views. If it is the project-level urls.py, then post up your file structure so we can see if the import structure is wrong.
I think the better solution would be to use separate urls.py file for separate apps and then include them to your root urls.
create a urls.py in your app.
in your root urls.py
from django.urls import path,include
urlpatterns = [
...,
...,
path('employee/', include('employee.urls')),
]

Django redirecting to a different view in another app

There are many similar questions to mine on Stack Overflow, but none which solve my problem.
I have a class-based view which accepts files, and once a valid file is found, I would like the website to redirect the user to a template inside a different app, passing in some parameters.
I've seen others put an extra path in 'urlpatterns' and get the view from there. But doing this only makes a GET signal on my command prompt, but not actually changing the web url.
views.py
from django.shortcuts import render, redirect # used to render templates
from django.http import JsonResponse
from django.views import View
from .forms import UploadForm
from .models import FileUpload
class UploadView(View):
def get(self, request):
files_list = FileUpload.objects.all()
return render(self.request, 'upload/upload.html', {'csv_files': files_list})
def post(self, request):
form = UploadForm(self.request.POST, self.request.FILES)
if form.is_valid():
csv_file = form.save()
data = {'is_valid': True,
'name': csv_file.file.name,
'url': csv_file.file.url,
'date': csv_file.uploaded_at}
# REDIRECT USER TO VIEW PASSING 'data' IN CONTEXT
return redirect('graph:chart', file_url=csv_file.file.url)
else:
data = {'is_valid': False}
return JsonResponse(data)
urls.py
from django.urls import path
from . import views
app_name = "upload"
urlpatterns = [
path('', views.UploadView.as_view(), name='drag_and_drop'),
]
urls.py (of other app)
from django.urls import path
from . import views
app_name = "graph"
urlpatterns = [
path('', views.page, name='chart'),
]
You can specify an app name and use exactly the redirect shortcut as you started:
https://docs.djangoproject.com/en/2.1/topics/http/urls/#naming-url-patterns
in the other app urls.py define app_name = 'other_app', and then use redirect('other_app:url_name', parameter1=p1, parameter2 = p2)
you can name easily your parameters either using path (Django >=2.0) or url (re_path for Django >=2.0), for instance:
from django.urls import path
from . import views
urlpatterns = [
path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail),
re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
]

Custom template in django form wizard - NameError

I am trying to create custom templates for a simple contact form as per the django docs but I am getting a NameError. Looks like a simple issue but I can't figure it out. Any help will be greatly appreciated. The error message is:
"NameError at /contact/
name 'wizardcustomtemplate' is not defined"
where 'wizardcustomtemplate' is the app. Here is my code:
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from wizardcustomtemplate.forms import SubjectForm, SenderForm, MessageForm
from wizardcustomtemplate.views import ContactWizard
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^contact/$', ContactWizard.as_view(FORMS)),
)
views.py
import os
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.core.mail import send_mail
from django.core.context_processors import csrf
from django.contrib.formtools.wizard.views import SessionWizardView
from django.contrib.formtools.wizard.views import WizardView
from django.core.files.storage import FileSystemStorage
from django.core.files import File
FORMS = [("0", wizardcustomtemplate.forms.SubjectForm),
("1", wizardcustomtemplate.forms.SenderForm),
("2", wizardcustomtemplate.forms.MessageForm)
]
TEMPLATES = {"0": "wizardcustomtemplate/subject.html",
"1": "wizardcustomtemplate/sender.html",
"2": "wizardcustomtemplate/message.html"
}
class ContactWizard(SessionWizardView):
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
def done(self, form_list, **kwargs):
form_data = process_form_data(form_list)
return render_to_response('wizardcustomtemplate/thanks.html', {'form_data': form_data})
def process_form_data(form_list):
form_data = [form.cleaned_data for form in form_list]
return form_data
forms.py
from django import forms
class SubjectForm(forms.Form):
subject = forms.CharField(max_length = 100,initial='Wizard')
class SenderForm(forms.Form):
sender = forms.EmailField(initial='abcd#efgh.org')
class MessageForm(forms.Form):
message = forms.CharField(initial='How r u?')
The form wizard works fine if I don't use the custom templates (FORMS, TEMPLATES etc.) Please let me know if you need additional information.
Solved it by adding import wizardcustomtemplate in views.py as suggested by #Rohan.