I'm making an Inventory Management System, which now I'm trying to make my form input more efficient.
I have 2 tables of Arrival and Withdraw
In table Arrival there are prod_cd , prod_nm, ..., withdraw
In table Withdraw there are prod_cd, prod_nm, withdraw
I want to make my form only input the prod_cd and then the field of prod_nm and withdraw would automatically retrieved from the Withdraw table
I've try to make another page so there will be Inquiry first to retrieve the Withdraw.objects, and then Add the record but it throw an error
views.py
def add_cycle(request, model, cls, inquiry):
if request.method == "POST":
form = cls(request.POST)
if form.is_valid():
form.save()
return redirect(inquiry)
else:
form = cls()
return render(request, 'add_new.html', {'form': form})
def add_arrival(request):
return add_cycle(request, Arrival, ArrivalForm, inquiry_arrival)
def inquiry_cycle(request, pk, model, cls):
instance= Withdraw.objects.get(pk=pk)
form = cls(instance=instance)
if request.method == "POST":
form = cls(request.POST,instance=instance)
if form.is_valid():
form.save(commit=True)
return redirect ('index')
else:
form = ArrivalForm(instance=instance)
return render_to_response('add_newInquiry.html', {'form': form})
def inquiry_arrival (request, pk):
return inquiry_cycle(request, pk, Arrival, ArrivalForm)
urls.py
url(r'^add_arrival$', add_arrival, name='add_arrival'),
url(r'^inquiry_arrival$', inquiry_arrival, name='inquiry_arrival'),
forms.py
class ArrivalForm(forms.ModelForm):
class Meta:
model = Arrival
fields = ('prod_cd', 'prod_nm', 'quantity', 'issues', 'location', 'withdraw', 'expired_date', 'sup_sheet')
add_new.html
<form method="POST">
<br>
{% csrf_token %}
<h4>ADDING ITEMS</h4>
<div class="form-group row">
<label for="id_{{ form.prod_cd.name }}" class="col-2 col-form-label"> {{ form.prod_cd.label }} </label>
<div class="col-10">
{{ form.prod_cd }}
</div>
</div>
<button type="submit" class="btn btn-primary" name="button"> Inquiry</button>
</form>
add_newInquiry.html
<form method="POST">
<br>
{% csrf_token %}
<h4>ADDING ITEMS</h4>
{% for field in form %}
<div class="form-group row">
<label for="id_{{ field.name }}" class="col-2 col-form-label"> {{ field.label }} </label>
<div class="col-10">
{{ field }}
</div>
</div>
{% endfor %}
<button type="submit" class="btn btn-primary" name="button"> Add Record</button>
</form>
I expect my form would retrieve some of it fields value from database, but I still got an error
ValueError at /add_arrival
The view inventory.views.add_arrival didn't return an HttpResponse object. It returned None instead.
Let's trace the error together! So, The view inventory.views.add_arrival didn't return an HttpResponse object. It returned None instead. What this means is that when Django attempts to fetch the add_arrival view, no templates are returned.
Let's take a further look at add_arrival view. It calls the function add_cycle. Pay attention to the last parameter inquiry_arrival, which is a method.
Now, in the add_cycle function, if the form is valid, we return redirect(inquiry) where inquiry is the inquiry_arrival method. However, since inquiry is a method, it needs to be called for something to be returned! To call this method, you should have added brackets behind inquiry, like so: redirect(inquiry()). Refer to this link for further information. Good luck!
Related
im getting this error as_crispy_field got passed an invalid or inexistent field
every time im trying to use as_crispy_field with forms
here is my code
models.py
class Customer_Email(models.Model):
subject=models.CharField(max_length=50,null=True,blank=True)
message=models.TextField(max_length=1000,null=True,blank=True)
file_upload=models.FileField(null=True,blank=True)
sender=models.ForeignKey(User,on_delete=models.CASCADE ,null=True,blank=True)
company=models.ForeignKey(Customer,on_delete=models.CASCADE ,null=True,blank=True)
date=models.DateTimeField(auto_now=True)
views.py
def send_email(request,id):
customer=get_object_or_404(Customer,pk=id)
form=Customer_Email_Form(request.POST)
customers=Customer.objects.all()
context={"customer":customer,"email_form":form,"customers":customers}
if request.method == 'GET':
return render(request,'crm/email_form.html',context)
if request.method=='POST':
if form.is_valid():
form.save()
messages.success(request,"Email Sent")
return render(request,'crm/listing.html',context)
return render(request,'crm/email_form.html',context)
html
{% load crispy_forms_tags %}
<form class="" method="POST">
{% csrf_token %}
<div class="form-group m-2">
<label>Subject</label>
{{email_form.subject|as_crispy_field}}
</div>
<div class="form-group m-2">
<label>Message</label>
{{email_form.message|as_crispy_field}}
</div>
<div class="form-group m-2">
<label>Uplaod</label>
{{email_form.file_upload|as_crispy_field}}
<span class="color-secondary">you can attach 2M files (pdf,doc)</span>
</div>
{{email_form.company|as_crispy_field}}
{{email_form.sender|as_crispy_field}}
<button
class="btn btn-primary btn-lg mt-5"
type="submit"
hx-post="email_form/p={{customer.id}}"
hx-target="#crm-list"
data-dismiss="modal"
>Send Email <i class='bx bx-mail-send bx-xl'></i></button>
</form>
forms.py
class Customer_Email_Form(forms.ModelForm):
class Meta:
model=Customer_Email
fields=['subject','file_upload','message','sender','company']
i have tried to change it to forms.Form but it gives me the same error i dont know what excactly i should do and im new to it
Try this...
def send_email(request,id):
customer=get_object_or_404(Customer,pk=id)
form=Customer_Email_Form()
customers=Customer.objects.all()
context={"customer":customer,"email_form":form,"customers":customers}
if request.method == 'GET':
return render(request,'crm/listing.htm.html',context)
if request.method=='POST':
form=Customer_Email_Form(request.POST)
if form.is_valid():
form.save()
messages.success(request,"Email Sent")
return render(request,'crm/listing.html',context)
return render(request,'crm/listing.html',context)
You were passing POST data to your form before any was sent, and then rendering the form. I find it easier/clearer to restructure as such:
def send_email(request,id):
if request.method=='POST':
form=Customer_Email_Form(request.POST)
if form.is_valid():
form.save()
messages.success(request,"Email Sent")
return redirect('send_email', id)
else:
messages.error(request, form.errors)
return redirect('send_email', id)
else:
customer=get_object_or_404(Customer,pk=id)
form=Customer_Email_Form()
customers=Customer.objects.all()
context={"customer":customer,"email_form":form,"customers":customers}
return render(request,'crm/listing.html',context)
Assuming that you have imported redirect and your url name in urls.py is 'send_email'.
I was creating a post based website i want to show the author's name to show up in the post it works in the admin site when adding posts but when i try uploading a post from the site the form is not getting validated therefore it is not getting saved please help
model :
from django.conf import settings
class MemeImg(models.Model):
Title = models.CharField(max_length=500)
op = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None, blank=True, null=True)
date_created = models.DateTimeField(auto_now_add=True)
Post_Img = CloudinaryField('Post')
forms :
class PostImg(forms.ModelForm):
class Meta:
model = MemeImg
fields = ['Title', 'op', 'Post_Img']
view :
#login_required(login_url='/login')
def post(request):
func = data(request)
if request.method == 'POST':
form = PostImg(request.POST, request.FILES, instance=request.user)
form.op = request.user
if form.is_valid():
print('success')
posts = form.save(commit=False)
posts.op = request.user
form.save()
return HttpResponseRedirect('https://youtu.be/dQw4w9WgXcQ')
else:
print("fail")
form = PostImg(request)
ctx = {
'form': form,
'url': func[0],
'name': func[1],
'date': func[2],
}
return render(request, 'Post.html', ctx)
and finally the post page template :
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="container">
{{ form.Title|materializecss }}
<div class="file-field input-field">
<div class="btn">
<span>File</span>
<input type="file">
</div>
<div class="file-path-wrapper">
{{ form.Post_Img }}
<input class="file-path validate" type="text">
</div>
</div>
<button class="btn waves-effect waves-light" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</div>
</form>
If anymore code is required please comment it
Thanks a lot
I think your problem come from the form instance which is instance=request.user, actually the instance is supposed to be the MemeImg object instance and not the user, that's making it not to save the image. So i have deleted the instance and also i don't know what you are using those extra context variable for 'url': func[0],'name': func[1], 'date': func[2] ?, so i deleted them too keep things simple. Now i think you should be able to save without any Issues.
#login_required(login_url='/login')
def post(request):
if request.method == 'POST':
form = PostImg(request.POST, request.FILES)
if form.is_valid():
print('success')
data = form.save(commit=False)
data.op = request.user
form.save()
return HttpResponseRedirect('https://youtu.be/dQw4w9WgXcQ')
else:
print("fail")
form = PostImg(request.POST)
ctx = {
'form': form,
}
return render(request, 'Post.html', ctx)
Also your form had in it {{ form.Post_Img }} which i don't no what you are looking to accomplish with that variables?, the right way is doing {{ form.as_p }} or simply just calling the form like this {{ form }} so i have made the correction in you HTML
too.
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="container">
{{ form.Title|materializecss }}
<div class="file-field input-field">
<div class="btn">
<span>File</span>
<input type="file">
</div>
<div class="file-path-wrapper">
{{ form }}
<input class="file-path validate" type="text">
</div>
</div>
<button class="btn waves-effect waves-light" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</div>
</form>
i have created a form for product table. I included values from multiple table in dropdown box. whenever i finish filling form and clicking submit, it throws me a error of UnboundLocalError. and it also says local variable 'c' referenced before assignment.i didn't understand what mistake i did and I'm new to django environment.
model.py
class Products(models.Model):
pname=models.CharField(max_length=120)
pcode=models.CharField(max_length=120)
category=models.CharField(max_length=120)
brand=models.CharField(max_length=120)
supplier=models.CharField(max_length=120)
description=models.CharField(max_length=120)
class Meta:
db_table="products"
forms.py:
class ProductForm(forms.ModelForm):
pname=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
pcode=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
category=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
brand=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
supplier=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
description=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
class Meta:
model=Products
fields="__all__"
views.py:
def addproduct(request):
if request.method == "POST":
form = ProductForm(request.POST)
if form.is_valid():
try:
form.save()
return redirect(show_products)
except Exception as e:
raise e
else:
form = ProductForm()
c=Category.objects.all()
b=Brand.objects.all()
return render(request,'addproduct.html',{'form':form,'c':c,'b':b})
addproduct.html:
<form method="POST" action="addproduct">
{% csrf_token %}
<div class="form-group">
<label>Product Code:</label>
{{form.pcode}}
</div>
<div class="form-group">
<label>Category:</label>
<select class="form-control" name='category' required='' id='id_category' >
{% for cat in c %}
<option value='{{cat.id}}'> {{cat.cname}}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label>Brand:</label>
<select class="form-control" name='brand' required='' id='id_brand' >
{% for bra in b %}
<option value='{{bra.id}}'> {{bra.bname}}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label>Supplier:</label>
{{form.supplier}}
</div>
<div class="form-group">
<label>Product Name:</label>
{{form.supplier}}
</div>
<center> <button class="btn btn-outline-success" type="submit">Submit</button></center>
</form>
When you submit the form the request is POST and b, c variable can't assign value. That why the error throws.
Try this
def addproduct(request):
if request.method == "POST":
form = ProductForm(request.POST)
if form.is_valid():
try:
form.save()
return redirect('show_products')
except Exception as e:
raise e
else:
form = ProductForm()
c=Category.objects.all()
b=Brand.objects.all()
return render(request,'addproduct.html',{'form':form,'c':c,'b':b})
In urls.py change this path('show_products',views.show_products) to
path('show_products',views.show_products, name='show_products')
My form looks like this:
class Form(forms.Form):
smth = forms.ChoiceField(label='Smth', choices=[(x, x) for x in my_settings.measurements])
def clean_smth(self):
smth = self.cleaned_data['smth']
problem_condition = some_convoluted_process(smth)
if problem_condition:
raise ValidationError("this sucks")
return smth
My view has this:
if request.method == 'POST':
try:
form = Form(request.POST)
except ValidationError as e:
pass
else:
if form.is_valid():
form.save()
return redirect('this_current_page')
else:
form = Form()
I'm using custom validation for the form.
In an ideal world, the user would submit the form and be redirected to the same exact page. If there were an error, the user would be on the same page but the error would be listed below the form. Instead, the error (inserted by the exception ValidationError) ends up in the middle of the form, creating an ugly line break. I've tried many ways to format / handle ValidationError in the template, to no avail.
I want to do this all on the same page; not have some annoying separate page that the user is redirected to in case of error. It's easier to just correct the form in situ than to see the fault on another page, press back, and try again.
How can I have the error printed prettily on the same template, when the error comes from raising the exception? I am using raise ValidationError because the examples I find online about custom form validation say to use an exception when things go awry with that validation.
if request.method == 'POST':
if form.is_valid():
form.save()
return redirect('this_current_page')
else:
print('Error: form invalid')
# you can alert the user here with django message framework for example
else:
form = Form()
forms.py
class YourForm(forms.Form):
def clean(self):
cleaned_data = super(YourForm,self).clean()
smth = cleaned_data.get('smth')
if some_convoluted_process(smth): # Depending of what your function does
self.add_error("smth","this sucks")
return cleaned_data
With the following, you are free to handle the form the way you want rather than: {{form}} , {{form.as_p}}, {{form.as_table}}
<div id="trigger_form" class="container">
<h4>Create Alert Trigger</h4>
<form action="/triggers/{{ stationid }}/" class="form" method="post">
{% csrf_token %}
<div class="row">
<div class="col-sm-12">
<label class="control-label" for="{{form.meas_type.id_for_label}}">Meas Type *</label>
{% if form.meas_type.errors %}
<label class="color-red">
{{form.meas_type.errors.as_text}}</i>
</label>
{% endif %}
{{ form.meas_type }}
</div>
</div>
<div class="row">
<div class="col-sm-12">
<label class="control-label" for="{{form.trig_type.id_for_label}}">Trig Type *</label>
{% if form.trig_type.errors %}
<label class="color-red">
{{form.trig_type.errors.as_text}}</i>
</label>
{% endif %}
{{ form.trig_type }}
</div>
</div>
</form>
</div>
I am trying to authenticate a user(using the simple authenticate() function) in django.
def auth(request):
if request.method == 'POST':
auth_form = AuthenticationForm(request.POST)
if auth_form.is_valid():
auth_form.save()
user = authenticate(username=request.POST['id_username'],password=request.POST['id_password'])
if user is not None:
login(request,user)
return redirect('/profile/home/')
else:
return redirect('/')
else:
return redirect('/')
def register(request):
if request.method == 'POST':
form = SimpleUserCreation(request.POST)
if form.is_valid():
form.save()
user = authenticate(username=request.POST['id_username'],password=request.POST['id_password1'])
login(request,user)
return redirect('/profile/home/')
else:
return redirect('/')
This is the template displaying the forms - Just wanted to display login and register forms in the same page(for this example)
{% extends 'base.html' %}
{% load bootstrap_toolkit %}
{% block content %}
<div class="row">
<div class="span4 offset1 login">
<form class="form-signin" action="/auth/" method="POST">
{% csrf_token %}
{{ auth_form|as_bootstrap }}
<br>
<center>
<button class="btn btn-large btn-primary" type="submit">
Sign In
</button>
</center>
</form>
</div>
<div class="span4 offset2 signup">
<form action="/register/" method="POST">
{% csrf_token %}
{{ form|as_bootstrap }}
<br>
<center>
<button class="btn btn-large btn-primary" type="submit">
Register
</button>
</center>
</form>
</div>
</div>
{% endblock %}
I am getting an error like this:
ValueError at /auth/
The view SimpleUserAuth.auth.views.auth didn't return an HttpResponse object.
Any idea where i am going wrong?? I think its the authenticating function's inability to find the correct id for the fields...maybe i am wrong. I am a Noob :|
Cheers
In your auth method, if auth_form.is_valid() returns False, you do not return a response object.
The same is the case in def register(request): . If it is a GET request, the method does not return a response object.
Hence the error(s)
I made the mistake in these lines -
1) AuthenticationForm takes argument as follows:
AuthenticationForm(data=request.POST)
2) u can't save AuthenticationForm.
auth_form = AuthenticationForm(request.POST)
if auth_form.is_valid():
auth_form.save()
Thanks for the help karthik :)