Basically, what happens here, the list user_data doesn't get passed to the template, I can't figure out why. Does anyone have any ideas please? When I use the search bar I just get the else condition from the template, and it never shows any variable. I also tried to create different variables to pass to the template, but none of them got passed for some reason.
This is in my views.py:
#login_required(login_url='login_user')
def profiles(request):
context = {}
if request.method == "POST":
data = request.POST.get('search_input')
if len(data) > 0:
username_result = NewUser.objects.filter(username__icontains=data).distinct()
email_result = NewUser.objects.filter(email__icontains=data).distinct()
user_data = []
for account in username_result:
user_data.append((account, False))
context['usernames'] = user_data
return render(request, "profiles/search_user.html", context)
else:
return render(request, "profiles/profiles.html")
return render(request, "profiles/profiles.html")
Then my template looks like this:
{% extends 'profiles/base.html' %}
{% block title %}One For All{% endblock %}
{% load static %}
<!-- importing css file -->
{% block style %}<link rel="stylesheet" type="text/css" href="{% static 'css/search_user.css'
%}">{% endblock %}
{% block content %}
<!-- navigation bar -->
<div class="navBar">
<!-- logo and logo spacers -->
<div class="logo_spacer"></div>
<div class="logo"></div>
<!-- Sign Up Button -->
<a class="homeBtn" href="{% url 'profiles' %}">Home</a>
{% if is_self %}
<a class="settingsBtn" href="{% url 'settings' user=user.username %}">Profile Settings</a>
{% else %}
<a class="settingsBtn" href="{% url 'user_profile' username=user.username %}">My Profile</a>
{% endif %}
<p>Top Menu</p>
</div>
<!-- main body of login page -->
<div class="main">
{% if user_data %}
<p>We find users</p>
{% for account in user_data %}
<div>
<a class="profile-link" href="{% url 'user_profile' username=user.0.username %}">
<!--<img class="img-fluid profile-image" src="{{account.0.avatar.url}}" alt="">--></a>
</div>
{% endfor %}
{% else %}
<p>This is when user_data doesn't exist or doesn't get passed to template: {{ user_data }} </p>
{{ user_data }}
{% endif %}
</div>
<div class="bottom">
<p>Bottom</p>
</div>
{% endblock %}
{% block js_block %}
{% endblock %}
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('logout/', views.logoutUser, name='logout'),
path('post/', views.post, name='post'),
path('', views.profiles, name='profiles'),
path('search_user/', views.profiles, name='profiles'),
path('UserProfile/<str:username>/', views.user_profile, name='user_profile'),
path('Settings/<str:user>/', views.settings, name='settings'),
]
In the view you set:
context['usernames'] = user_data
But in the template you reference:
{% if user_data %}
<p>We find users</p>
{% for account in user_data %}
user_data doesn't exist in the context - you need to reference usernames instead, or change the view to call it user_data
Related
I'm trying to make a simple portofolio app using django but I'm keep getting this error.
I looked everywhere on google but nothing helps.
I'm basically trying to link the Read more button(in project_index.html) to the project_details.html page using {% url 'project_detail' pk=project.pk %}
Views.py:
from django.shortcuts import render
from projects.models import Project
# Create your views here.
def project_index(request):
projects = Project.objects.all()
context = {"projects": projects}
return render(request, "project_index.html", context)
def project_detail(request, pk):
project = Project.objects.get(pk=pk)
context = {"project": project}
return render(request, "project_detail.html", context)
Urls.py:
from django.urls import path
from projects import views
urlpatterns = [
path("", views.project_index, name="project_index"),
path("/int:pk/", views.project_detail, name="project_detail"),
]
models.py:
from django.db import models
# Create your models here.
class Project(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
technology = models.CharField(max_length=20)
image = models.FilePathField(path="/img")
project_index.html:
{% extends "base.html" %}
{% load static %}
{% block page_content %}
<h1>Projects</h1>
<div class="row">
{% for project in projects %}
<div class="col-md-4">
<div class="card mb-2">
<img class="card-img-top" src="{% static project.image %}">
<div class="card-body">
<h5 class="card-title">{{ project.title }}</h5>
<p class="card-text">{{ project.description }}</p>
**<a href="{% url 'project_detail' pk=project.pk %}"**
class="btn btn-primary">Read More</a>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
project_detail.html:
{% extends "base.html" %}
{% load static %}
{% block page_content %}
<h1>{{ project.title }}</h1>
<div class="row">
<div class="col-md-8">
<img src="{% static project.image %}" alt="" width="100%">
</div>
<div class="col-md-4">
<h5>About the project:</h5>
<p>{{ project.description }}</p>
<br>
<h5>Technology used:</h5>
<p>{{ project.technology }}</p>
</div>
</div>
{% endblock %}
Thanks in advance.
correct your url
path("<int:pk>/", views.project_detail, name="project_detail")
I have a page that contains a form. It has 3 buttons, Enter/Leave and Options. My enter and leave button operate just fine, but the options button is supposed to redirect to a list of entries and currently it does not do anything, not even produce errors, which I can't figure out why it's happening.
I feel like I'm missing something very slight, I tried moving the Manager Options button into the form tags but this did not work either, so I'm not sure I'm missing an important piece as I am fairly new to Python/Django.
views.py
class EnterExitArea(CreateView):
model = EmployeeWorkAreaLog
template_name = "operations/enter_exit_area.html"
form_class = WarehouseForm
def form_valid(self, form):
emp_num = form.cleaned_data['adp_number']
if 'enter_area' in self.request.POST:
form.save()
return HttpResponseRedirect(self.request.path_info)
elif 'leave_area' in self.request.POST:
form.save()
EmployeeWorkAreaLog.objects.filter(adp_number=emp_num).update(time_out=datetime.now())
return HttpResponseRedirect(self.request.path_info)
elif 'manager_options' in self.request.POST:
return redirect('enter_exit_area_manager_options_list')
class EnterExitAreaManagerOptionsList(ListView):
filter_form_class = EnterExitAreaManagerOptionsFilterForm
default_sort = "name"
template = "operations/list.html"
def get_initial_queryset(self):
return EmployeeWorkAreaLog.active.all()
def set_columns(self):
self.add_column(name='Employee #', field='adp_number')
self.add_column(name='Work Area', field='work_area')
self.add_column(name='Station', field='station_number')
urls.py
urlpatterns = [
url(r'enter-exit-area/$', EnterExitArea.as_view(), name='enter_exit_area'),
url(r'enter-exit-area-manager-options-list/$', EnterExitAreaManagerOptionsList.as_view(), name='enter_exit_area_manager_options_list'),
]
enter_exit_area.html
{% extends "base.html" %}
{% block main %}
<form id="warehouseForm" action="" method="POST" novalidate >
{% csrf_token %}
<div>
<div>
{{ form.adp_number.help_text }}
{{ form.adp_number }}
</div>
<div>
{{ form.work_area.help_text }}
{{ form.work_area }}
</div>
<div>
{{ form.station_number.help_text }}
{{ form.station_number }}
</div>
</div>
<div>
<div>
<button type="submit" name="enter_area" value="Enter">Enter Area</button>
<button type="submit" name="leave_area" value="Leave">Leave Area</button>
</div>
</div>
</form>
{% endblock main %}
{% block panel_footer %}
<div class="text-center">
<button type="submit" name="manager_options" value="Options">
Manager Options
</button>
</div>
{% endblock panel_footer %}
list.html
{% extends "base.html" %}
{% load core_tags staticfiles %}
{% block head %}
<script src="{% static "js/operations/enter_exit_area_manager_options_list.js" %}"></script>
{% endblock head %}
{% block main %}
{% include 'core/list_view/list.html' %}
{% endblock main %}
You option buttons is really link to another page so you should add it to your template like this. Replacing button-styles class with however you want your button to look.
<a href="{% url 'enter_exit_area_manager_options_list' %}" class="button-styles">
Manager Options
</a>
When I click on my delete project link it takes me to my delete page with a button to click which should delete the model data of the project and then take me to the profile page. However when I click the delete button, the page just refreshes and no data gets deleted?!
What am I doing wrong here? Any help would be much appreciated :-)
Views
class DeleteProject(UpdateView):
model = UserProject
template_name = 'howdidu/delete_project.html'
def get_object(self, queryset=None):
obj = super(DeleteProject, self).get_object()
if not obj.user == self.request.user:
raise Http404
return obj
def get_success_url(self):
project_username = self.request.user.username
#project_slug = self.object.slug
return reverse('user_profile', kwargs={'username':project_username})
delete_project.html template
{% extends 'howdidu/base.html' %}
{% load staticfiles %}
{% block title %}Delete project{% endblock %}
{% block body_block %}
<h1>Delete project</h1>
<form method="post">{% csrf_token %}
<p>Are you sure you want to delete "{{ userproject.title }}"?</p>
<input type="submit" value="Confirm" />
</form>
{% endblock %}
Urls
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^register_profile/$', views.register_profile, name='register_profile'),
url(r'^update_profile/$', views.update_profile, name='update_profile'),
url(r'^create_project/$', login_required(views.CreateProject.as_view()), name='create_project'),
url(r'^(?P<username>\w+)/(?P<slug>[-\w]+)/update_project/$', login_required(views.UpdateProject.as_view()), name='update_project'),
url(r'^(?P<username>\w+)/(?P<slug>[-\w]+)/delete_project/$', login_required(views.DeleteProject.as_view()), name='delete_project'),
url(r'^(?P<username>\w+)/$', views.profile_page, name='user_profile'),
url(r'^(?P<username>\w+)/(?P<slug>[-\w]+)/$', views.project_page, name='user_project'),
)
Project.html template which has the delete link on
{% extends 'howdidu/base.html' %}
{% load staticfiles %}
{% block title %}Project{% endblock %}
{% block body_block %}
{% if project %}
<h1>{{ project.title }}</h1>
<img src="{{ project.project_picture.url }}" width = "300" height = "300" />
<h3>{{ project.project_overview }}</h3>
{% if user.is_authenticated %}
{% if project_user.username == user.username %}
<p>Edit project</p>
<p>Delete project</p>
{% endif %}
{% endif %}
{% else %}
The specified project {{ project.title }} does not exist!
{% endif %}
{% endblock %}
You must use DeleteView not UpdateView.
See here.
I'm trying to incorporate an template tag/inclusion tag into my sidebar for the site. The main section of the page updates properly when I put:
{% if user.is_authenticated %}
<h1> Hello {{ user.username }}
{% else %}
<h1> Hello </h1>
{% endif %}
When I try to use the same principle in my template tag/sidebar, it seems to ignore user.is_authenticated and will always show 'login' and 'register', when it should be just showing 'logout'.
The body of the html (main index page):
{% load Kappa_extras %}
<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-2" id="side_section">
{% block sidebar %}
{% get_game_list %}
{% endblock %}
</div>
<!--Main section-->
<div class="col-sm-10" id="main_section">
{% block body %}
{% endblock %}
</div>
</div>
</div>
The get_game_list function from 'Kappa_extras':
from django import template
from Kappa.models import Game, Game_Page
from django.contrib.auth.models import User
register = template.Library()
#register.inclusion_tag('Kappa/sidebar.html')
def get_game_list():
return {'game_list': Game.objects.all()}
and the 'Kappa/sidebar.html':
<div id="side_default_list">
<ul class="nav">
<li>Kappa</li>
{% if user.is_authenticated %}
<li>Log Out</li>
{% else %}
<li>Log In</li>
<li>Register</li>
{% endif %}
</div>
I checked a few older inquires though none of them are working properly. I tried putting request into def get_game_list(request): but it just said did not receive value for the argument. How do I get the sidebar to update properly when user.is_authenticated?
You need to pass the user to your inclusion tag.
#register.inclusion_tag('Kappa/sidebar.html')
def get_game_list(user):
return {'game_list': Game.objects.all(), 'user': user}
Then in your template, call the tag with
{% get_game_list user %}
Alternatively, you can set takes_context=True in your inclusion tag, so that you can access the user from the template context.
#register.inclusion_tag('Kappa/sidebar.html', takes_context=True)
def get_game_list(context):
return {'game_list': Game.objects.all(), 'user': context['user']}
In this case, you don't need to pass the user to the template tag any more.
{% get_game_list %}
See the docs for more information and other examples.
I'm doing a function to upload a file with a example that I found here on Stack Overflow, everything works fine, the problem is that when I try to access the document by a URL, the click sends me to the app url not the photo url, for example I'm trying to access to this
http://localhost:8000/media/documents/2013/10/01/Desert.jpg
and it should be the image URL
documents/2013/10/01/Desert.jpg
view.py
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
print form
if form.is_valid():
newdoc = Document(docfile=request.FILES['docfile'],credencial_miembro=request.POST['credencial_miembro'])
print newdoc
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('expmedico.views.list'))
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
# Render list page with the documents and the form
return render_to_response(
'upload.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
)
forms.py
class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Select a file',
help_text='max. 42 megabytes'
)
credencial_miembro=forms.CharField(max_length=20)
model.py
class Document(models.Model):
docfile = models.FileField(upload_to='documents')
credencial_miembro= models.CharField(max_length=20,null=False, blank=False)
ulr
url(r'^list/$', 'expmedico.views.list',name='list'),
Setting.py
MEDIA_ROOT = os.path.join(RUTA_PROYECTO, 'media')
MEDIA_URL = '/media/'
template.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Minimal Django File Upload Example</title>
</head>
<body>
<!-- List of uploaded documents -->
{% if documents %}
<ul>
{% for document in documents %}
<li>{{ document.docfile.name }}</li>
{% endfor %}
</ul>
{% else %}
<p>No documents.</p>
{% endif %}
<!-- Upload form. Note enctype attribute! -->
<form action="{% url list %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<table style="width:150%;">
<div style="text-align:center; font-style: oblique; color: red" >
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}><b>{{ message }}</b></li>
{% endfor %}
</ul>
{% endif %}
</div>
<tr>
<td><label>Fecha:</label></td>
<td>
<output><b>{% now "D d M Y" %}</b></output>
</td>
<td>{{ form.credencial_miembro.errors }}<label>Credencial:</label></td>
<td>{{ form.credencial_miembro }} </td>
</tr>
</table>
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
</body>
</html>
You are accessing a model not an image. Also, this might help:
https://docs.djangoproject.com/en/1.2/howto/static-files/
Please take a look there as i don't see this added to the urls.py you pasted.