Django: Url can't be resolved - python

I've made an Application containing List of trainers. My Index View Displays these trainer profiles from the database. I intend to implement a sear bar to filter these results. I am not getting what i'm doing wrong. As soon as i mention the url in action of the search for, it displays reverse match error
url's.py :
#/trainer/
url(r'^$', views.IndexView.as_view(),name='index'),
#/trainer/<trainer_id>/
url(r'^(?P<pk>[0-9]+)/$',views.DetailView.as_view(),name='details'),
#/trainer/trainer/add
url(r'trainer/add/$', views.TrainerCreate.as_view(), name='Trainer-add'),
#/trainer/trainer/<album_id>
url(r'trainer/(?P<pk>[0-9]+)/$', views.TrainerUpdate.as_view(), name='Trainer-update'),
#/trainer/trainer/add
url(r'trainer/(?P<pk>[0-9]+)/delete/$', views.TrainerDelete.as_view(), name='Trainer-delete'),
url(r'^search/$', views.search, name='Search'),
views.py
def search(request):
query = request.GET['q']
trainer= Trainer.objects.filter(name__icontains=query)
return render(request,'trainer/index.html', {'trainer': trainer})
search form in my base template
<form class="navbar-form navbar-left" method="get" action="{% url 'trainer:Search' %}">
<div class="form-group">
<input type="text" id="searchBox" class="input-medium search-query" name="q" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
index.py
<table style="width:100%" class="table table-hover">
<tr>
<th>#</th>
<th>Name</th>
<th>Technology</th>
<th>Location</th>
</tr>
{% for trainer in all_trainers %}
<tr>
<td><input type="checkbox" id="trainer{{ forloop.counter }}" name="trainer" value="{{ trainer.id }}"></td>
<td> <a href="{% url 'trainer:details' trainer.id %}"> {{ trainer.name }}</td>
<td>{{ trainer.technology }}</td></a>
<!-- View Details -->
<td>View Details</td>
<td>Download PDF</td>
<!-- Delete Album -->
<td>
<form action="{% url 'trainer:Trainer-delete' trainer.id %}" method="post">
{% csrf_token %}
<input type="hidden" name="trainer_id" value="{{ trainer.id }}" />
<button type="submit" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-trash"></span>
</button>
</form>
</td>
</tr>
{% endfor %}
</table>

You need {% url 'Search' %} and not {% url 'trainer:Search' %}; the : is for when you have namespaced your urls.

change this line
<form class="navbar-form navbar-left" method="get" action="{% url 'trainer:Search' %}">
to
<form class="navbar-form navbar-left" method="get" action="{% url 'Search' %}">

Are you including the urls.py somewhere?
Otherwise you need to add caret ^ at the start of your regex.
url(r'^trainer/search/$', views.search, name='Search'),

Related

django show me "django.db.models.query_utils.DeferredAttribute object at"

I'm trying to get values from an object of my DB on a form in html to edit it but when I call the current "value" from the attribute I get this:
Form
HTML
<form enctype="multipart/form-data" method="post">
{% csrf_token %}
{% for campo in formulario %}
<div class="mb-3">
<label for="" class="form-label">{{ campo.label }}:</label>
{% if campo.field.widget.input_type == 'file' and campo.value %}
<br/>
<img src="{{MEDIA_URL}}/imagenes/{{campo.value}}" width="100"srcset="">
{% endif %}
<input
type="{{ campo.field.widget.input_type}}"
class="form-control"
name="{{ campo.name }}"
id=""
aria-describedby="helpId"
placeholder="{{campo.label}}"
value="{{campo.value | default:''}}"
/>
</div>
<div class="col-12 help-text"> {{campo.errors}}</div>
{% endfor %}
<input name="" id="" class="btn btn-success" type="submit" value="Enviar informacion">
</form>
Views
Models
I found the problem... I instantiate the class instead of the object

Reverse for 'admin-color-product-map-edit' with arguments '('',)' not found. 1 pattern(s) tried: ['admin1/colorProductMap_edit/(?P<id>[0-9]+)$']

I'm a new face to Django so please be considerate to if ever my problem is something stupid. So I have been practicing Django, I've run into problems with tegards to NoReverseMatch, I went through answers in stackoverflow but still I couldn't find where I went wrong. Can you help me a bit guys?
views.py
#login_required(login_url="admin-login")
#user_passes_test(check_role_admin)
def colorProductMap_edit(request, id):
instance = ColorProductMapping.objects.get(color_p_map_id=id)
print(instance.color_id)
form = ColorProductMapForm(instance=instance)
if request.method == 'POST':
form = ColorProductMapForm(request.POST, instance=instance)
if form.is_valid():
form.save()
return redirect('/admin1/colorProductMap')
else:
form = ColorProductMapForm(instance=instance)
return render(request, 'admin1/colorProductMap.html', {'form': form, 'instance': instance})
I properly partnered and connected with the following in my urls.py.
urls.py
path('colorProductMap_edit/<int:id>', views.colorProductMap_edit, name="admin-color-product-map-edit"),
forms.py
class ColorProductMapForm(forms.ModelForm):
class Meta:
model = ColorProductMapping
fields = ['color_id', 'prod_id']
models.py
class ColorProductMapping(models.Model):
color_p_map_id = models.AutoField("Color & Product Map ID", primary_key=True, auto_created=True)
color_id = models.ForeignKey(Color, null=False, on_delete=models.CASCADE, verbose_name="Color ID")
prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")
colorProductMap.html
{% extends 'admin1/layout/master.html' %}
{% block title %}Color Product Map{% endblock %}
{% block main %}
<h1>
<center>Color Product Map</center>
</h1>
<div class="container">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10">
{%if colorProductMap_show%}
<button type="button" class="btn btn-primary mt-2" data-toggle="modal" data-target="#modal-primary">Add
Color Product Mapping
</button>
<div class="modal fade" id="modal-primary">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Color Product Mapping</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
</div>
<div class="modal-body mt-2">
<form action="{% url 'admin-color-product-map'%}" method="POST"
enctype="multipart/form-data">
{% csrf_token %}
<table border="1" class="table table-bordered border border-info">
<tr>
<th>
{{form.color_id.label_tag}}
</th>
<td>{{form.color_id}}</td>
</tr>
<tr>
<th>
{{form.prod_id.label_tag}}
</th>
<td>
{{form.prod_id}}
</td>
</tr>
</table>
<div class="modal-footer justify-content-right">
<input type="Submit" name="Submit" value="Submit" class="btn btn-outline-success">
<button type="button" class="btn btn-outline-danger" data-dismiss="modal">Close
</button>
</div>
</form>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<div class="container-fluid ">
<div class="row">
<div class="card mt-2 border border-secondary">
<div class="card-header">
<h3 class="card-title ">Color Product Map Table</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<table class="table table-bordered border border-info">
<thead>
<tr>
<th>Color Product Mapping Id</th>
<th>Product ID</th>
<th>Color ID</th>
<th>Action</th>
</tr>
</thead>
<tbody class="justify-content-center">
{% for x in colorProductMap_show %}
<tr>
<td>{{x.color_p_map_id}}</td>
<td>{{x.prod_id}}</td>
<td>{{x.color_id}}</td>
<td><a href="{% url 'admin-color-product-map-edit' x.color_p_map_id %}"
class="btn btn-outline-primary mt-2"><i
class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
<a href="{% url 'admin-color-product-map-delete' x.color_p_map_id %}"
class="btn btn-outline-danger mt-2"><i
class="fa fa-trash" aria-hidden="true"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- /.card-body -->
<div class="card-footer clearfix ">
<ul class="pagination pagination-sm m-0 justify-content-center">
{% if colorProductMap_show.has_previous %}
<li class="page-item"><a class="page-link"
href="?page={{colorProductMap_show.previous_page_number}}">
Previous </a>
</li>
{% endif%}
{% for x in colorProductMap_show.paginator.page_range %}
{% if colorProductMap_show.number == x %}
<li class="page-item active"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% else%}
<li class="page-item"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% endif %}
{% endfor %}
{% if colorProductMap_show.has_next %}
<li class="page-item"><a class="page-link"
href="?page={{colorProductMap_show.next_page_number}}">
Next </a>
</li>
{% endif %}
</ul>
</div>
</div>
<!-- /.card -->
</div>
</div>
{%endif%}
{% if instance %}
<form action="{% url 'admin-color-product-map-edit' x.color_p_map_id %}" method="POST"
enctype="multipart/form-data">
{% csrf_token %}
<table border="1" class="table table-bordered border border-info">
<tr>
<th>
{{form.color_id.label_tag}}
</th>
<td>{{form.color_id}}</td>
</tr>
<tr>
<th>
{{form.prod_id.label_tag}}
</th>
<td>
{{form.prod_id}}
</td>
</tr>
</table>
<input type="Submit" name="Submit" value="Submit" class="btn btn-success w-50"><br>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-outline-light" data-dismiss="modal">Close
</button>
</div>
</form>
{% endif %}
</div>
</div>
</div>
{% endblock %}
What am I doing wrong? I think I have followed every advice I could find, but yeah it still gives me the error. Any help is appreciated. Thank you very much!
You write your form tag as:
<form action="{% url 'admin-color-product-map-edit' x.color_p_map_id %}" method="POST"
enctype="multipart/form-data">
After observing your template and view it appears that you are using the same template for multiple views and this is causing confusion. As I note in the comment there is no x in the context for this view (In the other one you loop over a variable which doesn't exist in this view to get this). After looking a bit more one notices that by this {% url 'admin-color-product-map-edit' x.color_p_map_id %} you want to point to the current url itself. If a forms action is to the same url the best thing to do is forego the action attribute completely (If there is no action attribute the request would be to the same url as the page user is in):
<form method="POST" enctype="multipart/form-data">
Thanks all to guide me, I have found my mistake.
In the html template, as shown below
<form action="{% url 'admin-color-product-map-edit' x.color_p_map_id %}" method="POST"
enctype="multipart/form-data">
Here I am using x.color_p_map_id where x is not any iterable object so the error I was getting.
Now I have made a change and used instance instead of x in above url and now its working fine.
<form action="{% url 'admin-color-product-map-edit' instance.color_p_map_id %}" method="POST"
enctype="multipart/form-data">

Django not redirecting to next page

I don't know what's happening with my code, once a user that is not authenticated tries to access a page and it redirects to the login page, I can see the next parameter in the browser but after the user logins, it takes the user to the default LOGIN_REDIRECT_URL and not the next page. Also on the template next returns none, so seems the template is not getting thee next value, but in the url it shows the /?next=, thanks in advance.
urls.py
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.HomeView.as_view(),name="index"),
path('accounts/login/', auth_views.LoginView.as_view(), name='login'),
path('accounts/logout/', auth_views.LogoutView.as_view(next_page='/'), name='logout'),
path('accounts/profile/', views.ProfileView.as_view(), name='profile'),
]
registration/login.html
{% extends 'app/base.html' %}
{% block link %} id="active" {%endblock%}
{% block content %}
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6">
<div class="jumbotron" id="font">
{% if next %}
{% if user.is_authenticated %}
<h2 class="customtext" align="center">Your account doesn't have access to this page. To proceed,
please login with an account that has access.</h2>
{% else %}
<h2 class="customtext" align="center">Please login.</h2>
{% endif %}
{% else %}
<h2 class="customtext" align="center">Enter your login details.</h2>
{% endif %}
<form action="{% url 'login' %}" method="POST">
{%csrf_token%}
<div class="form-group">
<input type="text" name="username" placeholder="username" class="form-control">
</div>
<div class="form-group">
<input type="password" name="password" placeholder="password" class="form-control">
</div>
<!-- <div align="center"> -->
{% if form.errors %}
<!-- <p style="color: red; font-style: italic;">Your username or email is does not match.</p> -->
{{form.errors}}
{% endif %}
<!-- </div> -->
<div class="loginbtndiv" align="center">
<input type="submit" class="btn btn-warning btn-lg loginbtn" value="LOGIN">
</div>
<input type="hidden" name="next" value="{{ next }}">
</form>
</div>
</div>
<div>
</div>
</div>
{% endblock %}

How to customize login in django

I have a registration page for teachers having fields like email, mobile number, password etc, the table is named as Teacher.
I want to login page too for the same.
What I am doing is:
Added following in url page:
url(r'^login/$', auth_views.login, {'template_name': 'login.html'},name='login'),
Added following in settings.py:
AUTH_USER_MODEL = 'myapp.Teacher'
Added login.html:
{% extends "base.html" %}
{% load widget_tweaks %}
{% block body_block %}
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
{% if next %}
{% if user.is_authenticated %}
<p>Your account doesn't have access to this page. To proceed,
please login with an account that has access.</p>
{% else %}
<p>Please login to see this page.</p>
{% endif %}
{% endif %}
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Please Sign In</h3>
</div>
<div class="panel-body">
<form method="post" action="{% url 'login' %}">
{% csrf_token %}
<p class="bs-component">
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
</p>
<p class="bs-component">
<center>
<input class="btn btn-success btn-sm" type="submit" value="login" />
</center>
</p>
<input type="hidden" name="next" value="{{ next }}" />
</form>
</div>
</div>
</div>
</div>
</div>
{%endblock body_block%}
Now the login page doesn't work, giving me error:
AttributeError: type object 'Teacher' has no attribute 'REQUIRED_FIELDS'
How can I implement custom login page in django?

Url not changing , just render the template after login

The URL is not changing and data is not fetching after user login.
After Login the url not changed(i expected to change to 127.0.0.1:8000/employer/home)
#login_required
def home(request):
emp=Employer.objects.get(user=request.user)
jb=Job.objects.filter(employer=emp).order_by("-postdate")
return render(request,'employer/home.html',{'jobs':jb})#,{'employer':emp})
employer/home.html
<table class="table table-hover table-bordered">
<tr><th>Job ID</th><th>Title</th><th>Posted on</th></tr>
{% for job in jobs %}
<tr>
<td>{{ job.pk }}</td>
<td>{{ job.title }}</td>
<td>{{ job.postdate }}</td>
</tr>
{% endfor %}
</table>
login.html
<form class="form-signin" action="" method="post">{% csrf_token %}
<h4 class="form-signin-heading">Sign in to my account...</h4>
{% if errors %}
<p class="text-error">Sorry, that's not a valid username or password</p>
{% endif %}
<input type="text" id="username" class="input-block-level" name="username" placeholder="UserID">
<input type="password" id="password" class="input-block-level" name="password" placeholder="Password">
<p style="text-align:right;">Forgot your password?</p>
<button class="btn btn-large btn-success" type="submit" value="login">Sign in</button>
</form>
You need to tell it where to go after login using the next url parameter:
<form class="form-signin" action="{% url django.contrib.auth.views.login %}?next=employer/home/" method="post">
or set the LOGIN_REDIRECT_URL in settings:
The URL where requests are redirected after login when the contrib.auth.login view gets no next parameter.

Categories