I'm new to Django. I'm having an issue where I can't save my model in the views.py. The concept is to have an input field where a user can type in a name, then using request.POST.get('attribute_name') I can save my model, but it's not working. When I print a list of all the objects in that model there's nothing there, even though I don't get an error message during all of this.
template:
<form id="save_form" method="post" action="{% url 'project_view.views.projectz_save' %}">
{% csrf_token %}
<table>
<tr>
<td>Project Name</td>
<td><input name="projectz_name"/></td>
</tr>
</table>
<input type="submit" value="Save" />
</form>
views.py:
def projectz_save(request):
try:
p = Project(name=request.POST.get('projectz_name'))
p.save()
return redirect('http://www.google.com/')
except:
return redirect('http://www.google.com/')
app urls:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^$', views.register, name='register'),
url(r'^$', views.projectz_save, name='project_save'),
)
site urls:
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^project_view/', include('project_view.urls')),
I even put in some silly redirect code to google.com just to see if the views.py was even executing, but it's not working, though like I said there are no error messages, the page just refreshes. I'm sure I'm doing wrong that's easy to fix, but I'm a noobie. :D
Ok I think maybe I spotted the problem. The view is not executing because you have defined three urls with the exact regex in your project urls.py:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^$', views.register, name='register'),
url(r'^$', views.projectz_save, name='project_save'),
)
Django match it's urls by iterating over the patterns in the way they appeared so in that file all urls will match index. That's probably the reason why the page appears to be refreshing. Try to modify this a little:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^register$', views.register, name='register'),
url(r'^save$', views.projectz_save, name='project_save'),
)
This way you can execute the projectz_save method in the views.py if the action of the form matches the url regex.
Hope this helps!
Related
Template :
<a class="btn btn-primary" href="{% url 'edit' %}">Edit</a>ù
views.py:
def edit(request):
return render(request, "edit.html")
urls.py:
urlpatterns = [
path("", views.index, name="index"),
path("wiki/create", views.create, name="create"),
path("wiki/edit", views.edit, name="edit"),
path("wiki/<str:name>", views.entry, name="entry"),
path("search", views.search, name="search"),
path("save", views.save, name="save"),
path("random", views.random, name="random"),
]
I would like simply to switch from an HTML page on another, but the function gives me this error:
TemplateDoesNotExist at /wiki/edit
edit.html
But the template exist, I created it. I tryed a lot of changes but all of them gives me error. Thank you.
The Application name needs to be referenced in the template name.
Like so:
return render(request, "encyclopedia/edit.html")
I am getting the below error when I am trying to load the home page:
Reverse for 'display_data' not found. 'display_data' is not a valid view function or pattern name
My views.py file is as follows:
def home(request):
#query_results = QRC_DB.objects.all()
return render(request, 'display_data.html')
def display_data(request,component):
#query_results = QRC_DB.objects.all()
return HttpResponse("You're looking at the component %s." % component)
My urls.py file under the app is as follows:
from django.urls import path
from fusioncharts import views
urlpatterns = [
path('home/', views.home, name=''),
]
The urls.py file under the project is as follows:
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('fusioncharts.urls'))
]
And my html file (display_data) code is as follows :
{% block content %}
<h3>Display the test results</h3>
<div id="container" style="width: 75%;">
<canvas id="display-data"></canvas>
<li>SQL</li>
</div>
{% endblock %}
Can anyone please help me to find out the mistake ?
Thanks.
Your urls.py file doesn't contain any url for display_data.
When you're trying to click the link rendered in the HTML tag, namely,
<li>SQL</li>
it tries to resolve the URL display_data.
First, it checks the root urls.py file. Among the following:
path('admin/', admin.site.urls),
path('', include('fusioncharts.urls'))
it matches the second one. Then it loads the fusioncharts.urls but the fusioncharts.urls doesn't contain any URL for display_data. That's why you are getting the error.
The urls.py file should be like this:
from django.urls import path
from fusioncharts import views
urlpatterns = [
path('home/', views.home, name=''),
path('display_data/<str:arg>', views.display_data, name='display_data'),
]
# There is a change in urls.py and in your template 'display_data.html'
urls.py
urlpatterns = [
path('home/', views.home, name=''),
path('display_data/<str:component>', views.display_data, name='display_data'),
]
display_data.html
{% block content %}
<h3>Display the test results</h3>
<div id="container" style="width: 75%;">
<canvas id="display-data"></canvas>
<li>SQL</li>
</div>
{% endblock %}
I am trying my hand at learning Django and trying out the step-by-step tutorial at https://docs.djangoproject.com/en/2.0/intro/tutorial03/.
I have completed the app (well, till the Part 7) and is working as expected (and has been explained in the tutorial).
The only problem (so far) I am facing is when I am trying to navigate from the "Admin" page to the linked page "VIEW SITE" when I am being presented with "Page not found (404)" error. An image is being attached to make the situation clearer.
The link is pointing to "http://127.0.0.1:8000/" whereas it should be pointing to "http://127.0.0.1:8000/polls/". When I add the missing part of the path (manually) in the address bar the correct page (as expected) is presented.
I have tried to search on this as well as many other forums but could not get the right solution.
I am using Django 2.0.6 and Python 3.6.4 on mac sierra.
Shall be grateful for a lead on this.
Thanks
mysite/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
mysite/polls/urls.py
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
polls/template/polls/index.html
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li>{{ question.question_text }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
Error on navigation at VIEW SITE
you should open http://127.0.0.1:8000/polls/
not
http://127.0.0.1:8000/.
If you wanna use http://127.0.0.1:8000/ then your path should be
from django.urls import include, path
urlpatterns = [
path('', include('polls.urls')),
path('admin/', admin.site.urls),
]
It should be like this:
path('', include('polls.urls')),
not like this:
path('polls/', include('polls.urls'))
Because it should be the root url of your website
Here is what I have done (may be not the most elegant solution but works just fine).
I have modified the "mysite/urls.py" file as shown:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('', include('polls.urls')),
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
This way I am able to access the "polls" page from both "View Site" link on the Django Admin page (url: "127.0.0.1:8000") as well as from link residing elsewhere (url: "127.0.0.1:8000/polls/").
Thanks for all the help.
PS. Visiting https://docs.djangoproject.com/en/2.0/topics/http/urls/ may be of help to learners like me.
I am following a tutorial where they do something like this:
Leave a comment
They use slug. I have not been doing that, but have been referencing an ID. The parts of my code which I think are important to this are:
films/urls.py:
from django.conf.urls import url
from django.urls import path
from . import views
app_name = 'films'
urlpatterns = [
path('', views.index, name='index'),
url(r'^films/<int:film_id>/comment/', views.add_comment, name='add_comment'),
path('films/<int:film_id>/', views.detail, name='detail'),
]
films/views.py
def add_comment(request, film_id):
film = get_object_or_404(Film, pk=film_id)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit = False)
comment.post = post
comment.save()
return redirect('film:detail',film)
else:
form = CommentForm()
template = 'films/add_comment.html'
context = {'form':form}
return render (request,template,context)
mysite/urls.py:
urlpatterns = [
url(r'^accounts/',include('accounts.urls')),
url(r'^', include('films.urls')),
url(r'^admin/', admin.site.urls),
]
add_comment.html:
{% extends 'base_layout.html' %}
{% block content %}
<div class="create-comment">
<h2>Add Comment</h2>
</div>
{% endblock %}
If I click the link I made which is: Leave a comment
I get this:
And if I manually alter the url to
http://127.0.0.1:8000/films/2/comment/
I get this:
But it looks like url 3 in that list matches what I typed?
you are so close. Just some minor mistakes I believe:
(Final Working Edit)
films/urls.py
urlpatterns = [
path('', views.index, name='index'),
path('<int:film_id>/comment', views.add_comment, name='add_comment'),
path('<int:film_id>', views.detail, name='detail'),
]
mysite/urls.py
urlpatterns = [
url('films/', include('films.urls')),
url('accounts/',include('accounts.urls')),
url('admin/', admin.site.urls),
]
(Working out)
films/urls.py:
app_name = 'films'
urlpatterns = [
url(r'^films/(?P<film_id>\d+)/comment/', views.add_comment, name='add_comment'),
]
Notice: (?P<film_id>\d+) that's how you capture the correct identifier
This is incorrect:
Leave a comment
It should be:
Leave a comment
Notice there is no gap in {%
and we now use the identifier we defined in urls.py above.
Your def add_comment(request, film_id): has me a tad confused, however give my suggestions a shot. Then comment with any issues that occurred and we'll solve this!
EDIT: Ok next mini-errors that might be holding you back
urlpatterns = [
path(r'^$', views.index, name='index'),
path(r'^films/<int:film_id>/comment/$', views.add_comment, name='add_comment'),
path(r'^films/<int:film_id>/$', views.detail, name='detail'),
]
Make all the first arg strings regex strings i.e. 'foo' -> r'foo'
According to the v2 release notes, you need to use path( ) to use your cool <int:film_id> syntax. url() will not do it sadly ☹️
End your regexes with a '$', it means end of string. Prevents matching films/2/comment to films/2/
So I am trying to display an image on the web page, i save the image path in the database as media/imagename and in my html page i am doing this :
{% for stuff in profile %}
<div class="alert alert-success" role="alert"> {{ stuff.text }} </div>
<img scr='/Users/Username/PycharmProjects/social-django-1.9/mysite/media/media/{{ stuff.thumbnail }}' width="200">
{% endfor %}
And in my settings.py i do this:
MEDIA_ROOT = os.path.join(PROJECT_ROOT, '/Users/Username/PycharmProjects/social-django-1.9/mysite/media/media')
But the image doesn't display. What am i doing wrong here? Thanks!
Edit:
#urls.py
from django.conf.urls import patterns, url
from django.conf import settings
from social import views
urlpatterns = [
# main page
url(r'^$', views.index, name='index'),
# signup page
url(r'^signup/$', views.signup, name='signup'),
# register new user
url(r'^register/$', views.register, name='register'),
# login page
url(r'^login/$', views.login, name='login'),
# user doesnt exist webpage
url(r'^user-doesnt-exist/$', views.login, name='user-doesnt-exist'),
#page to show that the password is incorrect
url(r'^wrongpass/$', views.login, name='wrongpass'),
#webpage to show an error when a user tries to input nothing in the fields when signing up
url(r'^novalues/$', views.register, name='novalues'),
# logout page
url(r'^logout/$', views.logout, name='logout'),
# members page
url(r'^members/$', views.members, name='members'),
#invites page
url(r'^invites/$', views.invites, name='invites'),
# friends page
url(r'^friends/$', views.friends, name='friends'),
# user profile edit page
url(r'^profile/$', views.profile, name='profile'),
# messages page
url(r'^messages/$', views.messages, name='messages'),
# Ajax: check if user exists
url(r'^checkuser/$', views.checkuser, name='checkuser'),
#commiting again
]
if settings.DEBUG:
urlpatterns += patterns(''(r'^media/(P<path>.*)$','django.views.static.serve',
{'document_root':settings.MEDIA_ROOT,'show_indexes':True})),
Try setting your MEDIA_ROOT to:
MEDIA_ROOT = os.path.join(BASE_DIR, 'social/static/social/media')
MEDIA_URL = '/media/'
And in your project urls.py file add:
from django.conf import settings
from django.conf.urls import patterns
if settings.DEBUG:
urlpatterns += patterns('', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}))
Then, in your template call the image like:
{% if stuff.thumbnail %}
<img src="{{ object.thumbnail.url }}">
{% endif %}
And in models.py:
image = models.ImageField(upload_to='images/')
Here's some great documentation on serving media files, including how to serve them during development.