Im trying to link a button in HTML to another html in my project folder for my django project. Lets say its
MyApp
-Polls
-templates
-index
-Votes
-templates
-main
-truths
-rigged
I have a a button on main that uses rigged and truths so in main it has this button
<form action="{% url 'Votes:rigged' %}">
<input type="submit" value="rigged votes" />
</form>
now i want to add another button that would link polls->index into it. Is there a way to do that without copying everything from Polls into the folder Votes?
UPDATE*
main.html
<form action="{% url 'Polls:Index' %}">
<input type="submit" value="Index" />
</form>
Polls.url
urlpatterns=[
url(r'^Index/', Index.as_view(), name="Index"),
]
Index.views
class IndexView(TemplateView):
# template location
template_name = "Polls/Index.html"
# post logic must be defined
def post(self, request, *args, **kwargs):
return redirect(reverse_lazy("Polls:Index"))
Please refer to https://docs.djangoproject.com/en/1.10/topics/http/urls/#url-namespaces
Please understand how the namespaces and named urls work. You should have a urls.py file in your 'MyApp' folder where other files like 'settings.py' and 'wigs.py' are there.
For referring to an url by namespaces you need to first register the namespace associated with url.py of your Polls app. Example from the documentation:
from django.conf.urls import include, url
urlpatterns = [
url(r'^polls/', include('polls.urls', namespace='Polls')),
]
Furthermore you must also name your url in 'polls.urls' like
url(r'^index/$', Whatever_view,name='index'),
then you can call the url as "Polls:index"
Related
Error: NoReverseMatch at /
Reverse for 'language' with keyword arguments '{'name': ''}' not found. 1 pattern(s) tried: ['(?P[^/]+)/\Z']
I am creating a Encyclopedia app in Django which has a form as a input, which will display the search result from my view after searching those input variable in util.py file.
I have created a form like below in my template
<form method="get" formaction="{% url 'language' name=form.name%}">
<input class="search" type="text" name="q" placeholder="Search Encyclopedia
</form>
Here goes my urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("<str:name>/", views.language, name="language"),
]
And the language function in views.py(not writing whole views.py as it will take a lot of space here):
def language(request, name):
if util.get_entry(name):
return render(request, "encyclopedia/entries.html",{
"entries": util.get_entry(name),
"title": name.capitalize()
})
else:
return HttpResponseNotFound("<div style='text-align:center;font- family:sans-serif'><h1>Error</h1><h2> Requested page was not found.</h2></div>")
form.name is empty. You have "entries" and "title" in the rendering context but not form.name
I need to upload file on a Django page, however, after following the official tutorial, I was not able to upload it, it always gives the error "invalid form", and when I tried to print out the error msg of the form, it says "This field is required".
One thing notable is: I have 2 forms on one page, one is this upload form and the other one is for filling out information. Not sure if this is the root cause.
I have tried all solutions provided on the Internet.
Template file:
<form id="uploadForm" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="file" value="upload" name="sourcefile">
<button type="submit">Upload</button>
</form>
Forms.py:
from django import forms
from .models import SourceFile
class UploadFileForm(forms.ModelForm):
class Meta:
model = SourceFile
fields = ('file', 'title')
Models.py:
from django.db import models
# Create your models here.
class SourceFile(models.Model):
title = models.CharField(max_length=255, blank=True)
file = models.FileField(upload_to="media/")
Views.py
def model_form_upload(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
instance = SourceFile(file_field=request.FILES['file'])
instance.save()
return JsonResponse({'error': False, 'message': 'Uploaded Successfully!'})
else:
print("Invalid form")
# return JsonResponse({'error': True, 'errors': form.errors})
else:
form = UploadFileForm()
return render(request, 'source_validation.html', {'form': form})
Your template is wrong. Either use {{ form.as_p }} which should display a file input field because file is a field in your form. (so remove the <input type="file" ...>)
Or don't use it and manually add the <input> fields, but then you must use the correct names. Your form expects a "file" parameter, not a "sourcefile" parameter:
<input type="file" name="file">
Also, you're overcomplicating things in your view (even though your current code will work if you fix your template):
if form.is_valid():
form.save() # this will save your model
return redirect(...)
I'm trying to set up a raw html form where a user can make a suggestion and then save it on a database with a POST method, but I keep getting a Forbidden (403) CSRF verification failed. Request aborted. even after following the steps in the Help section.
I have found that I don't get the error if I add csrf_exempt on top of my view like this:
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def suggest_ptags(request):
context = {}
print("Form is submitted.")
return render(request, "partials/search_form.html", context)
But I was made aware that It removes completly the CSRF protection and I don't want that.
So what should I do?
Here's my search_form.html form in a partials folder in templates:
<!-- Suggestion Form in popup -->
<div class="prop-modal">
<div class="prop-content">
<a class="btn-close-prop">×</a>
<img src="{% static 'images/pyramids.svg' %}">
<form action="/suggest_ptags/" class="feedback-form" method="POST" enctype="text/plain">
{% csrf_token %}
<h5 class="title-prop">Suggestion</h5>
<input class="input-prop" name="suggest" rows="3" cols="37" placeholder="suggest something..."></input>
<input class="button-prop" type="submit" value="Envoyez"></input>
</form>
</div>
</div>
My current Views.py:
from django.views.decorators.csrf import ensure_csrf_cookie
#ensure_csrf_cookie
def suggest_ptags(request):
context = {}
print("Form is submitted.")
return render(request, "partials/search_form.html", context)
And in my Urls:
from django.conf.urls import url
from django.contrib import admin
from search.views import HomeView, ProductView, FacetedSearchView, autocomplete, suggest_ptags
from .settings import MEDIA_ROOT, MEDIA_URL
from django.conf.urls.static import static
urlpatterns = [
url(r'^$', HomeView.as_view(), name='home'),
url(r'^admin/', admin.site.urls),
url(r'^suggest_ptags/$', suggest_ptags, name='suggest_ptags'), #Suggestions
url(r'^product/(?P<slug>[\w-]+)/$', ProductView.as_view(), name='product'),
url(r'^search/autocomplete/$', autocomplete),
url(r'^search/', FacetedSearchView.as_view(), name='haystack_search'),
] + static(MEDIA_URL, document_root=MEDIA_ROOT)
Any solutions?
You shouldn't use enctype="text/plain". You can remove it (which is the same as enctype="multipart/form-data"), or use enctype="multipart/form-data" if you are uploading files.
Started learning django about a week ago and ran into a wall. Would really appreciate any enlightenment...
models.py
class data(models.Model):
course = models.CharField(max_length = 250)
def __str__(self):
return self.course
html
Converted the objects in models.course to schlist
<link rel="stylesheet" type="text/css" href="{% static '/chosen/chosen.css' %}" />
<form action={% views.process %} method="GET">
<div>
<h4 style="font-family:verdana;">First Course: </h4>
<select data-placeholder="Course" style="width:350px;" class="chosen-select" tabindex="7">
<option value=""></option>
{% for item in schlist %}
<option> {{ item }} </option>
{% endfor %}
</select>
</div>
</br>
<div>
<h4 style="font-family:verdana;">Second Course:</h4>
<select data-placeholder="Course" style="width:350px;" class="chosen-select" tabindex="7">
<option value=""></option>
{% for item in schlist %}
<option> {{ item }} </option>
{% endfor %}
</select>
</div>
</br>
<input type="submit" value="Compare!" />
</form>
urls.py (having my doubts if this works..)
urlpatterns = [
url(r'^(\d+)/(\d+)$',views.process, name = 'process'),
]
view.py
def process(request,q1 ,q2):
obj1= get_object_or_404(Schdata, course = q1)
obj2= get_object_or_404(Schdata, course = q2)
........
Was wondering if it is possible for the form action to direct the action to
(1) view.py or (2) url.py (and eventually to a view.py) with 2 arguments selected?
If so how should the form action be? {{view ?}} or {{url ?}}. Am I missing out the definition of my arguments in my HTML?
Directing to views.py:
User input is CharField, could use get_object_or_404 to get the model pk. However when defining my urls.py I would get a Noreverse error as my url arguments is the primary key.
Directing to urls.py:
Url arguments is primary key. From the way I see it, I need to magically convert my User input Charfield to a pk before passing it to urls.py
Is there a (or) function for get() in django? E.g get_object_or_404(pk = q1 or course = q1)?
Would really appreciate any advice. Been staring at this for hours.
You are trying to use the reverse resolution of urls in Django.
In your html file correct form action url to the following and method should be POST:
<form action={% url 'process' %} method="POST">
In case you are trying to pass parameters along then use this:
<form action={% url 'process' request.user.id 4 %} method="POST">
Reference:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Yes i'm late but it can help others for better understanding how Django processes the request.
Django 3.0 pattern
How Django processes the request
Basic :
First Django check the matching URL.
If URL is matched then calling the defined view to process the request. (Success)
If URL not matched/found the Django invokes error Page Not Found
In detail reading :
Official Django Documentations How Django processes a request
These are your URL patterns :
urlpatterns = [ path('profile/edit/<int:pk>/',views.editprofile, name='editprofile'),]
Third argument in urlpatterns is for if you want to change the url pattern from current to this :
urlpatterns = [ url('profile/edit/user/id/<int:pk>',views.editprofile, name = 'editprofile'),]
You don't need to redefine url pattern in all Templates where you using url name.
For Example :
This is my template profile.html where i used the url name instead of hard coded url.
<a class="item" href="{% url 'editprofile' user.id %}" >Edit profile </a>
Solution of your problem :
.html
Only use url name instead of hard coded url in your templates and pass arguments.
<form action={% process no_of_arguments %} method="POST">
views.py
Here you can process your request
def process(request,no_of_arguments):
Become good django developer
You can also use Django ModelForms for your model.
Using model forms or simple form you can do multiple things
Modular approach
Write server side validation in related form instead of doing in views.py
Readable code - Clean code
I am building a site where users can input text and submit the text so that it can be saved and accessed as a file on the server. Unfortunately, I am not quite sure how I would take the inputted text and save it aas a file.
Could anyone point me in the right direction as to how I might do this or detail the steps I will have to take? Preemptive apologizes if I have missed an obvious Google result. Being somewhat new to Django, I may have inadvertently glossed over helpful resources.
Here is the relevant HTML, mostly a form copied from a file upload form:
<form name="myWebForm" id="submissionCode_codeEditor" action="uploadFile/" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="500" />
<input type="text" name="title" placeholder="File Name"/>
<input type="hidden" name="taskID" value={{ taskID }} />
<input type="submit" value="Submit This Code" />
</form>
Here is the relevant Django model:
class Upload(models.Model):
title = models.CharField(max_length=50)
fileUpload = models.FileField(upload_to='file_uploads')
userID = models.ForeignKey(User)
task = models.ForeignKey(Task)
uploadTime = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.title
You're looking for ContentFile. It's a Django File subclass that instantiates with a string of text instead of a literal file. You can then save the ContentFile to your FileField.
from django.core.files.base import ContentFile
content = ContentFile(some_text)
upload_instance.fileUpload.save('/path/to/where/file/should/save.txt', content)
upload_instance.save()
First of all create a file in your media folder using command, i am assuming user posted text with name content
from app.models import Upload
from django.conf import settings
content = request.GET("content")
file_object = open("%s/%s"%(settings.MEDIA_ROOT, filename),w) #Take file name as hash of content posted and username so that no class
upload = Upload(title=title, fileUpload=filename,user_id=request.user.id)
Your file is uploaded and can be acceseed using MEDIA_URL from settings