django updateview return blank template - django

here is in my models.py:
class Segment(models.Model):
email_segment_name = models.CharField(max_length=200)
email_segment_status = models.BooleanField()
user = models.ForeignKey(User,on_delete=models.SET_NULL,blank=True,null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.email_segment_name
and forms.py:
class SegmentForm(forms.ModelForm):
class Meta:
model = Segment
fields = ['email_segment_name']
labels = {
'email_server_name':('Server Name'),
}
and views:
#method_decorator(login_required, name='dispatch')
class SegmentUpdate(UpdateView):
model = Segment
form_class = SegmentForm
template_name_suffix = '_update_form'
success_url = '/emails/segment'
segment_update_form.html:
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update" />
</form>
the FormView and DeleteView just works fine, but when I update the form, it response with 200 OK and the page is blank, any ideas?

change:
method='post'
to:
method='get'
in segment_update_form.html

Related

Url not being resolved in, 404 error django

I am not able to create an detail and update view using the <pk> and <pk>/update/, this is my url paths.
urlpatterns = [
path('',views.IndexView.as_view(), name='index'),
path('form/',views.CompanyView.as_view(),name='company'),
path('toy/',views.ToyView.as_view(),name='toy'),
path('int:pk>/',views.CompanyDetailView.as_view()),
path('int:pk>/update/',views.CompanyUpdateView.as_view())
]
my views looks like this,
class CompanyUpdateView(generic.UpdateView):
model = Company
fields = '__all__'
success_url = '/company'
class CompanyDetailView(generic.DetailView):
model = Company
fields = '__all__'
class CompanyView(generic.CreateView):
model = Company
template_name = 'company/company.html'
fields = '__all__'
success_url = '/company'
models.py is
class Company(models.Model):
company_name = models.CharField(max_length=50)
location = models.CharField(max_length=50)
email_id = models.EmailField()
def __str__(self):
return self.company_name
class Toys(models.Model):
toy_name = models.CharField(max_length=50)
company = models.ForeignKey(Company,on_delete=models.CASCADE,blank=True,null=True)
price = models.IntegerField()
This is the template used to in the CreateView and UpdateView since I am using a ModelForm
<form method="post">
{% csrf_token %}
<fieldset>
<legend>
<h2> Company Form </h2>
</legend>
{{ form.as_p }}
</fieldset>
<input type="submit" value="Submit" />
</form>
Create view is working. When I got to a url company/1/ or company/1/update I get a 404 error. What would be the reason for it and how to solve this

Django - saving model via a form is not working

I'm having a little problem with the .save() method in Django. For 1 form it works, for the other it doesn't. And I can't find the problem.
views.py
#login_required
def stock_add(request, portfolio_id):
if request.method == 'POST':
print('request.method is ok')
form = StockForm(request.POST)
print('form is ok')
if form.is_valid():
print('form is valid')
stock = form.save(commit=False)
stock.created_by = request.user
stock.portfolio_id = portfolio_id
stock.save()
return redirect('portfolio-overview')
else:
print("nope")
else:
print('else form statement')
form = StockForm()
context = {
'form':form
}
return render(request, 'portfolios/stock-add.html', context)
forms.py
class StockForm(ModelForm):
class Meta:
model = Stock
fields = ['quote', 'amount']
html
{% extends 'core/base.html' %}
{% block content %}
<div class="container">
<h1 class="title">Add Stock</h1>
<form method="POST" action=".">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="button is-primary">Submit</button>
</form>
</div>
{% endblock %}
models
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Portfolio(models.Model):
title = models.CharField(max_length=56)
description = models.TextField(blank=True, null=True, max_length=112)
created_by = models.ForeignKey(User, related_name='portfolios', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'Portfolio'
def __str__(self):
return self.title
class Stock(models.Model):
Portfolio = models.ForeignKey(Portfolio, related_name='stocks', on_delete=models.CASCADE)
quote = models.CharField(max_length=10)
amount = models.IntegerField()
created_by = models.ForeignKey(User, related_name='stocks', on_delete=models.CASCADE)
created_at = models.DateField(auto_now_add=True)
def __str__(self):
return self.quote
If you look at the views.py file, when I submit the form, it won't even do print('request.method is ok')
I can add the stock via the admin page.
So I have no clew where to look anymore...
Cheers
When you post a form and need a special url (like your' with an attribute), i like to set action="{% url myview.views.stock_add portfolio_id %}"
action="." will save to the same page without taking care of extra parameters (if needed)
Just pass portfolio_id in the context and that will work
I found the answer, an InteregerField (from models.py) needs a default value.
Either default=None (or another value).
Cheers

form not saving data in db

i'm creating a form for product create and i have 5 image fields in product model ,user can upload 5 or 0 images as per requirement , but form is not saving data
python
models.py
class Category(models.Model):
cate_id = models.AutoField(primary_key=True)
category_name = models.CharField(max_length=45)
class Product(models.Model):
product_id = models.AutoField(primary_key=True)
product_name = models.CharField(max_length=45)
product_description = models.CharField(max_length=500, blank=True, null=True)
price = models.IntegerField()
quantity = models.IntegerField()
product_category_fk = models.ForeignKey('Category', on_delete=models.CASCADE,db_column='product_category_fk',related_name='pros')
image1 = models.ImageField(upload_to='chand_imgs',blank=True)
image2 = models.ImageField(upload_to='chand_imgs',blank=True)
image3 = models.ImageField(upload_to='chand_imgs',blank=True)
image4 = models.ImageField(upload_to='chand_imgs',blank=True)
image5 = models.ImageField(upload_to='chand_imgs',blank=True)
#forms.py
class CategoryForm(forms.ModelForm):
category_name = forms.CharField(max_length=50)
class Meta:
model = Category
fields = ('category_name', )
class ProductForm(forms.ModelForm):
class Meta():
model = Product
fields = ('product_category_fk','product_name','product_description','price','quantity','image1','image2','image3','image4','image5',)
#views.py
#login_required
def product_management(request):
form = ProductForm(data=request.POST)
if request.method =='POST':
if form.is_valid():
post=form.save(commit=True)
if 'picture' in request.FILES:
form.picture =request.FILES['picture']
return HttpResponseRedirect(reverse('index'))
else:
return render(request,'chandler/index.html',{'form':form})
else:
form = ProductForm()
return render(request,'chandler/product.html',{'form':form})
#product.html
{% if user.is_authenticated %}
<form method=”post” enctype=”multipart/form-data” action="" >
<h2>New post</h2>
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% else %}
<h2>Please login first!!!!</h2>
{% endif %}
form not saving any data i know my view is incorrect ,already tried different methods
change
<form method=”post” enctype=”multipart/form-data” action="" >
to
<form method="post" enctype="multipart/form-data" action="" >

How can I grab the (text) value instead of the number on a multiple choice field?

I have a CreateView class and I'm trying to use the input from a multiple choice field it has as part of the success_url.
It works on my TopicCreateView class because the input is a charfield, but when I try to get it to work on PostCreateView it returns a KeyError. From what i understand it's because it returns the value of the multiple choice field(1, 2, 3 etc) instead of the text between the option tags.
The Topic part works fine.
views.py
class TopicCreateView(LoginRequiredMixin, CreateView):
model = Topic
template_name = 'topic_form.html'
fields = ['board', 'title']
success_url = '/topic/{title}'
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
And here is the models.py
class Topic(models.Model):
title = models.CharField(max_length=100, unique=True)
board = models.ForeignKey(Board, default='ETC', on_delete=models.SET_DEFAULT)
date_published = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
Here is what I can't get to work, the Post.
views.py
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
template_name = 'post_form.html'
fields = ['topic', 'content']
success_url = '/topic/{topic}'
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
and models.py
class Post(models.Model):
content = models.TextField()
author = models.CharField(max_length=200, default='Unknown', blank=True, null=True)
date_published = models.DateTimeField(default=timezone.now)
topic = models.ForeignKey(Topic, default=content, on_delete=models.SET_DEFAULT)
def __str__(self):
return self.topic
Also, the form is the same for both of them:
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Create A New Post</legend>
{{ form | crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Submit</button>
</div>
</form>
</div>
{% endblock %}
So, when I redirect to the newly created topic/thread it works, but I can't do the same for new posts.

django form how to render the fields

I'm trying to render a form but the fields are not displayed in the HTML.
views.py
#url(r'^boxes/(?P<pk>[0-9A-Za-z-]+)/$', views.show_form, name='box'),
def show_form(request, pk):
box = Box.objects.get(pk=pk)
form = SuggestionForm()
context = {
'box':box,
'form':form
}
return render(request, 'boxes/detail.html', context)
forms.py
class SuggestionForm(ModelForm):
class Meta:
model = Suggestion
fields = ['comment']
detail.html
<h3>{{box.title}}</h3>
<form action="." method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" class="btn btn-info" value="Add suggies" />
</form>
My models.py
#python_2_unicode_compatible
class Suggestion(models.Model):
"""
For adding comments (or suggestions)
"""
def __str__(self):
return self.comment[0:10]
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
comment = models.CharField("",max_length=250, blank=True, null=True)
box = models.ForeignKey(Participant, on_delete=models.CASCADE)
created_at = models.DateField(auto_now_add=True)
updated_at = models.DateField(auto_now=True)
The result HTML.. There is no fields in this form. I want to use a function based view.