How to save form data from base.html in django? - python

In my app, I have created a context_proccessors.py to show the form to base.html file.
I am able to show the form in the base.html file. But the problem I am facing is I have no idea how to save that form data from base.html since there is no view for the base.html. Below is my code:
models.py
class Posts(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_posts')
post_pic = models.ImageField(upload_to='post_pic', verbose_name="Image")
post_caption = models.TextField(max_length=264, verbose_name="Caption")
created_date = models.DateTimeField(auto_now_add=True)
edited_date = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.user.username}"
forms.py
from django import forms
from post_app.models import Posts
class PostForm(forms.ModelForm):
class Meta:
model = Posts
exclude = ('user',)
context_proccessors.py
from post_app.forms import PostForm
def post_form(request):
form = PostForm
return {
'post_form': form,
}
base.html
<form method="POST" enctype="multipart/form-data">
{{ post_form|crispy }}
{% csrf_token %}
<button type="submit" class="btn btn-primary">Post</button>
</form>
I want the form to be displayed on every page so that the user can submit data from anywhere

def PostView(request):
form = PostForm()
if request.method == 'GET':
return render(request, 'base.html', {form:form})
elif request.method == 'POST':
form.save(request.data)
In the views.py of your app you can define this view, and the you have to provide it an url in the urls.py of the root directory. So evere time there is a request on that url, if the method is GET, the form will be rendered on base.html file, if the method is POST, the post will be saved.

By following the answer by N T I have implemented this. So, I had to make a URL pattern for the view and use that URL pattern in the action in the form of base.html.
view.py
#login_required
def postsaveview(request):
form = PostForm()
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
if form.is_valid():
user_obj = form.save(commit=False)
user_obj.user = request.user
user_obj.slug = str(request.user) + str(uuid.uuid4())
user_obj.save()
return HttpResponseRedirect(reverse('profile_app:profile'))
urls.py
urlpatterns = [
path('post-save/', views.postsaveview, name='post-save'),
]
base.html
<form action="{% url "post-save" %}" method="POST" enctype="multipart/form-data">
{{ post_form|crispy }}
{% csrf_token %}
<button type="submit" class="btn btn-primary">Post</button>
</form>

Related

my form field doesn't appear at html file

I'm trying to fix this problem... I made a simple post form with forms.py but it doesn't show up at the HTML file. I searched at google but I still don't know how to fix it
views.py
from django.shortcuts import render
from contact.forms import contactForm
def contact(request):
form = contactForm(request.POST)
if form.is_valid():
return request.POST
context = locals()
template = 'contact.html'
return render(request, 'contact/contact.html')
contact.html
{% block content %}
<h1>
Contact doesn't appears..
</h1>
<form method = "POST">{% csrf_token %}
{{ form.as_p }}
<input type = "submit" value = "submit form" class = 'btn btn-default' />
</form>
{% endblock %}
forms.py
from django import forms
from django.shortcuts import render
class contactForm(forms.Form):
name = forms.CharField(required = False, max_length = 100, help_text='100 characters max.')
email = forms.EmailField(required = True)
comment = forms.CharField(required = True, widget = forms.Textarea)
You need to pass in the objects you want in the render function.
def contact(request):
...
context = {'form': form}
return render(request, 'news/year_archive.html', context)
As you can see you are passing the dictionary labeled context inside the render which should now be able to be accessed by your template.
Django view example

Django ModelForm not saving data to database, Form.save is not working?

List item
Hello I am django beginner having tough time could someone please help me I don't know what am I doing wrong ?
I am trying to create a form and saving some data through it by using form.save(). And I am new to here also so don't mind any mistakes.
Here is my model:
from django.db import models
from stores.models import Store
class Category(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Product(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
price = models.DecimalField(max_digits=5, decimal_places=5)
image = models.ImageField(upload_to='upload_to/')
category = models.ForeignKey(Category, default='Default', on_delete=models.CASCADE, blank=False, null=False)
store = models.ForeignKey(Store, on_delete=models.CASCADE, blank=False, null=False)
Here is my view:
from django.shortcuts import render, redirect
from .forms import NewPro
def pro(request):
if request.method == 'POST':
form = NewPro(request.POST)
if form.is_valid():
form.save()
return redirect('stores_list')
else:
form = NewPro()
return render(request, "default/add_product.html", {'form': form})
def product_list(request):
return render(request, 'default/product_list.html')
Here is my form:
from django import forms
from .models import Product
class NewPro(forms.ModelForm):
class Meta:
model = Product
fields = ('name', 'price', 'image','category', 'store',)
default/add_product.html :
{% extends 'default/base.html' %}
<html>
<head><title>E-Commerce App</title></head>
{% block content %}
<h1>Add Product details</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Add Product</button>
</form>{% endblock %}
</html>
Settings.py settings
MEDIA_ROOT = '/home/saifi/Saif_project/final_project/MEDIA_ROOT/upload_to'
I can see some indentation issues in the view - but I'll guess that's just formatting when copying into Stackoverflow.
the form.is_valid() check will validate all your form fields and will only write to the database if all the input fields are valid. If it's not saving, the first place I'd check would be for form errors.
In your template you can render the errors with {{form.errors}} and it will list each field and error.
You forgot request.FILES in your pro view function, you have an image file after all.
def pro(request):
if request.method == 'POST':
form = NewPro(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('stores_list')
else:
form = NewPro()
return render(request, "default/add_product.html", {'form': form})
Try using the form this way:
<form action="YOUR_URL_HERE" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Add Product</button>
</form>
I hope this will help. Welcome aboard ;)
Your indentation is wrong, the else should be for first 'if'
def pro(request):
form = NewPro()
if request.method == 'POST':
form = NewPro(request.POST)
if form.is_valid():
form.save()
return redirect('stores_list')
else:
form = NewPro()
return render(request, "default/add_product.html", {'form': form})

Django model form data not being saved

I have a profile model for the User which has fields like "bio" and "cover" representing the General information about the profile of the user etc..
I want those two things to be able to be edited by the User. I did everything from urls.py to forms.py to views.py to template etc and it looks like I can submit the data and it looks like its validating but the data isnt being saved.. i dont know how..
here are my files, i've included more code than neeeded just to see if maybe the code somewhere else is in fault.
note, the code that is not working is the one with "general" somewhere included in the name
urls.py
from django.conf.urls import include, url
from . import views
app_name = 'profili'
urlpatterns = [
#profile
url(r'^$', views.ProfilePage, name='profile'),
url(r'^edit/$', views.EditProfile, name='edit_profile'),
url(r'^edit/general/$', views.EditGeneralProfile, name='edit_general_profile'),
url(r'^edit/password$', views.EditPassword, name='edit_password'),
url(r'^edit/delete/$', views.DeleteProfile, name='delete_profile'),
]
views.py
def EditProfile(request):
if request.method == 'POST':
form = EditProfileForm(request.POST, request.FILES, instance=request.user)
if form.is_valid():
form.save()
return redirect('/profile')
else:
form = EditProfileForm(instance=request.user)
formpw = PasswordChangeForm(user=request.user)
generalform = EditGeneralProfileForm(instance=request.user)
args = {
'form': form,
'formpw': formpw,
'generalform': generalform,
}
return render(request, 'profili/editprofile.html', args)
#login_required
def EditGeneralProfile(request):
generalform = EditGeneralProfileForm(request.POST, request.FILES, instance=request.user)
if generalform.is_valid():
generalform.save()
return redirect('/profile')
else:
print('THIS IS NOT WOOORRKIINNGGG')
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
followall = models.ManyToManyField(User, related_name='followfriend')
bio = models.TextField(max_length=100, default='', blank=True)
cover = models.FileField(blank=True)
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
forms.py
class EditGeneralProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('bio', 'cover')
template where the form actually appears in GET request
<form class="form-self general-form" method="post" action="{% url 'profili:edit_general_profile' %}" enctype="multipart/form-data">
{% csrf_token %}
{% for item in generalform %}
<div class="full-part">
<div class="label-par">
<span class="label-part">{{ item.label }}:</span>
</div>
<div class="original-part">{{ item }}</div>
</div>
{% endfor %}
<div class="full-part-btn">
<button type="submit" class="fpartbtn">Save</button>
</div>
</form>
This is a form for the Profile model, so you should pass that as the instance.
generalform = EditGeneralProfileForm(request.POST, request.FILES, instance=request.user.profile)

How to save a data after user logs in DJANGO

After user logs in, user is able to submit a form. On click of submit button, data is being stored in DB, but how should I connect this information to the submitting user.
I would need the code as well as the structure of the new db
Kind of starting out in django.
Any help would be appreciated!!!
I have included user as foreign key in the CustomizeRequest model, but now how do i fill in this information?
Exact Scenario: After user log in, once he comes to contactUs.html, he submits a form which tells the number of travellers. This number is being stored in the DB. But now how do I connect each of these numbers to the submitted user?
models.py
class CustomizeRequest(models.Model):
user = models.ForeignKey(User)
travellers = models.CharField(max_length=2)
def __str__(self):
return self.travellers
contactUs.html
<form method="POST" class="form-horizontal">
{% csrf_token %}
<div class="btn-group" data-toggle="buttons">
{% for radio in crform.travellers %}
<label class="btn btn-default {% if radio.choice_label = '1' %}active{% endif %}" for="{{ radio.id_for_label }}">
{{ radio.choice_label }}
{{ radio.tag }}
</label>
{% endfor %}
</div>
<button type="submit" class="btn btn-default btn-block btn-warning">SUBMIT</button>
</form>
views.py
def contactUs(request):
if request.method=="POST":
form = CustomizeRequestForm(request.POST)
form.save()
else:
form = CustomizeRequestForm()
context_dict = {'form': form}
return render(request, 'tour/contactUs.html', context_dict)
Based on catavaran answer (with a check to see if the form is valid):
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
#login_required
def contactUs(request):
form = CustomizeRequestForm(data=request.POST or None)
if request.method == "POST":
if form.is_valid():
customize_request = form.save(commit=False)
customize_request.user = request.user
customize_request.save()
return redirect('.')
else:
pass # could add a notification here
context_dict = {'form': form}
return render(request, 'tour/contactUs.html', context_dict)
Logged user is available as request.user property. You can get the unsaved model instance using form.save(commit=False) trick, set the user field and then save the instance to database:
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
#login_required
def contactUs(request):
if request.method == "POST":
form = CustomizeRequestForm(request.POST)
if form.is_valid():
customize_request = form.save(commit=False)
customize_request.user = request.user
customize_request.save()
return redirect('.')
else:
form = CustomizeRequestForm()
context_dict = {'form': form}
return render(request, 'tour/contactUs.html', context_dict)

working with forms in django

I want to write form and when submit it write "welcome!" in my page.But after I submit form method still is GET!!what's wrong?
this is my models:
from django.db import models
import django_tables2 as tables
from django import forms
class Form1(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
this is my view:
def contact(request):
if request.method == 'POST': # If the form has been submitted...
# ContactForm was defined in the previous section
form = Form1(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
return render(request, 'student/Home.html',{'message':'welcome'})
else:
form = Form1() # An unbound form
return render(request, 'student/Home.html', {'form': form})
this is my template(Home.html):
<!DOCTYPE html>
<html>
<body>
<form action="{% url 'student:contact' %}" method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Submit" />
</form>
<p>{{message}}<p>
</body>
</html>

Categories