Hi Everyone I am trying to submit the form in Django. but I am not getting any response in Backend. when I clicked on submit. the form is not getting submitted.
The code
Models
class JobListing(models.Model):
position = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, blank=True)
company_name = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
about_company = models.TextField(blank=True)
description = models.TextField()
city = models.CharField(max_length=250)
job_location = models.CharField(max_length=250)
KeySkill = models.TextField()
eligiblity = models.TextField(blank=True)
resposibility = models.TextField(blank=True)
min_experience = models.FloatField()
max_experience = models.FloatField()
last_date_to_apply = models.DateField(default=timezone.now)
min_salary = models.PositiveIntegerField()
max_salary = models.PositiveIntegerField()
shift_time = models.CharField(max_length=15, choices=shiftDetail)
posted = models.DateField(default=timezone.now)
number_of_position_opening = models.PositiveIntegerField(default=1)
job_post_status = models.IntegerField(default=1, choices=job_post_status)
def save(self, *arg, **kwargs):
if not self.slug:
self.slug = slugify(self.position)
super(JobListing, self).save(*arg, **kwargs)
def __str__(self):
return str(self.position) + " -- " + str(self.company_name)
Form.py
class JobList(forms.ModelForm, forms.Form):
job_location = forms.ModelChoiceField(queryset=CountryAndState.objects.filter(country__isnull=False).distinct())
Key_Skill = forms.ModelMultipleChoiceField(
queryset=skill.objects.all().values_list('name', flat=True).distinct().order_by('name'),
widget=forms.SelectMultiple, required=False, blank=True)
class Meta:
model = JobListing
fields = ['position', 'number_of_position_opening', 'company_name', 'about_company', 'description',
'eligiblity', 'resposibility', 'city',
'job_location', 'KeySkill', 'Key_Skill', 'min_experience', 'max_experience', 'min_salary',
'max_salary', 'shift_time', 'last_date_to_apply']
exclude = ['slug', 'posted']
widgets = {
'KeySkill': forms.TextInput(attrs={'type':'text'}),
'about_company': forms.Textarea(attrs={'rows': 100, 'cols': 15}),
'last_date_to_apply': forms.DateInput(attrs={'type':'date'})
}
def __init__(self, user, *args, **kwargs):
super(JobList, self).__init__(*args, **kwargs)
for field in self.fields.keys():
widget = self.fields[field].widget
if 'cols' in widget.attrs and 'rows' in widget.attrs:
widget.attrs.update({'class': 'form-control pl-15 bg-transparent summernote'})
else:
widget.attrs.update({'class': 'form-control pl-15 bg-transparent'})
widget.attrs['placeholder'] = self.fields[field].label
self.fields[field].required = False
self.fields['company_name'].queryset = User.objects.filter(created_by=user, user_type=4)
View.py
class JobCreateView(LoginRequiredMixin, TemplateView):
template_name = 'Job/Recruiter/PostNewJob.html'
template_name2 = 'Job/RecruiterAgency/PostNewJob.html'
redirect_field_name = 'redirect_to'
def get(self, request, *args, **kwargs):
joblist = JobList(request.user.id)
if request.user.user_type == 2:
return render(request, self.template_name, {"form": joblist})
elif request.user.user_type == 3:
return render(request, self.template_name2, {"form": joblist})
def post(self, request):
job_detail = JobList(request.user.id, request.POST)
field = job_detail.fields.pop('Key_Skill')
if job_detail.is_valid():
job_detail.save()
return redirect('/job/manage_job')
job_detail.fields['Key_Skill'] = field
if request.user.user_type == 2:
return render(request, self.template_name, {"form": job_detail})
elif request.user.user_type == 3:
return render(request, self.template_name2, {"form": job_detail})
template.html
{%extends 'index.html'%}
<body class="hold-transition light-skin sidebar-mini theme-primary">
{%block body%}
<div class="content-wrapper">
<h1>Create New Job</h1>
<div class="">
<form action="" enctype="multipart/form-data" method="post" id="form">
{%csrf_token%}
<div>
{{form.as_p}}
{{form.errors}}
</div>
<button type="submit" class="btn btn-dark" value="Submit" form="form"> Submit </button>
</form>
</div>
I have tried both Submit method with Input tags as well as Button. I tried debugging the code but am not receiving any requests in the backend. submit button is acting like it is disable
You added action as blank in form tag
<form action="" enctype="multipart/form-data" method="post" id="form">
add appropriate url name in form tag
<form action="{% url 'post_url_name' %}" enctype="multipart/form-data" method="post" id="form">
Related
I tried to add comments with the post and it raise this error, and I supmit my comment using ajax but it seems the problem coming from the view but I couldn't figure out what exactly the problem
My add comments View
#login_required
def add_comment_post(request):
comment_form = PostCommentForm(request.POST)
if comment_form.is_valid():
user_comment = comment_form.save(commit=False)
user_comment.author = request.user
user_comment.save()
result = comment_form.cleaned_data.get('content')
user = request.user.username
return JsonResponse({'result': result, 'user': user})
My comment Model
class PostCommentIDF(MPTTModel):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='pos_com')
parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='post_children')
author = models.ForeignKey(Account, on_delete=models.CASCADE)
content = models.TextField()
publish = models.DateTimeField(auto_now_add=True)
status = models.BooleanField(default=True)
likes = models.ManyToManyField(Account, blank=True, related_name='pos_com')
class MPTTMeta:
order_insertion_by = ['-publish']
def __str__(self):
return f'{self.author}---{self.content[:15]}'
My form for the comments
class PostCommentForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class Meta:
model = PostCommentIDF
fields = {'post', 'content'}
widgets = {
'content': forms.Textarea(attrs={'class': 'rounded-0 form-control', 'rows': '1', 'placeholder': 'Comment', 'required': 'True'})
}
def save(self, *args, **kwargs):
PostCommentIDF.objects.rebuild()
return super(PostCommentForm, self).save(*args, **kwargs)
the comments form in the template
<form id="Postcommentform" class="Postcommentform" method="post" style="width: 100%;">
{% load mptt_tags %}
{% csrf_token %}
<select class="d-none" name="video" id="id_video">
<option value="{{ video.id }}" selected="{{ video.id }}"></option>
</select>
<div class="d-flex">
<label class="small font-weight-bold">{{ comments.parent.label }}</label>
{{ comment_form.parent }}
{{comments.content}}
<button value="Postcommentform" id="Postnewcomment" type="submit" style="color: white; border-radius: 0;" class="d-flex justify-content-end btn btn-primary">Post</button>
</div>
</form>
When form is not valid your the codes under your if statement will not execute so your function will return None instead of an HttpResponse.
You should handle it with in a esle statement for example:
#login_required
def add_comment_post(request):
comment_form = PostCommentForm(request.POST)
if comment_form.is_valid():
user_comment = comment_form.save(commit=False)
user_comment.author = request.user
user_comment.save()
result = comment_form.cleaned_data.get('content')
user = request.user.username
return JsonResponse({'result': result, 'user': user})
else:
return JsonResponse({'result': "form is not valid"})
Working on my first Django project! I have an UpdateView and I want to limit the dropdown results of program_code so it only shows items that the user owns. I think I have to pass kwargs to the view to limit the queryset but not sure where to begin or how to go about doing that. Any advice would be greatly appreciated.
View:
class ContactsUpdateView(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, UpdateView):
model = Contact
fields = ['first_name1', 'last_name1','address1','address2','city','province','postal_code','country','active_status','program_code']
template_name = 'contacts/contacts_form.html'
success_message = "Contact was updated successfully"
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
contact = self.get_object()
if self.request.user == contact.author:
return True
return False
model:
class Contact(models.Model):
first_name1 = models.CharField(max_length=100, verbose_name='First Name', null=True)
last_name1 = models.CharField(max_length=100, verbose_name='Last Name', null=True)
address1 = models.CharField(max_length=100, verbose_name='Address 1', null=True)
address2 = models.CharField(max_length=100, verbose_name='Address 2', null=True, blank=True)
city = models.CharField(max_length=100, verbose_name='City', null=True)
province = models.CharField(max_length=2, choices=PROVINCE_CHOICES, default='Ontario', verbose_name='Province')
postal_code = models.CharField(max_length=7, verbose_name='Postal Code', null=True)
country = models.CharField(max_length=100, verbose_name='Country', null=True, default='Canada')
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
active_status = models.BooleanField(default=True)
program_code = models.ForeignKey(Program, on_delete=models.CASCADE)
def __str__(self):
return self.first_name1 + ' ' + self.last_name1
def get_absolute_url(self):
return reverse('contacts-home')
template form:
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-2 mt-2">Update Contact</legend>
<p>Created by: {{ object.author }}, Last Updated: {{ object.date_posted }}</p>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-info" type="submit">Update</button>
<div class="mt-4"><a class="btn btn-outline-danger btn-sm" href="{% url 'contacts-delete' object.id %}" role="button">Delete Contact</a></div>
</div>
</form>
You can try like this:
# form
class ContactForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None) # This will be sent from View
super(ContactForm, self).__init__(*args, **kwargs)
self.fields['program_code'].queryset = Program.objects.filter(owner=user)
class Meta:
model = Contact
fields = ['first_name1', 'last_name1','address1','address2','city','province','postal_code','country','active_status','program_code']
#view
class ContactsUpdateView(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, UpdateView):
model = Contact
from_class = ContactForm
template_name = 'contacts/contacts_form.html'
success_message = "Contact was updated successfully"
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def get_form_kwargs(self):
# Sending user information to Form
kwargs = super(ContactsUpdateView, self).get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs
Here in the View, we are overriding the get_form_kwargs method to pass current user information to the Form. And inside the form, we are overriding the __init__ method to catch the user data sent from View, and use it to override default queryset value of the field program_code.
I'm uploading images, and they appear inside the Static / Media folder
but I can not show these images inside the perfil.html
and using the shell of the error:
Erro:
name 'user' is not defined
but I'm logged in because the other options that user needs logged in as they are working like:
views.py
def gallery(request):
gallery = Gallery.objects.all()
form = GalleryForm()
data = {'gallery': gallery, 'form': form}
return render(request, 'gallery.html', data)
def gallery_novo(request):
if request.method == 'POST':
form = GalleryForm(request.POST, request.FILES)
if form.is_valid():
my_novo_gallery = form.save(commit=False) #save no commit
my_novo_gallery.user=request.user #set user
my_novo_gallery.save() #save to db
return redirect('sistema_perfil')
else:
form = GalleryForm
return render(request, 'gallery.html', {'form': form})
def perfil(request):
usuario = Usuario.objects.all()
form = UsuarioForm()
data = {'usuario': usuario, 'form': form}
gallery = Gallery.objects.all()
form2 = GalleryForm()
data2 = {'gallery': gallery, 'form2': form2}
return render(request, 'perfil.html', data, data2)
models.py
class Usuario(models.Model):
nome = models.CharField(max_length=50, blank=False)
sobrenome = models.CharField(max_length=50, blank=False)
user = models.OneToOneField(User, on_delete=models.CASCADE)
email_confirmed = models.BooleanField(default=False)
email = models.EmailField(blank=False)
foto = StdImageField( blank=False, variations={
'large': (600, 400),
'thumbnail': (100, 100, True),
'medium': (300, 200),
})
telefone = models.CharField(max_length=20, blank=False, verbose_name="Celular")
cpf = models.CharField(max_length=19)
data_nascimento = models.CharField(max_length=8, blank=False, verbose_name="Data de nascimento")
sexo = models.CharField(default='M', max_length=2, choices=SEXO_CHOICES)
pet = MultiSelectField( max_length=100, choices=PET_CHOICES, verbose_name="Selecione seus pets")
endereco = models.CharField(max_length=50)
numero = models.CharField(max_length=10)
bairro = models.CharField(max_length=30)
cep = models.CharField(max_length=25)
cidade = models.CharField(max_length=30)
estado = models.CharField(default='RS', max_length=3, choices=STATE_CHOICES)
password1 = models.CharField(max_length=15, blank=False)
about = models.TextField(max_length=1000, blank=False, verbose_name="Sobre vocĂȘ")
def __unicode__(self):
return self.nome
#receiver(post_save, sender=User)
def cadastro_novo(sender, instance, created, **kwargs):
if created:
Usuario.objects.create(user=instance)
instance.usuario.save()
def __str__(self):
return str(self.nome) + ' - ' + str(self.email) + ' - ' + str(self.telefone)
class Gallery(models.Model):
gallery = StdImageField( blank=False, variations={
'large': (600, 400),
'thumbnail': (100, 100, True),
'medium': (300, 200),
})
titulo = models.CharField(max_length=50, blank=False)
usuario_id = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
forms.py
class GalleryForm(forms.ModelForm):
gallery = forms.FileField(
widget=forms.ClearableFileInput(attrs={'multiple': 'True'}))
titulo = forms.CharField()
class Meta:
model = Gallery
fields = ( 'gallery', 'titulo')
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
return super(GalleryForm, self).__init__(*args, **kwargs)
def save(self, commit=True, user=None):
form = super(GalleryForm, self).save(commit=False)
form.usario_id = user
if commit:
form.save()
return form
gallery.html
{%extends 'bases/base.html' %}
{% load static %}
{% load bootstrap %}
{% load widget_tweaks %}
{% load crispy_forms_tags %}
{% block main %}
<form class="exampleone" action="{% url 'sistema_gallery_novo' %}" method="POST" enctype="multipart/form-data" id="form" name="form" validate >
{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-4">
{{ form.gallery | as_crispy_field }}
</div>
<div class="form-group col-md-4">
{{ form.titulo | as_crispy_field }}
</div>
<div class="form-group col-md-4">
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block">Cadastrar</button>
</form>
</div> </div>
<div>
{% endblock %}
urls.py
url(r'gallery/$', gallery, name='sistema_gallery'),
url(r'gallery-novo/$', gallery_novo, name='sistema_gallery_novo'),
url(r'perfil/$', perfil, name='sistema_perfil'),
perfil.html
{% for g in user.usuario.gallery_set.all %}
<img src="{{ g.medium.url}}">
{% endfor %}
I'm trying to save multiple Images and his parent's data together on the same template.
I have one parent's model(to save normal data) and child's model(to save images). In this case, saving parent's data is working very well. but images are not work.
There isn't any error message.
//model
class QuotationPanchok(models.Model):
whose = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=50, help_text='', default='')
many = models.IntegerField(default='1', help_text='')
design = models.CharField(max_length=3, choices=(('yes', 'yes'), ('no', 'no'),))
sian = models.CharField(max_length=3, choices=(('yes','yes'), ('no', 'no'),))
havefile = models.CharField(max_length=3, choices=(('yes','yes'), ('no', 'no'),))
deadline = models.DateField(blank=True)
addressto = models.CharField(max_length=50, default='', help_text='')
fulltext = models.TextField(max_length=150, blank=True)
status = models.CharField(max_length=7, choices=(('not','not'), ('finish', 'finish'),), default='not')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
class ImagesForQuotation(models.Model):
whose = models.ForeignKey(QuotationPanchok, on_delete=models.CASCADE)
image = models.ImageField(upload_to='images/', blank=True, null=True)
def __str__(self):
return self.whose.title + " Image"
// views
def quotation_create(request):
ImageFormset = modelformset_factory(ImagesForQuotation, fields=('image',), extra=4)
if request.method == 'POST':
form = QuotationCreateForm(request.POST)
formset = ImageFormset(request.POST or None, request.FILES or None)
if form.is_valid() and formset.is_valid():
post = form.save(commit=False)
post.whose = request.user
post.save()
for f in formset:
try:
photo = ImagesForQuotation(whose=post, image=f.cleaned_date['image'])
photo.save()
except Exception as e:
break
return redirect('index')
else:
form = QuotationCreateForm()
formset = ImageFormset(queryset=ImagesForQuotation.objects.none())
context = {
'form': form,
'formset': formset,
}
return render(request, 'quotationapp/quotation_create.html', context)
//forms
class QuotationCreateForm(forms.ModelForm):
class Meta:
model = QuotationPanchok
fields = (
'title',
'many',
'design',
'sian',
'havefile',
'deadline',
'addressto',
'fulltext',
)
def __init__(self, *args, **kwargs):
super(QuotationCreateForm, self).__init__(*args, **kwargs)
for field_name, field in self.fields.items():
field.widget.attrs['class'] = 'form-control'
//template(quotation_create.html)
{% block content %}
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
{{ formset.as_table }}
<input type="submit" class="btn btn-primary" value="">
</form>
{% endblock %}
How can I solve this problem?
Thank you..
I want to let users to add/update caption of their already updated photos without changing any other field of the photo.
Here is the model:
class UserPic(models.Model):
user = models.ForeignKey(User, unique=False)
picfile = ImageWithThumbsField(upload_to= get_uplaod_file_name, sizes=((648,648),(200,200),(1200,1200)))
caption = models.CharField(max_length=200 , blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
likes = models.IntegerField(default=0)
liked_by= models.ForeignKey(Liker, blank=True)
#models.permalink
def get_absolute_url(self):
return ('view_pirate', None, {'user': self.account.user})
def __unicode__(self):
return unicode(self.picfile.name)
views.py
def edit_photo(request, pic_id):
pic = UserPic.objects.get(id=pic_id)
if request.method == 'POST':
if pic.user== request.user:
picform = CaptionForm(request.POST)
if picform.is_valid():
edform = picform.save(commit=False)
edform.caption = request.POST['caption']
edform.save()
message = "caption is uploaded"
else:
edform = CaptionForm()
args = {}
args.update(csrf(request))
args['pic'] = pic
args['pic_id'] = pic_id
#args['form'] = edform
return render_to_response('userpics/photo.html', args,
context_instance= RequestContext(request))
photo.html
<div class="caption">
<form action="{% url "userpics.views.edit_photo" pic.id %}" method="POST">
{% csrf_token %}
{{form.as_ul}}
<input type="submit" value="SEND">
</form>
forms.py:
class CaptionForm(forms.ModelForm):
class Meta:
model= UserPic
fields = ('caption',)
However when I post the form, django still complain that:
MultiValueDictKeyError at /pics/edit/26
"'caption'"
I really got confused as I could not find any resources to deal with this particular problem. So appreciate your hints.
Ok I managed to solved the problem like this:
photo.html
<form action="{% url "userpics.views.edit_photo" pic.id %}" method="POST">
{% csrf_token %}
<input type="text" name="caption" value="{{pic.caption}}">
<input type="submit" value="SEND">
</form>
views.py
def edit_photo(request, pic_id):
pic = UserPic.objects.get(id=pic_id)
if request.method == 'POST':
if pic.user== request.user:
picform = CaptionForm(request.POST)
if picform.is_valid():
pic.caption = request.POST['caption']
pic.save()
message = "caption is uploaded"
else:
edform = CaptionForm(instance=pic)
args = {}
args.update(csrf(request))
args['pic'] = pic
args['pic_id'] = pic_id
return render_to_response('userpics/photo.html', args,
context_instance= RequestContext(request))