as_crispy_field got passed an invalid or inexistent field - django

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'.

Related

User form foreignkeyfield form not valid

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>

Django form not submitting in POST

Been having an issue where I am unable to upload files into my form. From what I can gather on my own, it's because I'm not submitting in POST (since uploaded files aren't saved unless you're in POST) but I don't know why that's the case. Here's my code:
Views.py
def commission(request):
if request.method == "POST":
form = CommissionForm(request.POST)
if form.is_valid():
subject = str(form.cleaned_data.get("name")) + "'s commission request"
message = form.cleaned_data.get("name") + ",\nhas requested a commission, with the following request:\n" + form.cleaned_data.get("request") + "\n Reply to them using their email:\n" + form.cleaned_data['email']
email = form.cleaned_data['email']
print(form.cleaned_data)
attach = request.FILES['reference']
try:
mail = EmailMessage(subject, message, settings.EMAIL_HOST_USER, [email])
if attach != None:
mail.attach(attach.name, attach.read(), attach.content_type)
mail.send()
return redirect("main-commissions-success")
except:
return render(request, "main/commissions.html", {"form": form})
return render(request, "main/commissions.html", {"form": form})
else:
form = CommissionForm()
return render(request, "main/commissions.html", {"form": form})
Commissions.html
<div class="row">
<div class="content-section card w-50 mx-auto my-5">
<div class="card-body">
<form method="POST" action="" class="border border-light m-10" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4 text-center">Request A Painting</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group text-center">
<button class="btn btn-outline-info" type="submit">Send Request</button>
</div>
</form>
</div>
</div>
</div>
And since this has no model relation, I'm not going to bother adding it here. Hopefully someone can help point out whatever dumb mistake I've made lol.
I figured out what went wrong so, for anyone else with a similar issue, I had forgotten to request the files from the post request. So this:
if request.method == "POST":
form = CommissionForm(request.POST)
is meant to be this:
if request.method == "POST":
form = CommissionForm(request.POST, request,FILES)
in order to access your files.

whenever i click submit button i get unboundLocalError and local variable 'c' referenced before assignment

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')

How to retrieve row from database by matching form field

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!

Django - How to Authenticate users while logging in (or) registering while using django-bootstrap-toolkit?

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 :)