My models is:
class LabRequest(models.Model):
ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE)
lab_test = models.ManyToManyField(Lab)
My Form
class LabRequestModelForm(forms.ModelForm):
class Meta:
model = LabRequest
fields = ['ticket', 'lab_test']
widgets = {
'lab_test': forms.CheckboxSelectMultiple,
}
My view
def LabRequestToGenerateView(request):
if form.is_valid():
obj = form.save(commit=False)
obj.created_by = request.user.id
obj.save()
return render(request, 'dashboard/laboratory_request.html', {'form': form})
My Template
<form action="." method="POST">
{% csrf_token %}
{{ form.as_p }}
<div class="form-group float-right">
<button type="submit" name="submit" class="btn btn-success btn-sm" > <i
class="fa fa-save"></i>
Save</button>
</div>
</form>
{% for rl in rl %}
<label for=""> Ticket: {{ rl.ticket }} </label>
<p> Lab Tests: {{ rl.lab_test }}</p>
{% endfor %}
So, It's displaying as a checkbox that's good. but when i want to save some data it saves only ticket, not lab_test? So, how do I save both?
As you see it displays only ticket which is Ubed Gedi ALi and where I wanted to see lab_test it shows me appname.modelname.None
Related
I have a function with a formset that needs a product that I take from the id that I pass in the function and of the formset creates 3 boxes to insert the images which I then save, the problem is that if these images are not compiled, the redirect is done anyway while in reality the error should come out. Where is the problem?
view
def product_gallery_create_view(request, id):
ProductGalleryFormset = modelformset_factory(ProductGallery, fields = ('image',), extra = 3)
product = Product.objects.get(id = id)
if request.method == "POST":
formset = ProductGalleryFormset(request.POST, request.FILES)
if formset.is_valid():
for form in formset:
instance = form.save(commit = False)
instance.product = product
instance.save()
return redirect('home')
else:
formset = ProductGalleryFormset()
context = {'formset':formset}
return render(request, 'crud/product_gallery_create.html', context)
model
class ProductGallery(models.Model):
product = models.ForeignKey(Product, on_delete = models.CASCADE, related_name = 'product_gallery')
image = models.ImageField(upload_to ='galleria/', null = False, blank = False)
html
<div class="container mt-3">
<h4>galleria prodotto</h4>
<hr>
{% if formset.errors %}
<div class="alert alert-danger">
{{ formset.errors }}
</div>
{% endif %}
<form method="post" enctype='multipart/form-data' class="notifica" autocomplete="off" novalidate>
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
<div class="d-flex align-item-center justify-content-between">
<div><small>img</small> {{ form.image }}</div>
</div>
<hr class="mt-4 mb-4">
{% endfor %}
<input type="submit" value="crea galleria" class="btn btn-info w-100">
</form>
</div>
I want to add comments form a specific html which has it's own views and models and I do not want to create a new html file like comment.html which will only display the form and its views. I want users to be able to comment right underneath a post, so that users don't have to click a button such as "add comment" which will take them to a new page with the "comment.form" and then they can comment. Basically want a page with all transfer news and their respective comments as well as a comment-form under the old comment. But I'm stuck. I can add comments manually from the admin page and it's working fine, but it seems that I have to create another url and html file to display the comment form and for users to be able to add comments(btw I'm trying to build a sports related website). Thanks in advance!
My models.py:
class Transfernews(models.Model):
player_name = models.CharField(max_length=255)
player_image = models.CharField(max_length=2083)
player_description = models.CharField(max_length=3000)
date_posted = models.DateTimeField(default=timezone.now)
class Comment(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
transfernews = models.ForeignKey(Transfernews, related_name="comments", on_delete=models.CASCADE)
body = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s - %s' % (self.transfernews.player_name, self.user.username)
My forms.py :
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('body', 'transfernews')
My views.py :
def addcomment(request):
model = Comment
form_class = CommentForm
template_name = 'transfernews.html'
def transfer_targets(request):
transfernews = Transfernews.objects.all()
form = CommentForm(request.POST or None)
if form.is_valid():
new_comment = form.save(commit=False)
new_comment.user = request.user
new_comment.save()
return redirect('transfernews/')
return render(request, 'transfernews.html', {'transfernews': transfernews})
My urls.py:
path('transfernews/', views.transfer_targets, name='transfernews'),
My transfernews.html:
<h2>Comments...</h2>
{% if not transfernew.comments.all %}
No comments Yet...
{% else %}
{% for comment in transfernew.comments.all %}
<strong>
{{ comment.user.username }} - {{ comment.date_added }}
</strong>
<br/>
{{ comment.body }}
<br/><br/>
{% endfor %}
{% endif %}
<hr>
<div>Comment and let us know your thoughts</div>
<form method="POST">
{% csrf_token %}
<input type="hidden" value="{{ transfernew.id}}">
<div class="bg-alert p-2">
<div class="d-flex flex-row align-items-start"><textarea class="form-control ml-1 shadow-none textarea"></textarea></div>
<div class="mt-2 text-right"><button class="btn btn-primary btn-sm shadow-none" type="submit">
Post comment</button><button class="btn btn-outline-primary btn-sm ml-1 shadow-none" type="button">Cancel</button></div>
</div>
</div>
</form>
Here's how you can do it :
First, add a field in your CommentForm :
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('body', 'transfernews')
Then in your template, you can set an hidden input in the form to link the comment to the transfernews :
{% if form.errors %}
<p>There are errors in your form :</p>
<ul>{{ form.errors }}</ul>
{% endif %}
<form method="POST">
{% csrf_token %}
{# Add this next line #}
<input type="hidden" value="{{ transfernew.id}}">
<div class="bg-alert p-2">
<div class="d-flex flex-row align-items-start">
<textarea class="form-control ml-1 shadow-none textarea" name="body"></textarea>
</div>
<div class="mt-2 text-right">
<button class="btn btn-primary btn-sm shadow-none" type="submit">Post comment</button>
<button class="btn btn-outline-primary btn-sm ml-1 shadow-none" type="button">Cancel</button>
</div>
</div>
</form>
Then in your view :
def transfer_targets(request):
transfernews = Transfernews.objects.all()
form = CommentForm(request.POST or None)
if form.is_valid():
new_comment = form.save(commit=False)
new_comment.user = request.user
new_comment.save()
return redirect('transfernews')
return render(request, 'transfernews.html', {
'transfernews': transfernews,
'form': form
})
How can I pass data to form fields in django templat ? , for example I have below code in my project:
<td class="col-3">
{{form.number|as_crispy_field}}
</td>
Can I use
<td class="col-3">
{{form.number}} = 10
</td>
in django template ?
#mosi -
<td class="col-3">
{{form.number}} = 10
</td>
No, you cannot use this. If you are planning to pass data from views to template then do something like this
Let's say you have a form something like this
forms.py
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=30)
email = forms.EmailField(max_length=254)
views.py
def home(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
pass # your logic here
else:
form = ContactForm()
return render(request, 'home.html', {'form': form})
template.html
<form method="post" novalidate>
{% csrf_token %}
{{ form.name }}
{{form.email}}
<button type="submit">Submit</button>
</form>
OR
Simply
<form method="post" novalidate>
{% csrf_token %}
{{ form }}
<button type="submit">Submit</button>
</form>
Now, if you want to set initial values to your form in template
Lets say you have the following
class ContactForm(forms.Form):
name = forms.CharField(max_length=30,initial='test')
Then in your template you do something like this
<form method="post" novalidate>
{% csrf_token %}
<input type="text" name="name" id="name" value="{{ form.name.value }}">
<button type="submit">Submit</button>
</form>
Now, in case of an UpdateView where data is pulled in dynamically from the Database based on let's say product id. The following is just an example
class ProductForm(forms.ModelForm):
class Meta:
model = Product
exclude = (
"created_by",
"slug",
)
class ProductUpdateView(UpdateView):
# specify the model you want to use
model = Product
form_class = ProductForm
template_name = "catalog/product/update_product.html"
product_update.html
<form method="post" enctype="multipart/form-data">
<div class="card-body">
{% csrf_token %}
{{ form.as_p}}
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
Or
<form method="post" enctype="multipart/form-data">
<div class="card-body">
{% csrf_token %}
<input type="text" name="name" id="name" value="{{ form.name.value }}">
<input type="text" name="description" id="description" value="{{ form.description.value }}">
.........
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
I am still new to django. Playing around with a leadmanager app and I don't know why my form is not validating.
views
def index(request):
lead=LeadForm()
if request.method == 'POST':
lead=LeadForm(request.POST)
if lead.is_valid():
messages.success(request, f'Thank you for registering. Someone will be contacting you soon.')
return redirect('index')
else:
lead=LeadForm()
messages.error(request, f'Something went wrong. Please try again later.')
return render(request, "frontend/index.html", {'lead':lead})
in index.html
<form action="" method="POST" class="lead-form">
{% csrf_token %}
<fieldset class="lead-info">
<div class="form-control">
<label for="">Full Name</label>
{{ lead.fullname }}
</div>
<div class="form-control">
<label for="">Email</label>
{{ lead.email }}
</div>
<div class="form-control">
<label for="">Phone</label>
{{ lead.phone }}
</div>
<div class="form-control">
<label for="">City</label>
{{ lead.city }}
</div>
</fieldset>
<button type="submit" class="btn-pill">Submit</button>
</form>
in forms.py
class LeadForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = Lead
fields = ['fullname', 'email', 'phone', 'city', 'contact_preference']
widgets = {'contact_preference': forms.RadioSelect }
Any help is appreciated. contact_preference is rendering FYI, I just cut the code to keep this question not that long.
I am trying to set up a contact form. I have implemented the Django-crispy-forms and now my form is not submitted (I don't have any errors).
I've added action="" to my form in my template without any success.
forms.py
class ContactForm(forms.Form):
name = forms.CharField(max_length=100, help_text='Enter your name or username')
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea(attrs={'rows': 3, 'cols': 40}), help_text='Example: I forgot my password!')
views.py
def contact_us(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
sender_name = form.cleaned_data['name']
sender_email = form.cleaned_data['email']
message = "From {0}:\n\n{1}".format(sender_name, form.cleaned_data['message'])
send_mail('PLM_Tool contact', message, sender_email, ['myadress#gmail.com'])
return redirect('home:index')
else:
form = ContactForm()
return render(request, 'accounts/contact.html', {'form': form})
urls.py
app_name = 'accounts'
urlpatterns = [path('contact/', views.contact_us, name='contact'),]
contact.html
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block main %}
<form method="post" action="">
{% csrf_token %}
<div class="row">
<div class="col-6">
{{ form.name|as_crispy_field }}
</div>
<div class="col-6">
{{ form.email|as_crispy_field }}
</div>
<div class="col-6">
{{ form.message|as_crispy_field }}
</div>
</div>
</form>
<button type="submit" class="btn btn-success">Send</button>
Cancel
<br><br>
{% endblock %}
Here is the problem, and do not give action to form
crispy forms create the field not the button.
<form method="post">
{% csrf_token %}
<div class="row">
<div class="col-6">
{{ form.name|as_crispy_field }}
</div>
<div class="col-6">
{{ form.email|as_crispy_field }}
</div>
<div class="col-6">
{{ form.message|as_crispy_field }}
</div>
</div>
<button type="submit" class="btn btn-success">Send</button>
</form>
just add the button inside the form