How to make form in _base.html - django

I need to make form in header section of site. This form will be available for all pages in my site. For example, i have in my app "accounts":
forms.py
class SignupForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ('phone',)
views.py
def signup(request):
form = SignupForm(request.POST or None)
# CODE #
ctx = {
'form': form,
}
return render(request, 'accounts/signup.html', ctx)
urls.py
from django.urls import path
from . import views
app_name = 'accounts'
urlpatterns = [
path('signup/', views.signup, name='signup'),
]
accounts/signup.html
{% block signup %}
{{ form }}
{% endblock %}
If I add{% include 'accounts/signup.html' %} to my _base.html, I don't, get form - {{ form }} but all other content will be included.
And can you tell me how exactly get form for all pages in site? Is it the correct approach?

Use a custom templatetag to initialize an empty form and display it from wherever you want - just make sure the action attribute of the HTML <form> tag points to your signup view.

Related

Django update view only seems to work with regex urls

I am getting my hands dirty with Django and have a simple use case in which i have to create a function based view for updating a Model. Below is my function based view function:
def update_post(request, id=None):
obj = get_object_or_404(PostModel, id=id)
form = PostModelForm(request.POST or None, instance=obj)
if form.is_valid():
obj = form.save(commit=False)
print(f"The object that i am going to save is {form.cleaned_data}")
obj.save()
messages.success(request, f"Updated object with id {id}")
return HttpResponseRedirect(f"/blog/read/{id}")
context = {
"form": form
}
return render(request, "blog/update-post.html", context)
Below is my update-post.html:
<html>
<form method="POST" action="."> {% csrf_token %}
{{form.as_p}}
<input type="submit" value="Change">
</form>
</html>
And this is my urls.py file :
from django.urls import path, include
from django.conf.urls import url
from .views import list_posts, read_post, create_post, update_post
app_name = "blog"
urlpatterns = [
path('posts/', list_posts, name="list"),
path('read/<int:id>', read_post, name="read"),
path("create/", create_post, name="create"),
#url(r'^(?P<id>\d+)/edit/$', update_post, name="update")
path("update/<int:id>", update_post, name="update"),
]
The update view only seems to work when i use the above regex url pattern for editing the post .
Otherwise i get the below error message:
Can someone please tell me where i am going wrong with this.

Django: form works in index but not in a particular page

I'm having multiple forms around my website.
However, a have a particular form that is working in the home page (index.html), but when coping this particular form in a section of my site it doesn't work anymore (on this section, if I return to home everything works as expected).
What am I missing?
Views.py:
from django.shortcuts import render, HttpResponse, HttpResponseRedirect
from .models import Treasure, TamaniosCantidades
from .forms import TreasureForm, TamaniosCantidadesForm, LoginForm
from django.contrib.auth import authenticate, login, logout
# Create your views here.
def index(request):
treasures = Treasure.objects.all()
form = TreasureForm()
tamanioscantidades_form = TamaniosCantidadesForm()
return render(request, 'main_app/index.html', {'treasures': treasures,
'form': form,
'tamanioscantidades_form': tamanioscantidades_form})
def productos(request):
treasures = Treasure.objects.all()
form = TreasureForm()
return render(request, 'main_app/productos.html', {'treasures': treasures,
'form': form})
def die_cut(request):
tamanioscantidades_form = TamaniosCantidadesForm()
return render(request, 'main_app/die-cut-stickers.html', {'tamanioscantidades_form': tamanioscantidades_form})
def post_tamanioscantidades(request):
form = TamaniosCantidadesForm(request.POST)
if form.is_valid():
tamanioscantidades = TamaniosCantidades(tamanios=form.cleaned_data['tamanios'],
cantidades=form.cleaned_data['cantidades'])
# tamanioscantidades = tamanioscantidades_form.save(commit = False)
# tamanioscantidades.usuario = request.user
tamanioscantidades.save()
return HttpResponseRedirect('/')
def post_treasure(request):
form = TreasureForm(request.POST)
if form.is_valid():
treasure = Treasure(name=form.cleaned_data['name'],
value=form.cleaned_data['value'])
treasure.save()
return HttpResponseRedirect('/')
urls.py:
app_name = 'main_app'
urlpatterns = [
path('', views.index),
path('productos/', views.productos),
path('productos/die-cut-stickers', views.die_cut, name='die-cut-stickers'),
path('post_url/', views.post_treasure, name='post_treasure'),
path('post_url_tamanioscantidades/', views.post_tamanioscantidades, name='post_tamanioscantidades'),
]
*html**:
<div class="col-md-6 border border-primary rounded border-3">
<div class="m-5">
<div class="row">
<form action="post_url_tamanioscantidades/" method="post">
{% csrf_token %}
{{ tamanioscantidades_form.as_p }}
<input type="submit" value="Submit"/>
</form>
</div>
</div>
As I said, this form works in home, but when coping the same code in a section of my site the submit button does not save the form in database.
It returns:
Page not found (404)
Request Method: POST
Request URL: http://127.0.0.1:8000/productos/post_url_tamanioscantidades/
Using the URLconf defined in gallito.urls, Django tried these URL patterns, in this order:
admin/
productos/
productos/die-cut-stickers [name='die-cut-stickers']
post_url/ [name='post_treasure']
post_url_tamanioscantidades/ [name='post_tamanioscantidades']
accounts/
The current path, productos/post_url_tamanioscantidades/, didn't match any of these.
The problem is the form is being submitted to http://127.0.0.1:8000/productos/post_url_tamanioscantidades/ which does not exist instead you want it to submit at http://127.0.0.1:8000/post_url_tamanioscantidades/
So in your form html start the form action with /
<form action="/post_url_tamanioscantidades/" method="post">

Form not showing, Only the button shows Django

I am trying to show a newsletter form, and it is not shown in the page
This is my models.py
from django.db import models
# Create your models here.
class newsletter_user(models.Model):
email = models.EmailField()
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.email
This is my forms.py
from django import forms
from .models import newsletter_user
class newsletterForm(forms.ModelForm):
class Meta:
model = newsletter_user
fields = ['email']
def clean_email(self):
email = self.cleaned_data.get('email')
return email
This is my admin.py
from django.contrib import admin
from .models import newsletter_user
# Register your models here.
class newsletterAdmin(admin.ModelAdmin):
list_display = ('email','date_added',)
admin.site.register(newsletter_user,newsletterAdmin)
This is the views.py
from django.shortcuts import render
from .models import newsletter_user
from .forms import newsletterForm
# Create your views here.
def newsletter_subscribe(request):
form = newsletterForm(request.POST or none)
if form.is_valid():
instance = form.save(commit=false)
if newsletter_user.objects.filter(email=instance.email).exists():
print("already exists")
else:
instance.save()
context = {'form':form,}
template = "/blog/templates/footer.html"
return render(request, template, context)
This is the html
<form method="post" action=''>
<div class = "input-group">
{{form}} {% csrf_token %}
<span class = "input-group-btn">
<button class="btn btn-default" type="submit">Subscribe</button>
</span>
</div>
</form>
This is my urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.BlogIndex.as_view(), name='home'),
url(r'^(?P<slug>[-\w]+)/$', views.BlogDetail.as_view(), name='entry_detail'),
url(r'^ckeditor/', include('ckeditor_uploader.urls')),
url(r'^footer/$', subscribe_views.newsletter_subscribe, name='subscribe'),
]
My Project directory
The button is shown
But the form is not shown..
This is my source in web browser RIGHT-CLICK->VIEW SOURCE
The url router will send the request to the first matching view. That is the only one that is called, and that view has to provide the context data that the template consumes. (You can also write your own context processor to insert context that you need everywhere.)
Since another pattern also matches /footer/, your request is clearly handled by some other view.
url(r'^(?P<slug>[-\w]+)/$', views.BlogDetail.as_view(), name='entry_detail'),
If the other view doesn't provide form into the context, there's nothing for Django to render.
Your view function newsletter_detail() is not called from other views, so that context is not used. (Using the undefined none there would have caused a run time error, which shows that the code was never evaluated.)
Catch-all routes such as entry_detail should either be used as the last url route, or be made more specific. Something like r'^/blog/(?P<slug>[-\w]+)/$', for instance, which will not match /footer/.
For a simple "subscribe" form in the footer, I recommend writing it as just html, and set up a route /subscribe/ to handle POST requests. There's not anything to gain by using Django's form framework for such a simple case (Just one field).
The django docs has an example of how you can implement something like this.
You footer.html template fragment should not require any context that is not automatically inserted by a context processor. Django's CsrfViewMiddleware provides the {% csrf_token %}, so that's an example of something you can use in template fragments such as a footer.
If you need some complicated form in your footer, you can write custom middleware to insert a Django Form instance in every context, (but you should probably give it a less generic name than form).
You may need to make some changes in your view somewhat like this,
def newsletter_subscribe(request):
if request.method == 'POST':
form = newsletterForm(request.POST)
if form.is_valid():
instance = form.save(commit=false)
if newsletter_user.objects.filter(email=instance.email).exists():
print("already exists")
else:
instance.save()
else:
form = newsletterForm()
context = {'form':form,}
template = "/blog/templates/footer.html"
return render(request, template, context)
You only need to initialise the form with request.POST , if request method is actually "POST". Else, just initialise a blank form.

Django Updating Existing Model field

I have a model in Django with a foreign key to Django User Model. I am trying to update my model with a form, but database isn't updating. I can't figure out the problem.
model.py
from django.conf import settings
class UserInfo(models.Model):
username = models.CharField(max_length = 30)
owner = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,)
form.py
from django import forms
from society.models import UserInfo
class Editform(forms.ModelForm):
username=forms.CharField(widget=forms.TextInput(attrs={'onchange': 'this.form.submit();', 'class': 'editinput'}))
class Meta:
model = UserInfo
fields ='__all__'
views.py
from django.shortcuts import render
from society.models import UserInfo
from django.contrib.auth.models import User
from society.forms import Editform
def ProfileView(request):
user = request.user
username = UserInfo.objects.get(owner=user)
if request.method == 'POST':
form = Editform(request.POST, instance=username)
if form.is_valid():
form.save()
else:
form = Editform(instance=username)
return render (request, 'profile_view.html', {'user':username, 'form':form})
url.py
from django.conf.urls import url
from django.contrib import admin
import society.views
urlpatterns = [
url(r'^$', 'society.views.home'),
url(r'^admin/', admin.site.urls),
url(r'^login/', 'django.contrib.auth.views.login'),
url(r'^logout/', 'django.contrib.auth.views.logout'),
url(r'^userreg/', 'society.views.UserReg'),
url(r'^profile/', 'society.views.ProfileView'),
]
profile_view.html
<div>
<form method="POST">
{% csrf_token %}
{{form.username}}
{{user.username}}
</form>
</div>
When ever I change form.username, user.username change instantly but the database is not updating. I tried with adding a submit button, but still no luck.
You should pass record id for updating existing UserInfo record.
from django.shortcuts import render
from society.models import UserInfo
from django.contrib.auth.models import User
from society.forms import Editform
def ProfileView(request):
user_id = request.POST.get('user_id')
user = UserInfo.objects.get(pk=user_id)
if request.method == 'POST':
form = Editform(request.POST, instance=user)
if form.is_valid():
form.save()
else:
form = Editform(instance=user)
return render (request, 'profile_view.html', {'user':username, 'form':form})
You can update in 2 method for eg: here i am going to update Your username,
1) if you using object.get():
get_name = UserInfo.objects.get(owner=user)
get_name['username'] = 'Your Input what you need to change'
get_name.save()
2) if you using object.filter():
get_name = UserInfo.objects.filter(owner=user).update(username='your data') # or form.username
Thats it..
Apart from anything else, you haven't pointed your form at anything, so the form can't connect to the logic of the view - in effect, you've specified the form should POST content, but not where to.
The form should point to a URL in your urls.py file, which is of course linked to the view you've shown above. That works in the following way:
<form action="{% url 'core.views.new_comment' %}" method="post">
{% csrf_token %}
...
</form>
There's more guidance about how this works here in the docs. (Obviously people know that the answer's in the docs, the trick is finding it. :) )
(Also, your formatting is off in the views.py, but I think that's just a cut and paste problem when entering the question.)
Anyway I soloved this problem, Thank You everyone. Just Changed the form.py
from django import forms
from society.models import UserInfo
class Editform(forms.ModelForm):
username=forms.CharField(widget=forms.TextInput(attrs={'onchange': 'this.form.submit();', 'class': 'editinput'}))
class Meta:
model = UserInfo
exclude =('owner',)
As owner is a mandatory field, but I omitted it from template it was showing mandatory field error. Its working now. Thanks anyway.

How to render a POST and make it show up on another page

I'm trying to create a marketplace website similar to craigslist.
I created a form according to the Django tutorial "Working with forms", but I don't know how to render information I got from the POST forms.
I want to make information(subject,price...etc) that I got from POST show up on another page like this. http://bakersfield.craigslist.org/atq/3375938126.html and, I want the "Subject"(please look at form.py) of this product(eg.1960 French Chair) to show up on another page like this. http://bakersfield.craigslist.org/ata/ }
Can I get some advice to handle submitted information?
Here's present codes. I'll appreciate all your answers and helps.
<-! Here's my codes -->
◆forms.py
from django import forms
class SellForm(forms.Form):
subject = forms.CharField(max_length=100)
price = forms.CharField(max_length=100)
condition = forms.CharField(max_length=100)
email = forms.EmailField()
body = forms.TextField()
◆views.py
from django.shortcuts import render, render_to_response
from django.http import HttpResponseRedirect
from site1.forms import SellForm
def sell(request):
if request.method =="POST":
form =SellForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
price = form.cleaned_data['price']
condition = form.cleaned_data['condition']
email = form.cleaned_data['email']
body = form.cleaned_data['body']
return HttpResponseRedirect('/books/')
else:
form=SellForm()
render(request, 'sell.html',{'form':form,})
◆urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^sechand/$','site1.views.sell'),
url(r'^admin/', include(admin.site.urls)),
)
◆sell.html
<form action = "/sell/" method = "post">{% csrf_token%}
{{ form.as_p }}
<input type = "submit" value="Submit" />
</form>
I assume you have a Sell model/table in your db(where you store the users' "sells"), otherwise it wouldn't make any sense. This means you can save yourself some time and use a ModelForm,
instead of a simple Form. A model form takes a database table and produces an html form for it.
forms.py
from django.forms import ModelForm
from yourapp.models import Sell
class SellForm(ModelForm):
class Meta:
model = Sell
In your views.py you need one more view that displays the Sells that your users have
posted for others to see. You also need an html template that this view will render with context about each Sell.
sell_display.html
{% extends 'some_base_template_of_your_site.html' %}
{% block content %}
<div id="sell">
<h3> {{ sell.subject }}</h3>
<p> {{ sell.condition }}</p>
<p> {{ sell.body }}</p>
<!-- the rest of the fields.. -->
</div>
{% endblock %}
We also need a new url entry for the displaying of a specific Sell
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Changed `sell` view to `sell_create`
url(r'^sechand/$','site1.views.sell_create'),
# We also add the detail displaying view of a Sell here
url(r'^sechand/(\d+)/$','site1.views.sell_detail'),
url(r'^admin/', include(admin.site.urls)),
)
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from yourapp.models import Sell
from yourapp.forms import SellForm
def sell_detail(request, pk):
sell = get_object_or_404(Sell, pk=int(pk))
return render_to_response('sell_display.html', {'sell':sell})
def sell_create(request):
context = {}
if request.method == 'POST':
form = SellForm(request.POST)
if form.is_valid():
# The benefit of the ModelForm is that it knows how to create an instance of its underlying Model on your database.
new_sell = form.save() # ModelForm.save() return the newly created Sell.
# We immediately redirect the user to the new Sell's display page
return HttpResponseRedict('/sechand/%d/' % new_sell.pk)
else:
form = SellForm() # On GET request, instantiate an empty form to fill in.
context['form'] = form
return render_to_response('sell.html', context)
This is enough to get you going I think. There are patterns to make these things more modular and better, but I don't want to flood you with too much information, since you are a django beginner.