Django: html without CSS and the right text - python

First of all, this website that I'm trying to build is my first, so take it easy. Thanks. Anyway, I have my home page, home.html, that extends from base.html, and joke.html, that also extends base.html. The home page works just fine, but not the joke page. Here are some parts of my files, for you to understand how I want my system to work:
views.py
def joke_page(request, joke_id):
joke = Joke.objects.get(id=int(joke_id))
return render(request, 'joke.html', {'joke': joke})
urls.py
urlpatterns = [
url(r'^$', views.home_page, name='home_page'),
url(r'^(?P<joke_id>[0-9]+)/$', views.joke_page, name='joke_page'),
]
joke.html
{% extends 'base.html' %}
{% block header_text %}{{ joke.title }}{% endblock %}
{% block text %}{{ joke.text }}{% endblock %}
What I want is that URLs that end like jokes/1/ to render a page with the right html using joke.html. Instead, it renders a page without CSS or with joke.title and joke.text Also, I noticed that jokes/1/ doesn't find anything:
DoesNotExist at /jokes/1/
Joke matching query does not exist..
I had 20 jokes in the database and I can find jokes/2/ through jokes/21/, which means their ids have shifted? :P
Can someone experienced with Django point out my(many, without a doubt) mistakes? Thank you!
Edit: second urls.py
urlpatterns = [
url(r'^$', jokes_views.home_page, name='home'),
url(r'^jokes/', include(jokes_urls)),
url(r'^admin/', include(admin.site.urls)),
]

Are you using the {% load staticfiles %} in your templates?

Related

How can I redirect to a page depend on different user group correctly by django?

I am creating a feature to let the banned user (user without any group) go to a specific page banned_alert when they click the "post", because they are not allowed to do so. But then when I test this feature, the Chrome shows This page isn’t working | the IP redirected you too many times. Can somebody tell me how to do it correctly? Did I miss any configuration? Below is my code snippets. Thank you for your time!
base.html: (has_group function already works correctly somewhere else)
{% load get_group %}
{% if request.user|has_group:"mod" or request.user|has_group:"default" or user.is_staff %}
<a class="nav-link" href="/create-post">Post</a>
{% else %}
<a class="nav-link" href="/banned_alert">Post</a>
{% endif %}
banned_alert.html:
{% extends 'main/base.html' %}
{% block title %}Your account has been banned by Admin{% endblock %}
{% load crispy_forms_tags %}
{% block content %}
<h2>Please contact the Admin!</h2>
{% endblock %}
view.py
def banned_alert(request):
return redirect('/banned_alert')
urls.py
urlpatterns = [
path('', views.home, name='home'),
path('home', views.home, name='home'),
path('sign-up', views.sign_up, name='sign_up'),
path('create-post', views.create_post, name='create_post'),
path('banned_alert', views.banned_alert, name='banned_alert'),
]
You have a recursion:
this is your path
path('banned_alert', views.banned_alert, name='banned_alert'),
User visit this banned_alert path,
it redirects user to view banned_alert
Which redirects user back to url banned_alert
and it redirects back to view banned_alert
reapeat N times (it has no ending)
best way to ban user is to create a flag in his model:
models.py
class User(AbstractUser):
is_banned = models.BooleanField(default=False)
if you want to ban user, change user's field is_banned to true, and then in your template or view, check if user is banned or not, and do your logic according to it
By the way, in your ulrs.py you need to close paths with backslash like this path('home/', views.home, name='home'),

How to include in django template a reverse url in translation

I have the following block of code, And I want to include a url to the login page, after the user logs out, in a translatable text.
Unfortunately, translation blocks cannot include tags, and I get the following error:
SyntaxError: Translation blocks must not include other block tags: url "account:login"
{% blocktrans %}
You have been successfully logged out.
You can log-in again.
{% endblocktrans %}
urls.py:
from django.urls import path
from django.contrib.auth import views as auth_views
app_name = 'account'
urlpatterns = [
path('login/', auth_views.LoginView.as_view(), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]
What would be the right way to achieve something like this?
Edit: I figured there are workarounds, such as translating blocks of text separately, or using javascript to append the "href" element after the page loads. But I wonder if there is a more efficient, Django way.
As documented
Reverse URL lookups cannot be carried out within the blocktrans and
should be retrieved (and stored) beforehand:
{% url 'path.to.view' arg arg2 as the_url %}
{% blocktrans %}
This is a URL: {{ the_url }}
{% endblocktrans %}

django can't show a template - how to fix

I just made the app users to validate user that is already registered in database. Included url inside project directory(urls.py), executed the login page in urls.py from app directory, made the template and a link refer in base.html. It all works, however when click Login link return this error:
TemplateDoesNotExist at users/login/
I tried to rename the path according tree navigation but always return this same error. Any idea what is happening?
Sorry my english
tree navigation in my project like this:
my_project
urls.py(project):
from django.contrib import admin
from django.urls import include, path
app_name = ['app_web_gym', 'users']
urlpatterns = [
path('admin/', admin.site.urls),
path('users/', include('users.urls', namespace='users')),
path('', include('app_web_gym.urls', namespace='app_web_gym')),
]
urls.py(app)
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
app_name = 'users'
urlpatterns= [
path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
]
base.html:
<p>
Web Gym-
Clientes-
Treinos-
Instrutores-
{% if user.is_authenticated %}
<p>Hello, {{user.username}}.<p/>
{% else %}
Login
{% endif %}
</p>
{% block content %} {% endblock content %}
login.html:
{% extends 'app_web_gym/base.html' %}
{% block content %}
{% if form.errors %}
<p>Wrong username/password. Try again.</p>
{% endif %}
<form method='POST' action="{% url 'users:login' %}">
{% csrf_token %}
{{form.as_p}}
<button name='submit'>Log in</button>
<input type='hidden' name='next' value="{% url 'app_web_gym:index' %}" />
</form>
{% endblock content %}
I printed the full error:
TemplateDoesNotExist
I noticed that says Django tried loading these templates, in this order, in last line ->
/home/at_admin/prj01/app_web_gym/templates/users/login.html (Source does not exist)
thats the wrong path to login.html the correct is
/home/at_admin/prj01/users/templates/users/login.html as shown in tree navigation.
I don't know why is this happening and don't know how to fix it.
have you registered your app in main settings.py? It occurs sometimes when you forget to register your app
In main settings.py file:
at the end of, add one more line
INSTALLED_APPS = ['appname'] (replace appname with the name of your app having login page)
Hey people i just deleted all the app users and recreated it with the same coding that i previously copied. It worked this time though still don't know what happened.
Thanks all
First you should've checked if the app was installed in your settings. And as it looks in the error the files were being looked at the wrong place(app_web_gym/users/login.html) instead of (users/login.html). So I suppose you made a mistake in installing your app in settings.py.

how to work with two apps in django

Hello im learning django and i would like to know if its a way to make my two apps work i have my folders like this
mysite/
--/app1 (blog app)
--/app2 (a list of users that signs up with a form)
--/mysite
--db
--manage.py
my app2 has the index.html and the structure.html which i use to inheritate my others html files, so
im trying to use the post_list.html file that i made in my app1, first of all this is how my urls looks something like this
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'info', 'app2.views.grid'),
url(r'', 'app2.views.home'),
url(r'^blog/', 'app1.views.post_list')
)
my app1 views looks like this
from django.shortcuts import render
from .models import Post
# Create your views here.
def post_list(request):
posts = Post.objects.filter(published_date_isnull=False).order_by('published_date')
return render(request, 'app1/post_list.html',{'posts':posts})
then my post_list.html looks like this
{% extends "/app2/templates/app2/structure.html" %}
{% block content %}
{% for post in posts %}
<div class="post">
<div class="date">
{{ post.published_date }}
</div>
<h1>{{ post.title }}</h1>
<p>{{ post.text|linebreaks }}</p>
</div>
{% endfor %}
{% endblock %}
when i enter to my browser and type 127.0.0.1:8000/blog/ it keeps apearing my app2/index.html, what am i missing? do i have to do anything else than adding my views to my url like i did?
aditional info: i added my app2 and my app1 to my settings thoe
I think your urls.py needs to be updated:
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^info', 'app2.views.grid'),
url(r'^$', 'app2.views.home'),
url(r'^blog/', 'app1.views.post_list')
)
url(r'', 'app2.views.home') will act like a wild card since python uses regular expressions to match. Take a look at the URL dispatcher documentation for a better understanding of what's going on.

Django reverse error: NoReverseMatch

I've looked at a lot of different posts, but they're all either working with a different version of django or don't seem to work. Here is what I'm trying to do:
urls.py (for the entire project):
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^blog/', include('blog.urls', namespace="blog")),
url(r'^admin/', include(admin.site.urls)),
)
urls.py (specific to the app):
urlpatterns = patterns ('' ,
url(r'^$', views.index, name='index'),
url(r'^(?P<slug>[\w\-]+)/$', views.posts, name="postdetail"),
)
views.py:
def index(request):
posts = Post.objects.filter(published=True)
return render(request,'blog/index.html',{'posts':posts})
def posts(request, slug):
post = get_object_or_404(Post,slug=slug)
return render(request, 'blog/post.html',{'post':post})
And finally the template:
{% block title %} Blog Archive {% endblock %}
{% block content %}
<h1> My Blog Archive </h1>
{% for post in posts %}
<div class="post">
<h2>
<a href="{% url "postdetail" slug=post.slug %}">
{{post.title}}
</a>
</h2>
<p>{{post.description}}</p>
<p>
Posted on
<time datetime="{{post.created|date:"c"}}">
{{post.created|date}}
</time>
</p>
</div>
{% endfor %}
{% endblock %}
For some reason this gives me a "No reverse Match": Reverse for 'postdetail' with arguments '()' and keyword arguments '{u'slug': u'third'}' not found. 0 pattern(s) tried: []
I've already tried getting rid of the double quotes around postdetail in the template, and I've also tried referring to it by the view name instead of the pattern name. Still no luck. The documentation isn't too helpful either.
Help is really appreciated! Thanks
You've used a namespace when including the URLs, so you probably need to use "blog:postdetail" to reverse it.

Categories

Resources