Django - Add two names - Couldn't print results - django

I'm new to Django.
Trying to build an app that adds two names. Pretty Basic.
Built a page that collects the names but not printing the final result.
Here is my code:
urls.py - inside the app
urlpatterns = [
path('',views.home, name='home'),
path('add',views.addname,name='add')
]
views.py
from django.shortcuts import render
from django.http import HttpResponse
def home(request):
return render(request,'input.html')
def addname(request):
val1 = (request.POST['fname'])
val2 = (request.POST['lname'])
res = 'Hi' + val1 +val2
return render(request, 'resultprint.html',{'resultprint':res})
templates/input.html
{% block content %}
<h1>Hello!</h1>
<form action='addname' method='post'>
{% csrf_token %}
Enter 1st name : <input type='text' name='fname'><br>
Enter 2nd name : <input type='text' name='lname'><br>
<input type='submit'>
</form>
{%endblock%}
templates/resultprint.html
{% block content %}
Result: {{resultprint}}
{%endblock%}
Below are the screenshots:
Couldn't really find where is the mistake happening.
I added the templates and app in the Settings file.

You have to set the same url in your urls.py :
urlpatterns = [
path('', views.home, name='home'),
path('addname', views.addname, name='addname')
]
But you can use directly the name of the url in your html file like that :
{% block content %}
<h1>Hello!</h1>
<form action='{% url 'addname' %}' method='post'>
{% csrf_token %}
Enter 1st name : <input type='text' name='fname'><br>
Enter 2nd name : <input type='text' name='lname'><br>
<input type='submit'>
</form>
{%endblock%}

Related

how to make sure a certain django url path is only checked if all the other paths have been checked

I am building an app where users can access their archives through a simple slug, as follows:
lekha.cc/<archive_slug>
This is exactly as instagram does it. However, whenever I go to any other page, such as
lekha.cc/dashboard
The code for the archive view runs, saying that it has not found an archive with that slug. This is an issue for 2 reasons: we dont want any excess code to run, and if a user chooses to name their archive 'dashboard', the entire website would potentially break down since no one would be able to access their dashboard.
My urls.py folder is as follows:
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('main.urls'), name='index'),
path('onboarding/', account_views.onboarding, name='onboarding'),
path('register/', account_views.register, name='register'),
path('login/', auth_view.LoginView.as_view(authentication_form=LoginForm, template_name='accounts/login.html'), name="login"),
path('logout/', account_views.logout_view, name='logout'),
path('dashboard/', archival_views.dashboard, name='dashboard'),
path('account_settings/', account_views.account_settings, name='account_settings'),
path('<str:slug>/', main_views.archive, name='archive'),
path('item/<str:slug>/', main_views.work, name='work'),
]
Does anyone have any solutions to this issue?
EDIT:
Here is the code for the dashboard view
def dashboard(request):
user = get_current_user()
archive = Archive.objects.get(creator=user)
filesystem = Folder.objects.get(archive=archive)
if request.method == "POST":
if 'addCategory' in request.POST:
category_name = request.POST['folderName']
filesystem = Folder.objects.get(pk=filesystem.pk)
filesystem.add_child(name=category_name)
return render(request, "archival/dashboard.html", {'filesystem': filesystem, "archve": archive, "fileSystemParse": filesystem.get_annotated_list()})
And the archive view
def archive(request, slug):
# retrieve archive with the corresponding slug requested (lekha.cc/dhruva will return the archive with slug='dhruva')
archive = Archive.objects.get(archive_slug=slug)
filesystem = Folder.objects.get(archive=archive)
return render(request, 'archive.html', {'archive': archive, 'filesystem': filesystem})
And the dashboard template:
<html lang="en">
<head>
<style>
</style>
</head>
</html>
{% extends 'navbar.html' %}
{% block content %}
{% load static %}
<div style="height: 200px; width: 100%;"></div>
<p>
archive: {{ archive.archive_slug }}, filesystem: {{ filesystem.name }}
</p>
<div id="folder_view">
{% include 'partials/folder_view.html' %}
</div>
<input type="button" value="addFolder">
<input type="button" value="addFile">
<form action="/dashboard/" method="post">
{% csrf_token %}
<input type="text" name="folderName">
<input type="submit" value="Add Category" name="addCategory">
</form>
<!-- Popups -->
<div id="new_folder_popup" class="dashboard-popup">
<div class="dashboard-popup-content">
<span class="close">×</span>
<!-- <form action="/dashboard/" method="post">
{% csrf_token %}
<input type="text" name="folderName">
<input type="submit" value="Add Category" name="addCategory">
</form> -->
</div>
</div>
The issue was caused by the browser requesting /favicon.ico/ which django was passing through my view. The url.py file should in theory look through all the URLs in order until it finds the right view, so by default django already checks URLs only once.
The real issue is described further here

Django Template Second Form Input Triggering Wrong View

Trying to have two forms on one page and have a user select a create input or load input. Should be pretty straight forward. Doesn't seem to work. Anytime I click select a person and click load, it evaluates the first URL for Create. Can someone please point out what I'm missing? I'm sure it's something simple.
Views:
def Create(request):
print('Create View')
def Load(request):
print('Load View')
URLs:
urlpatterns = [
path('', views.Index, name='index'),
path('person/', views.Create, name='Create'),
path('person/', views.Load, name='Load'),
Template:
{% block body_main %}
<form action={% url 'Create' %} method='POST'>
<h2>Name</h2>
{% csrf_token %}
{{ form1 }}
<input class="btn btn-success" name="form1btn" value="Submit" type="submit"/>
</form>
<br>
<form action={% url 'Load' %} method='POST'>
<h2>Select Existing Name</h2>
{% csrf_token %}
{{ form2 }}
<input class="btn btn-success" name="form2btn" value="Submit" type="submit"/>
<form>
{% endblock %}
Here is the problem (also mentioned in point 3 in Django URL docs:
path('person/', views.Create, name='Create'),
path('person/', views.Load, name='Load'),
Everytime django URL matcher gets here, it will usually hit Create first and return.
Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL, matching against path_info.
So it will always return the Create view.
To solve this problem I suggest creating 3 separate URLs that are more readable:
path('person/new', views.Create, name='Create'),
path('person/load', views.Load, name='Load'),

Django: Adding 2 variables and getting a response on the same page

Any help would be greatly appreciated
index.html
{% extends 'base.html' %}
{% block content %}
<div>
<h1>Welcome Home</h1>
<form action="{% url 'calc:home' %}" method="GET">
<!-- {% csrf_token %} -->
Enter 1st Number : <input type="text" name="num1"><br><br>
Enter 2nd Number : <input type="text" name="num2"><br>
<input type="submit" name="" value="Add"><br><br>
</form>
Result of the game is : {{result}}
</div>
{% endblock %}
views.py
from django.shortcuts import render
from django.http import HttpResponse
def home_view(request):
if request.GET.get('num1'):
val1 = int(request.GET.get("num1"))
val2 = int(request.GET.get("num2"))
res = val1 + val2
return render(request, 'calc/index.html',{'result':res})
urls.py
from django.urls import path
from . import views
app_name = 'calc'
urlpatterns = [
path('', views.home_view, name='home'),
]
i get this error when running the server: UnboundLocalError: local variable 'res' referenced before assignment
I hope this will help. Basically you are using a variable outside of it's scope. you defined res in "if" block but called outside "if" though it was not present in that scope.So you should first assign a default value.
def home_view(request):
res=0
if request.GET.get('num1'):
val1 = int(request.GET.get("num1"))
val2 = int(request.GET.get("num2"))
res = val1 + val2
return render(request, 'calc/index.html',{'result':res})

Reverse for 's_note' with arguments '()' and keyword arguments '{'note_t': 'note_1 opeth', 'user_name': 'opeth'}' not found. 0 pattern(s) tried: []

I have a link to note detail page (s_note) in the user page (username). So as long as I have no entries(notes) in the database for the user the user page renders fine, but as soon as there is a valid note the render fails with the above error and points to ln:6 of user.html.
my urls.py
from django.conf.urls import url
from notes.models import User, Note
from . import views
app_name = 'notes'
urlpatterns = [
url(r'^$', views.index, name='u_index'),
my url
url(r'^signup/$', views.signup, name='u_signup'),
url(r'^(?P<user_id>[\w\-]+)/$', views.user, name='username'),
url(r'^(?P<user_name>[\w\-]+)/(?P<note_t>[\w\-]+)/$', views.note, name='s_note'),
url(r'^(?P<user_name>[\w\-]+)/(?P<note_t>[\w\-]+)/$', views.note, name='s_note')
]
my views
def note(request, user_name, note_t):
nt = Note.objects.get(note_title=note_t)
return render (request, 'notes/detail.html', {'note': nt})
my users.html
<h2>Hi! {{ user.user_n }} Your notes are here.</h2>
{% if allnotes %}
<ul>
{% for note in allnotes %}
<li>{{ note.note_title }}</li>
{% endfor %}
</ul>
{% else %}
<p>You have no notes yet!</p>
{% endif %}
<form method="post" action"">
<table>
{% csrf_token %}
{{ NForm }}
</table>
<input type="submit" value="Create">
</form>
Your url doesn't match for underscores or spaces which your keyword currently contains.
url(r'^(?P<user_name>[\w\-]+)/(?P<note_t>[\w\-]+)/$', views.note, name='s_note'),
should be
url(r'^(?P<user_name>[\w\-]+)/(?P<note_t>[\w\-\_\s]+)/$', views.note, name='s_note'),
although this isn't much of a solution since most spaces would turn into %20's, you should try to remove any spaces from your keywords and update your regex accordingly.
It was a namespacing problem as #Alasdair observed, it sorted with the edit -
'{% url 'notes:s_note'...%}'
in the template.

Django 1.9 - Not displaying user uploaded images

I am trying to display images that have been uploaded by the user, but no matter what I try I am getting the broken link icon. I have searched and searched through the documentation, on SO and elsewhere for a couple of days now to no avail. I am new to Django and currently in development so I'm sure I've made some other rookie mistakes, but right now the only thing I care about is displaying uploaded images in templates.
Here are the relevant snippets of my code:
settings.py
MEDIA_URL = '/media/media_root/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media", "media_root")
urls.py
urlpatterns = [
url(r'^admin/?', admin.site.urls),
url(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^about/?', profiles.views.about, name='about'),
url(r'^properties/single/?', properties.views.single, name='single_mens'),
url(r'^properties/married/?', properties.views.married, name='married'),
url(r'^properties/add/add_photos/?', properties.views.add_photos, name='add_photos'),
url(r'^properties/add/?', properties.views.add_rental, name='add_rental'),
url(r'^', profiles.views.home, name='home'),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
models.py
class RentalPicModel(models.Model):
def __unicode__(self):
return self.image.url
image = models.ImageField(upload_to="pics/originals/", null=True)
rental = models.ForeignKey(RentalModel, on_delete=models.CASCADE)
forms.py
class AddPhotosForm(forms.ModelForm):
class Meta:
model = RentalPicModel
fields = ['image', 'rental']
def clean_image(self):
return self.cleaned_data['image']
def clean_rental(self):
return self.cleaned_data['rental']
views.py
def add_photos(request):
form = AddPhotosForm
current_rental = None
current_photos = []
if request.method == "POST":
form = AddPhotosForm(request.POST, request.FILES)
if request.POST.get('another'):
if form.is_valid():
cleaned_image = form.cleaned_data['image']
cleaned_rental = form.cleaned_data['rental']
current_rental = cleaned_rental
pic = RentalPicModel(image=cleaned_image, rental=cleaned_rental)
pic.save()
current_photos = RentalPicModel.objects.filter(rental=current_rental)
current_photos = [rental.image for rental in current_photos]
for photo in current_photos:
print photo
context = {
'form' : form,
'photos' : current_photos,
}
return render(request, "add_photos.html", context)
Here the output of the print statement (after uploading one photo) is: pics/originals/DSC_1376.jpg and I can see the file is saved to that location.
add_photos.html
<div class="container">
<h1>Upload your photos here.</h1>
<br>
<div class='row'>
<form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %}
{{ form|crispy }}
<div class='col col-xs-3'></div>
<div class='col col-xs-3'>
<input class="btn btn-block btn-info" name="another" type="submit" value="Save and Add Another">
</div>
<div class='col col-xs-3'>
<input class="btn btn-block btn-primary" name="finish" type="submit" value="Save and Finish">
</div>
<div class="col col-xs-3"></div>
</form>
</div>
{% if photos|length > 0 %}
<h2>Uploaded photos:</h2>
{% for photo in photos %}
<div class='row'>
<img src="{{ photo.url }}" alt="">
</div>
{% endfor %}
{% endif %}
</div>
When I inspect the <img> element, I see src="/media/media_root/pics/originals/DSC_1376.jpg" which gives me a url of http://127.0.0.1:8000/media/media_root/pics/originals/DSC_1376.jpg. This seems to be the correct file location to me, but it is still not displaying.
Like I say, everything seems to me to be set up how it is described in the Django documentation and in every other question I've read on SO. What am I missing?
Thank you in advance.
EDIT
Do I need to modify my STATICFILES_DIRS setting at all for uploaded media? Here is what I have right now:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static_files"),
)
which is where I've put all my CSS and javascript files.
You forgot to concatenate the MEDIA_URL and the {{ photo.url }}.
Try:
<img src="{% get_media_prefix %}{{ photo.url }}" alt="">
More about {% get_media_prefix %} HERE in the docs.
My urls were the problem. When it was trying to retrieve the media files, it matched url(r'^', profiles.views.home, name='home') before it matched any of the media urls. A simple $ fixed it:
url(r'^$', profiles.views.home, name='home')