I am trying to build an educational website and am trying to put all categories using for loops in a dropdown in the navbar. I have put it in base.html and all other templates extend base.html. But the items are only shown in the root page whose template is home.html.
I have tried using passing multiple contexts to all posts.
base.html:
{% load static %}
<!doctype html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}">
<title>{% block title %}ION{% endblock %}</title>
</head>
<body>
<header class="site-header">
<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand mr-4" href="{% url 'blog-home' %}">ION</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarToggle">
<div class="navbar-nav mr-auto">
<a class="nav-item nav-link" href="{% url 'blog-home' %}">Home</a>
<a class="nav-item nav-link" href="{% url 'post-all' %}">Posts</a>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Categories</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
{% for cate in cat %}
<a class="dropdown-item" href="{% url 'category' cate.pk %}">{{ cate.name }}</a>
{% endfor %}
</div>
</li>
<a class="nav-item nav-link" href="{% url 'blog-about' %}">About</a>
</div>
<!-- Navbar Right Side -->
<div class="navbar-nav">
{% if user.is_authenticated %}
<a class="nav-item nav-link" href="{% url 'post-create' %}">New Post</a>
<a class="nav-item nav-link" href="{% url 'profile' %}">Profile</a>
<a class="nav-item nav-link" href="{% url 'logout' %}">Logout</a>
{% else %}
<a class="nav-item nav-link" href="{% url 'login' %}">Login</a>
<a class="nav-item nav-link" href="{% url 'register' %}">Register</a>
{% endif %}
</div>
</div>
</div>
</nav>
</header>
<main role="main" class="container">
<div class="row">
<div class="col-md-12">
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{message.tags}}">
{{message}}
</div>
{% endfor %}
{% endif %}
{% block content %}{% endblock %}
</div>
</div>
</div>
</main>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
<!--From snippets navigation, main, and the starter template: https://getbootstrap.com/docs/4.3/getting-started/introduction/
home.html (Only place where it works):
{% extends "blog/base.html" %}
{% block title %}
ION Home
{% endblock %}
{% block content %}
<div class="text-center">
<h1>Home</h1>
</div>
<div class="card">
<img class="card-img-top" src="https://www.litmos.com/wp-content/uploads/2016/06/blog-eLearning-templates.png" alt="Card image cap">
<div class="card-body">
<h3 class="card-title text-center">Learning Reimagined</h3>
<p class="card-text">
ION is an open network that intends to reimagine learning. Anyone from anywhere can upload courses and help those unable to go to conventional schools or as an aid for education.
We promote education to the fullest. We believe in equal right for everyone. Students can take the help of ION to study or even make ION their primary study source.
</p>
</div>
</div>
{% endblock %}
views.py:
def home(request):
context = {
'posts': Post.objects.all(),
'cat': Category.objects.all()
}
return render(request, 'blog/home.html', context)
def about(request):
return render(request, 'blog/about.html', {'title':'About'})
class PostListView(ListView):
model = Post
template_name = 'blog/posts.html' #<app>/<model>_<viewtype>.html
context_object_name = 'posts' #It needs the specifying to loop over just like it did in the context of home
ordering = ['-date_posted']
paginate_by = 15
class UserPostListView(ListView):
model = Post
template_name = 'blog/user_posts.html' #This is when you click a profile in a post, it takes you to his posts only
context_object_name = 'posts'
paginate_by = 15
def get_queryset(self):#This does so that it takes you to the user posts only if he currently still exists
user = get_object_or_404(User, username=self.kwargs.get('username'))
return Post.objects.filter(author=user).order_by('-date_posted')
class PostDetailView(DetailView):
model = Post
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
fields = ['title', 'content', 'display', 'category']
def form_valid(self, form):#This sets the user to be the author of the blog you're trying to create
form.instance.author = self.request.user
return super().form_valid(form)
class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Post
fields = ['title', 'content', 'display', 'category']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):#This is where only the author can update the post
post = self.get_object()
if self.request.user == post.author:
return True
return False
class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Post
success_url = '/'
def test_func(self):#This is where only the author can update the post
post = self.get_object()
if self.request.user == post.author:
return True
return False
class CatPostListView(ListView):
model = Post
template_name = 'blog/science.html' #This is when you click a profile in a post, it takes you to his posts only
context_object_name = 'posts'
paginate_by = 15
def get_queryset(self):
return Post.objects.filter(category=2).order_by('-date_posted')
models.py:
class Category(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField()
parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.SET_NULL)
class Meta:
# enforcing that there can not be two categories under a parent with same slug
# __str__ method elaborated later in post. use __unicode__ in place of
# __str__ if you are using python 2
unique_together = ('slug', 'parent',)
verbose_name_plural = "categories"
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.SET_NULL)
display = models.TextField(max_length=250)
date_posted = models.DateTimeField(default=timezone.now)#DON'T USE () HERE Just auto_now_ will show the date of the current day
author = models.ForeignKey(User, on_delete=models.CASCADE)#No () #This deletes the posts when the user is deleted
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
I expect the categories to show up on all pages.
It won't because there is no category data in other pages(apart from home page). So either you can send the Category variable through context variable cat in each view, or you can create a custom context processor, like this:
def cat_on_all_pages(request):
return {'cat': Category.objects.all()}
And add it in the settings:
'OPTIONS': {
'context_processors': [
'path.to.cat_on_all_pages',
# other context processors
],
}
If you add custom context processor, then you can remove cat from context in home view.
Related
I am studying to develope a blog website using DJango's generic view class.
I categorized blogs into categories.
If you select a blog from the full list and go to the detail page, you have implemented the ability to go to the previous post and the next post using "previous()" and "next()" in that post.
I want to select a blog from a category list and move it to the preivous post or the next post according to that category list, but I don't know how.
What can I do?
models.py
class Post(models.Model):
..........
def prev(self):
return self.get_previous_by_created_at()
def next(self):
return self.get_next_by_created_at()
views.py
class PostListByCategory(PostList):
def get_queryset(self):
slug = self.kwargs['slug']
if slug == 'no_category':
category = None
else:
category = Category.objects.get(slug=slug)
return Post.objects.filter(category=category).order_by('-pk')
def get_context_data(self, **kwargs):
context = super(PostListByCategory, self).get_context_data()
slug = self.kwargs['slug']
if slug == 'no_category':
category = 'None'
else:
category = Category.objects.get(slug=slug)
context['category'] = category
return context
post_detail.html
..............
<div class="row row-cols-auto">
{% if object.next %}
<div class="col">
<a href="{% url 'tube_detail' object.next.pk %}" class="btn btn-sm pt-1 pb-1 bg-light" title="Prev">
<i class="bi bi-caret-left-fill" style="color:#dd3535"></i>
</a>
</div>
{% endif %}
<div class="col">
<a href="{% url 'tube_list' %}{% if request.GET.category %}category/{{ request.GET.category}}{% endif %}" class="btn btn-sm pt-1 pb-1 bg-light" title="LIST">
<i class="bi bi-list" style="color:#dd3535"></i>
</a>
</div>
{% if object.prev %}
<div class="col">
<a href="{% url 'tube_detail' object.prev.pk %}" class="btn btn-sm pt-1 pb-1 bg-light" title="Next">
<i class="bi bi-caret-right-fill" style="color:#dd3535"></i>
</a>
</div>
{% endif %}
</div>
''''''''''''
Hi I am letting the user upload multiple images per project but so far the images are not displayed. In projects.html all projects should be displayed and the title and the describtion work so far. But the main-image doesn´t show up. In single-project all images should be displayed.
What do I have to change in my models.py?
Thanks in forward
models.py
class Project(models.Model):
title = models.CharField(max_length=200)
describtion = models.TextField(null=True, blank=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
class ProjectImage(models.Model):
project = models.ForeignKey(Project, on_delete=models.CASCADE)
featured_images = models.FileField()
forms.py
class ProjectForm(ModelForm):
featured_images = forms.ImageField(widget=ClearableFileInput(attrs={'multiple':True}))
class Meta:
model = Project
fields = ['title', 'describtion', 'featured_images']
views.py
def createProject(request):
form = ProjectForm()
if request.method == 'POST':
form = ProjectForm(request.POST)
images = request.FILES.getlist('image')
if form.is_valid():
project = form.save()
for i in images:
ProjectImage(project=project, image=i).save()
context = {'form':form}
return render(request, 'projects/project_form.html', context)
def projects(request):
projects = Project.objects.all()
context = {"projects":projects}
return render(request, 'projects/projects.html', context)
def project(request, pk):
projectObj = Project.objects.get(id=pk)
return render(request, 'projects/single-project.html', {'project':projectObj})
projects.html
{% for project in projects %}
<div class="column">
<div class="card project">
<a href="{% url 'project' project.id %}" class="project">
<img class="project__thumbnail" src="{{project.featured_images.url}}" alt="project thumbnail" />
<div class="card__body">
<h3 class="project__title">{{project.title}}</h3>
<h3 class="project__title">{{project.price}} €</h3>
</div>
</a>
</div>
</div>
{% endfor %}
single-project.html
<h3 class="project__title">{{project.title}}</h3>
<h3 class="project__title">{{project.price}} €</h3>
<h3 class="singleProject__subtitle">Infos zum Produkt</h3>
{{project.describtion}}
project_form.html
<form class="form" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
<div class="form__field">
<label for="formInput#text">{{field.label}}</label>
{{field}}
</div>
{% endfor %}
<input class="btn btn--sub btn--lg my-md" type="submit" value="Submit" />
</form>
To access the images of a project, you need to use the related manager in your templates:
projects.html
{% for project in projects %}
<div class="column">
<div class="card project">
<a href="{% url 'project' project.id %}" class="project">
<img class="project__thumbnail" src="{{project.projectimage_set.all.0.featured_images.url}}" alt="project thumbnail" />
<div class="card__body">
<h3 class="project__title">{{project.title}}</h3>
<h3 class="project__title">{{project.price}} €</h3>
</div>
</a>
</div>
</div>
{% endfor %}
I assumed that by "main-image" you mean the first image of the project.
single-project.html
<h3 class="project__title">{{project.title}}</h3>
<h3 class="project__title">{{project.price}} €</h3>
<h3 class="singleProject__subtitle">Infos zum Produkt</h3>
{{project.describtion}}
{% for projectimage in project.projectimage_set.all %}
<img src="{{projectimage.featured_images.url}}"/>
{% endfor %}
To avoid the N+1 query problem, you can also change the query in your view:
views.py
def projects(request):
projects = Project.objects.all().prefetch_related('projectimage_set')
context = {"projects":projects}
return render(request, 'projects/projects.html', context)
I create two model name subject and section if I create a model name maths I want to create some section in it which is one to one so I am trying to load the page of a section acc to the subject like I click on maths link only the section which is relate to math open no other section open I think you understand so here is my code
my models.py
class Subject(models.Model):
name = models.CharField(max_length=80, blank=False,)
thumbnail = models.ImageField(upload_to='subject thumbnail', blank = False)
total_Section = models.FloatField(default='0')
joined_date = models.DateTimeField(default=timezone.now,editable=False)
update_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Section(models.Model):
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
sub_section = models.CharField(max_length=500, blank=True)
title = models.CharField(max_length=5000, blank=False)
teacher = models.CharField(max_length=500, blank=False)
file = models.FileField(upload_to='section_vedios', blank=False)
price = models.FloatField(blank=False)
content_duration = models.DurationField(blank=False)
joined_date = models.DateTimeField(default=timezone.now,editable=False)
update_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
my views.py for subject
#login_required
def home(request):
subject_list = Subject.objects.all()
return render (request, 'home.html', {'subject_list': subject_list })
my views.py for sections
#login_required
def sections(request):
return render (request, 'sections.html',)
my html for subject it worked
<ul>
{% for subject in subject_list %}
<li class="sub"> <a name='thumb' class="thumb" href="{% url 'subjects:section' %}"><img class="thumbnail" src="{{ subject.thumbnail.url }}" alt="">
<span><strong> {{ subject.name }} </strong> </span> </a>
<p>No of Section : {{ subject.total_section }} </p> </li>
{% endfor %}
</ul>
my html for viewing section according to subject by clicking link it is not showing anything
<li class="sub"> <a name='thumb' class="thumb" href="#">
<span><strong> {{ subject.section.title }} </strong> </span> </a>
<p>Name: {{ subject.section.teacher }} </p> {{ subject.section.price }} </li>
</div>
my urls.py for home html in which subject are rendering
urlpatterns = [
path('Register/',views.register,name='register'),
path('', views.my_login, name='login'),
path('logout/',views.user_logout,name='logout'),
path('SectionWise/',views.home,name='home'),
path('edit-profile/',views.edit_profile,name='edit')
]
my urls.py for section
urlpatterns = [
path('Section/', views.sections, name='section'),
path('add_section/',views.add_sections,name='add_section')
]
I tried to use above method like for subject but in every link it shows all the section no matter which subject link you are clicking
adding as asked
urls.py
urlpatterns = [
path('section/<int:section_id>/', views.sections, name='section'),
path('add_section/',views.add_sections,name='add_section')
]
my home.html
{% for subject in subject_list %}
<a href="{% url 'subjects:section' subject.section.id %}">
<div class="card" style="width: 18rem;">
<img src="{{ subject.thumbnail.url }}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">{{subject.id}} {{ subject.name }}</h5>
<p class="card-text">{{ subject.about }}</p>
<hr>
<p class="number" > No of Section:<strong> {{ subject.total_Section }}</strong></p>
<p class="last"> Last update:<strong> {{ subject.update_at }}</strong></p>
</div>
</div>
</a>
{% endfor %}
In your models.py, change your subject in Section class to include the related_name attribute
class Section(models.Model):
subject = models.ForeignKey(Subject, related_name="section" on_delete=models.CASCADE)
# .... the rest of your fields
Then edit your sections in views to be
from django.shortcuts import get_object_or_404
#login_required
def sections(request, subject_id):
subject = get_object_or_404(Subject, pk=subject_id) # retrieve the subject
section_list = subject.section.all() # get the sections related to the subject
print(section_list)
return render (request, 'sections.html',{"section_list" : section_list})
and in your urls.py add this as one of the urlpatterns
path('section/<int:subject_id>/', views.sections, name='section'),
as for your home.html
<ul>
{% for subject in subject_list %}
<li>
<a href="{% url 'section' subject.id %}">
<img class="thumbnail" src="{{ subject.thumbnail.url }}" alt="">
<span><strong> {{ subject.name }} </strong> </span>
</a>
<p>No of Section : {{ subject.total_section }} </p>
</li>
{% endfor %}
</ul>
and your sections.html
<ul>
{% for section in section_list %}
<li> {{ section.title }} </li>
{$ endfor %}
</ul>
Answer fully edited to take into account the modifications you made in your requirements.
1. The model:
Please add a related name to the foreign key to improve readability:
class Section(models.Model):
subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='sections')
2. The subject page :
Where you can show all the sections related to the selected subject.
The view:
You take a second argument to know which subject you should display:
#login_required
def sections(request, subject_id):
try: # First, you get the requested subject (if it exists)
subject = Subject.objects.get(id=subject_id)
except Subject.DoesNotExist: # Use Django shortcuts to display 404 if necessary
raise Http404("There is no subject with this id.")
sections = subject.sections
return render (request, 'sections.html', {'sections': sections})
The template:
You can know access the sections fields by using {{section.field}} in a forloop:
<ul>
{% for section in sections %}
<li class="sub">
<a name='thumb' class="thumb" href="#">
<span><strong> {{ section.title }} </strong> </span>
</a>
<p>Name: {{ section.teacher }} </p>
{{ section.price }}
</li>
{% endfor %}
</ul>
3. The home page :
The view:
The view can stay the same:
#login_required
def home(request):
subject_list = Subject.objects.all()
return render (request, 'home.html', {'subject_list': subject_list })
The template:
You change the url tag by giving the correct url name and the id of the section to display:
<ul>
{% for subject in subject_list %}
<li class="sub">
<a name='thumb' class="thumb" href="{% url 'section' subject.id %}">
<img class="thumbnail" src="{{ subject.thumbnail.url }}" alt="">
<span><strong> {{ subject.name }} </strong> </span>
</a>
<p>No of Section : {{ subject.total_section }} </p>
</li>
{% endfor %}
</ul>
4. The URLs:
You have to add the new argument that we are using for the section:
urlpatterns = [
path('', views.my_login, name='login'),
path('section/<int:subject_id>/', views.sections, name='section'),
]
And this should work.
I looking for a resolving of my issue.
I have custom User model:
class User(AbstractUser):
username = models.CharField(max_length=150, unique=True, blank=False, null=False)
first_name = models.CharField(max_length=150, blank=True)
last_name = models.CharField(max_length=150, blank=True)
password = models.CharField(max_length=150, blank=False)
email = models.EmailField(unique=True, blank=False)
date_create = models.DateTimeField(auto_now_add=True)
address = models.CharField(blank=True, max_length=128)
phone = PhoneNumberField(unique=True)
photo = models.ImageField(upload_to='images/', blank=True)
is_active = models.BooleanField(default=True)
In my app I have e-mail-confirmation. When I create user I hit the "is_active=False". When user activate account then flag "is_active=True". Everything works good.
But when INactive user tries to log in I wanna get message from Django in Login form.
Django has it(source code):
def confirm_login_allowed(self, user):
if not user.is_active:
raise ValidationError(
self.error_messages['inactive'],
code='inactive',
)
But doesn't work for me.
Update: When inactive user tried to log in I get same message as user with incorrect username or password.
I tried to override AuthenticationForm:
User = get_user_model()
class CustomAuthenticationForm(AuthenticationForm):
class Meta: # tried with Meta and without
model = User
def confirm_login_allowed(self, user):
if not user.is_active:
raise forms.ValidationError('There was a problem with your login.')
View:
class CustomLoginView(SuccessMessageMixin, LoginView):
form_class = CustomAuthenticationForm
success_url = reverse_lazy('home')
success_message = "You was logged in successfully"
url:
path('login/', CustomLoginView.as_view(), name='login'),
Update, templates base and login:
<!doctype html>
{% load static %}
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
crossorigin="anonymous"></script>
{% block mystyle %}
{% endblock %}
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark justify-content-center">
<a class="navbar-brand" href="#">Site</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup"
aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-link" href="{% url 'home' %}">Home</a>
{% if user.is_authenticated %}
<a class="nav-link" href="{% url 'cabinet' %}">Cabinet</a>
<a class="nav-link" href="{% url 'logout' %}">LogOut</a>
{% else%}
<a class="nav-link" href="{% url 'signup' %}">SignUp</a>
<a class="nav-link text-right" href="{% url 'login' %}">LogIn</a>
{% endif %}
</div>
</div>
</nav>
{% if messages %}
{% for message in messages %}
<div class="alert alert-success">{{ message }}</div>
{% endfor %}
{% endif %}
{% block content %}
{% endblock %}
</body>
</html>
{% extends "base.html" %}
{% load crispy_forms_tags %}
<!DOCTYPE html>
{% block title %}Log In{% endblock %}
{% block content %}
<h1 class="row justify-content-center p-4">Log In</h1>
<div class="row justify-content-center">
<div class="col-4">
<form autocomplete="off" method="post">
{% csrf_token %}
{{ form|crispy }}
<div class="container p-2">
Forgot your password?
</div>
<div class="container p-2">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
{% endblock %}
Could someone help me? Thanks.
I understood it from point of security. I resolved it just override ModelBackend
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
UserModel = get_user_model()
class CustomModelBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
if username is None or password is None:
return
try:
user = UserModel._default_manager.get_by_natural_key(username)
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a nonexistent user (#20760).
UserModel().set_password(password)
else:
if user.check_password(password): # here (remove 'and self.user_can_authenticate(user):')
return user
Settings
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'accounts.backends.CustomModelBackend',
]
When I submit my form, it doesn't post the form data and just reloads the form.
It was working beforehand but I'm not sure what I've changed that doesn't make it work anymore. Posting the data through the admin still works fine.
The only 'error' message I can see is in the terminal:
which can be seen here
It sends a get request instead of a post request as well. I've also tested it with removing the JS and bootstrap CDNs but the issue is still the same.
My code is below:
Here is my views.py
def create(request):
if request.method == 'POST':
form = EventCreateForm(request.POST, request.FILES)
if form.is_valid():.
instance = form.save(commit=False)
instance.author = request.user
instance.save()
instance.save_m2m()
return redirect('event:home')
else:
form = EventCreateForm()
return render(request, 'event/create.html', {'form': form})
create.html
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
{{ form.media }}
<div class="container-fluid">
<div class="col-md-4">
<div class="page-header">
<p> Create an event!</p>
</div>
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
{{ form | crispy}}
<button type="submit">Submit</button>
<br>
<br>
</form>
</div>
</div>
{% endblock %}
Base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" crossorigin="anonymous" integrity="sha384-xBuQ/xzmlsLoJpyjoggmTEz8OWUFM0/RC5BsqQBDX2v5cMvDHcMakNTNrHIW2I5f"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" crossorigin="anonymous" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" crossorigin="anonymous" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'event/css/custom.css' %}">
<title>Django Project</title>
</br>
<div class="container-fluid" style='font-family:arial'>
<center>
<h2> Welcome to the django website!</h2>
</center>
</div>
{{ form.media }}
</head>
<!-- body of the text -->
<body>
{% if messages %}
{% for messages in messages %}
{{ message }}
{% endfor %}
{% endif %}
{% if user.is_authenticated %}
<nav class="navbar navbar-expand-md navbar-dark bg-dark sticky-top">
<div class="navbar-nav">
<a class="nav item nav-link active" href="{% url 'event:home' %}">Home</a>
<a class="nav item nav-link" href="{% url 'profiles:profile' %}">Profile</a>
<a class="nav item nav-link" href="{% url 'profiles:edit' %}">Edit profile</a>
<a class="nav item nav-link" href="{% url 'event:create' %}">Create</a>
<a class="nav item nav-link" href="{% url 'profiles:logout' %}">Logout</a>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search">
<button class="btn btn-success" type="submit">Search</button>
</div>
{% else %}
Login
Register
{% endif %}
</nav>
{% block content %}
{% endblock %}
</body>
</html>
Models.py
class Event(models.Model):
title = models.CharField(max_length=100)
link = models.TextField()
author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
image = models.ImageField(default='default.jpg', upload_to='event_images')
image_thumbnail = ImageSpecField(source='image',
processors=[ResizeToFill(100, 100)],
format='JPEG',
options={'quality': 60})
start = models.DateField(blank=True, null=True)
start_time = models.TimeField(blank=True, null=True)
end = models.DateField(blank=True, null=True)
end_time = models.TimeField(blank=True, null= True)
description = HTMLField('description')
tags = models.ManyToManyField(Tags)
subject = models.ManyToManyField(Subject)
attendees = models.ManyToManyField(User, related_name = 'attendees', blank=True)
def __str__(self):
return f'{self.title}'
def get_absolute_url(self):
return reverse('event:detail', kwargs={'pk': self.pk})
Thanks everyone in advance,
All help will be greatly appreciated!
You may have deleted your action. Try adding the url back?
<form method="post" action="{% url "event:create" %}" enctype="multipart/form-data">
I had a problem like this too. I solved it by getting rid of a div tag containing a bootstrap class (<div class="form-group>" to be more precise) located around my form.
same problem existed for me also , the silly mistake you have done is the button thing in your create.html file , replace that with input tap with type submit and class btn , button doesn't submit request
Try this :
<input type="submit" class="btn btn-primary" value="Submit">
i know its bit late but this may seem helpful