I have just started with using Django with a Django Crash Course book and got stuck on a part.
Let me show you what I have done so far and where I got stuck.
I opened a templates folder on the hellodjango project folder and wrote some basic HTML code like this.
<h1>Greetings</h1>
<p>Hello, world!</p>
<p>{{my_statement}}</p>
Here, the book says that it is okay to write my_statement like this because it will be later understood in python.
Later on it tells you to change views.py file under the homepage folder like this.
from django.views.generic import TemplateView
class HomepageView(TemplateView):
template_name = 'index.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['my_statement'] = "Nice to see you:"
return context
However, when I refresh the page my_statement variable doesn't show up on the webpage at all. What could I possibly be doing wrong? I think if I didn't didn't have the packages, an error would pop up? But errors don't show up as well.
I have also checked the django documentation on this topic but the code here has similarities to the one I am working with.
Thanks for your help.
Related
Hi I am new to Python/django and am using VS Code. Now I got python IntelliSense and pylance extension installed and most things are showing up on IntelliSense but some aren't.
How can I get it to work for everything?
I would very much appreciate some insight since it's driving me nuts...
request.POST from an imported lib not showing up
selected_meetup.participants not showing up nor is selected_meetup.participants.add
from urllib import request
from django.forms import SlugField
from django.shortcuts import render
from .models import Meetup
from .forms import RegistrationForm
# from django.http import HttpResponse
# Create your views here.
def index(request):
meetups = Meetup.objects.all()
return render(request, 'meetups/index.html', {
'meetups': meetups
})
def meetup_details(request, meetup_slug):
try:
selected_meetup = Meetup.objects.get(slug=meetup_slug)
if request == 'GET':
registration_form = RegistrationForm()
else:
registration_form = RegistrationForm(request.POST)
registration_form = RegistrationForm(request.)
if registration_form.is_valid():
participant = registration_form.save()
selected_meetup.participants.add(participant)
return render(request, 'meetups/meetup-detail.html', {
'meetup_found': True,
'meetup': selected_meetup,
'form': registration_form
})
except Exception as exc:
return render(request, 'meetups/meetup-detail.html', {'meetup_found': False
})
Update:
That's great guys, I now understand the type problem it's obvious now (only had so many extensions issues especially django/html) I got confused...
Now I added types to Meetup and Participant but selected_meetup.participants. still refused to show me its method ADD.
I assume the problem is the lib is written without types. Is there a way to solve that? because quite valuable to me to be able to see what's possible write away...
have you got solutions to that?
I would re-install the extensions, then make sure it is referencing the right version of python. If that doesn't work I would recommend to just type it out in full and look past the error.
You didn't declare what type of object request is in the programming process. Maybe you can declare request = request () in the code.The second is the same. vscode can't recognize the type of the selected_meetup you wrote.
You can hover over these two objects and find that the vscode prompt the type can be any.
Thank you to all of the people who looked at this in advance! I really appreciate it.
I have setup a very simple model that consists of two parameters (title, which is the date when this was published and the text, that's it):
models.py
class Post(models.Model):
title = models.DateField(blank=True, null=True)
body = models.TextField()
def __str__(self):
return str(self.title)
After following a standard "create a blog in Django tutorial" I have created two views that show the list of everything posted and a view that will show details of any selected post.
views.py
class NowListView(ListView):
model = Post
template_name = 'archive.html'
class NowDetailView(DetailView):
model = Post
template_name = 'then.html'
Finally, I have this urls.py that successfully shows all the posts at http://127.0.0.1:8000/now/archive and specific post at http://127.0.0.1:8000/now/archive/1 (or any other number, depending on the pk).
urls.py
urlpatterns = [
path('archive', NowListView.as_view(), name='archive'),
path('archive/<int:pk>', NowDetailView.as_view(), name='then'),
]
What I want to achieve is to display the latest post on http://127.0.0.1:8000/now.
I have tried a million ways to do it, and nothing worked, always something in the way (would take too long to write all of them). After all this tries it is obvious to me that I have to use a query to pull the latest post, but I have no working way of doing it.
I have tried using this Post.objects.earliest('title') and this Post.objects.order_by('title').first() in my urls as such:
urls.py
urlpatterns = [
path('archive', NowListView.as_view(), name='archive'),
path('archive/<int:pk>', NowDetailView.as_view(), name='then'),
path('>',NowDetailView.as_view(Post.objects.order_by('title').first()), name='then'),
]
This gives me an error:
TypeError: as_view() takes 1 positional argument but 2 were given
I have also tried creating a def function under my class in views.py, but the error then was that the urls couldn't import it for some reason.
In any case, I am probably over thinking it and just simply being stupid. If anyone could help me with this I would be very grateful! Thanks a ton in advance and sorry for the long question!
Best,
Rasul Kireev
This belongs in the view., not the URL.
You need to define get_object:
class NowLatestView(DetailView):
model = Post
template_name = 'then.html'
def get_object(self)
return Post.objects.order_by('title').first()
So I'm creating a small ecommerce website for a friend and cannot work out why the url won't resolve itself.
For the sake of simplicity whilst making the website I'm using a product called "number 1". It has a slug field of "number-1" and on the product page clicking on the product takes a user to "/shop/number-1"
My url pattern for this is:
url(r'^<slug:url>', views.item, name='products')
with the view:
def item(request, url=""):
products = product.objects.get(url=url)
return render(request, 'shop\product.html', {'products', products})
As far as I can tell this should render my product.html template but instead it returns a 404 and I'm not sure why?
If it helps I have other views, such as product types set within the same views and they work fine so as far as I can tell its that the slug:url isn't being used in the views.item, or the view isn't getting the context properly.
Also I'm on django 1.11.7 for this project.
The url pattern you are trying to use (slug:url) is only valid in Django 2.
If you are on Django 1.11 then you need to use a regular expression - something like this:
url(r'^?P<url>[\w-]+', views.item, name='products')
Always make sure you're looking at the documentation for your version of Django ;-).
Please change url pattern to:
url(r'^?P<url>[\w-]+', views.item, name='products')
I'm (new to) working in Django and would like to create two features that do not rely upon models/database tables. The basis of this app is as a web-based wrapper to a Python application.
The features are:
I would like to be able to load a ConfigObj text file into a page and edit it's configuration prior to saving again.
I would like to be able to call command line python/bash scripts and display their output on a page - like exec in PHP.
At the moment I'm working on simple custom admin pages without model as described here:
Django admin, section without "model"?
Would this be the right direction to go in? I'm not sure proxy tables apply as the features I desire have nothing to do with any data.
So far I have looked at is it possible to create a custom admin view without a model behind it and a few other links. At the moment I have:
main/urls.py
url(r'^admin/weectrl', include('weectrl.urls')),
which links with weectrl/urls.py
from weectrl import views
urlpatterns = patterns('',
(r'^admin/weectrl/manage/$', weectrl_manage_view),
(r'^admin/weectrl/config/$', weectrl_config_view),
)
which points to weectrl/views.py
def weectrl_manage_view(request):
r = render_to_response('admin/weectrl/manage.html', context, RequestContext(request))
return HttpResponse(r)
def weectrl_config_view(request):
r = render_to_response('admin/weectrl/config.html', context, RequestContext(request))
return HttpResponse(r)
The current error message is name 'weectrl_manage_view' is not defined
Ok, found something that works.
In the main url.py
url(r'^admin/weectrl/', include('weectrl.urls')),
In app/urls.py
urlpatterns = patterns('',
url(r'^config/$', views.config, name='config'),
url(r'^manage/$', views.manage, name='manage'),
)
and in app/views.py
def config(request):
context = ""
return render(request, 'weectrl/config.html', context)
def manage(request):
context = ""
return render(request, 'weectrl/manage.html', context)
html files are in app/templates/app/...
I am trying to create a custom context processor which will render a list of menu items for a logged in user. I have done the following:
Within my settings.py I have
TEMPLATE_CONTEXT_PROCESSOR = (
'django.contrib.auth.context_processors.auth',
'mysite.accounts.context_processors.user_menu',
)
Under the accounts submodule I have context_processors.py with the following, for now:
def user_menu(request):
return {'user_menu':'Hello World'}
On my template page I have the following:
{% if user.is_authenticated %}
Menu
{{user_menu}}
{% endif %}
The invoking view is as follows:
def profile(request):
return render_to_response('accounts/profile.html',context_instance=RequestContext(request))
However I am unable to get the {{user_menu}} to render anything on the page, I know the user is authenticated as other sections of the template with similar checks render correctly. Am I missing something here. Please help
Thank you
Edit: Thanks Ben, Daniel, I have fixed the (S) in TEMPLATE_CONTEXT_PROCESSOR, however Django now has trouble resolving the module and I get the following message
Error importing request processor module django.contrib.auth.context_processors: "No module named context_processors"
UPDATE: I fixed it by changing the path to django.core.context_processors.auth Seems like the modules have been moved around
The setting name should be TEMPLATE_CONTEXT_PROCESSORS, with an S.