I have a Candidat models and Experience_Pro models as shown below with fk relation between them .
i can register or login a candidat(user) and a profil page with firstname and lastname of that candidat shown, and a form for Experience_Pro for the user to add if he does have one .
but when i enter all the info in the Experience_Pro form and click update nothing is added to candidat
I don't know what i am missing but the form is showing with no errors and even after i update the profile no errors but nothing is saved to candidat
models.py
class Candidat(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
experience_Pro = models.ForeignKey('Experience_Pro' ,on_delete=models.CASCADE,blank=True,
null=True,default='')
class Experience_Pro(models.Model):
annee_debut = models.IntegerField()
annee_fin = models.IntegerField()
description_exp_pro = models.TextField(null=True,blank=True)
forms.py
class UpdateCandidat(forms.ModelForm):
class Meta:
model=Candidat
fields=['experience_Pro']
class CreateExperience_Pro(forms.ModelForm):
class Meta:
model=Experience_Pro
fields='__all__'
views.py
#login_required
def profil(request):
exp_form = CreateExperience_Pro()
c_form = UpdateCandidat()
if exp_form.is_valid():
exp = exp_form.save()
candidat = c_form.save(commit=False)
candidat.save(experience_Pro=exp)
return redirect('profil')
context={
'exp_form':exp_form
}
return render(request ,'candidats/profil.html',context)
profil.html
<h1>Profil Candidat</h1>
<p>Prenom: {{ user.first_name }}</p>
<p>Nom: {{ user.last_name }}</p>
<p>Email: {{ user.email }}</p>
<form method="POST" action="">
{% csrf_token %}
{% comment %} {{ c_form }} {% endcomment %}
{{ exp_form }}
<input type="submit" value="Update">
</form>
You need to do some update:
#login_required
def profil(request):
if request.method == 'POST':
exp_form = CreateExperience_Pro(request.POST)
c_form = UpdateCandidat(request.POST)
if exp_form.is_valid() and c_form.is_valid():
exp = exp_form.save()
candidat = c_form.save()
return redirect('profil')
else:
context = {
'exp_form': exp_form,
'c_form': c_form,
}
return render(request, 'candidats/profil.html', context)
else:
exp_form = CreateExperience_Pro()
c_form = UpdateCandidat()
context = {'exp_form': exp_form, 'c_form': c_form}
return render(request, 'candidats/profil.html', context)
Related
i am trying to filter a forms drop down list based on a users group
To find the user group i am using a custom templatetag
template tag
from django import template
register = template.Library()
#register.filter(name='in_group')
def in_group(user,group_name):
try:
group=Group.objects.get(name=group_name)
except Group.DoesNotExist:
return False
return group in user.groups.all()
task.html
{% load group_check %}
<form method="post">
{% csrf_token %}
{% if user.is authenticated %}
{% if requset.user|in_group:'DEVELOPER' %}
#...DO SOMETHING
{{ form.as_p }}
<button type="submit">add task</button>
</form>
models
GOALS_TYPE= (('DT','Daily Task'),
('WT','Weekly Task'),
('V','Verified'),
('D','Done'),
)
class GoalStatus(models.Model):
title = models.CharField(max_length=254, null=True)
task_id=models.IntegerField(default=1,null=False)
description =models.CharField(max_length=254)
verified_by=models.ForeignKey('ScrumyUser', on_delete= models.CASCADE, null=True)
status=models.CharField(choices=GOALS_TYPE, max_length=2, default='DT')
def __str__(self):
return self.title
the template for the form is based on the forms.py
forms.py
class ChangeTaskForm(forms.ModelForm):
class Meta:
model = GoalStatus
fields = ('title', 'task_id','description','status', 'verified_by')
views.py
def move_goals(request,pk):
if request.method == 'POST':
form = ChangeTaskForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/index/')
else:
form = ChangeTaskForm()
return render(request, 'oderascrumy/task.html', {'form': form})
urls.py
path('task/<pk>/', views.move_goals, name='move_goals')
so for example if the user is in group "developer", the drop down choices for status will be only verified and done
You can do like below
views.py
def move_goals(request,pk):
if request.method == 'POST':
form = ChangeTaskForm(request.POST, user=request.user)
if form.is_valid():
return HttpResponseRedirect('/index/')
else:
form = ChangeTaskForm(user=request.user)
return render(request, 'oderascrumy/task.html', {'form': form})
forms.py
class ChangeTaskForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(ChangeTaskForm, self).__init__(*args, **kwargs)
if user.groups.filter(name='DEVELOPER').exists():
self.fields['status'].choices = (('V','Verified'), ('D','Done'),)
class Meta:
model = GoalStatus
fields = ('title', 'task_id','description','status', 'verified_by')
template.html
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">add task</button>
</form>
I think no need of template tag for this.
So I have these two models Lecture and FileUpload. I want that the user to be able to add a lecture to a specific course and also upload multiple files for that lecture. Thing is that after I submit the form the information gets saved except for the uploaded files, so I am guessing something is wrong with my formset. Please have a look:
FileFormset = inlineformset_factory(Lecture, FileUpload, exclude=[])
def classroom(request):
if request.method == 'POST':
form1 = LectureForm(request.POST)
if form1.is_valid():
lecture = form1.save()
formset = FileFormset(request.POST, request.FILES, instance=lecture, prefix='files')
if formset.is_valid():
formset.save()
else:
print(formset.errors)
formset.save()
return redirect('courses:index')
else:
form1 = LectureForm()
formset = FileFormset()
context = {'teacher_data': TeacherData.objects.all(),
'teachers': Teacher.objects.all(),
'courses': Course.objects.all(),
'form1': form1,
'formset': formset,
}
return render(request, 'courses/classroom.html', context)
<form method="post" action="">
{% csrf_token %}
{{ form1.as_p }}
{{ formset.management_form }}
{% for form in formset %}
{{ form }} <br>
{% endfor %}
<br>
<button type="submit">Add Lecture</button>
</form>
class LectureForm(forms.ModelForm):
class Meta:
model = Lecture
fields = ('course', 'lecture_title', 'lecture_category', 'content')
class FileForm(forms.ModelForm):
class Meta:
model = FileUpload
fields = ('files',)
class Lecture(models.Model):
LECTURE_CHOICES = (
('Courses', 'Courses'),
('Seminars', 'Seminars'),
)
course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures',)
lecture_category = models.CharField(max_length=10, choices=LECTURE_CHOICES, default='Courses',)
lecture_title = models.CharField(max_length=100, blank=True, null=True)
content = models.TextField(blank=True, null=True)
def __str__(self):
return str(self.lecture_title)
class FileUpload(models.Model):
files = models.FileField(upload_to='documents', null=True, blank=True)
lecture = models.ForeignKey('Lecture', related_name='files', on_delete=None, default=None)
def __str__(self):
return str(self.files)
add enctype attribute to you from widget like,
<form method="post" action="" enctype= multipart/form-data>
Try this
I can't seem to figure out why its not letting me display my ForeignKey fields that I'm passing to the forms on my templates. I researched all over but couldn't figure out an answer with explanation that works. Anyone have any ideas what I'm doing wrong?
forms.py
class MeetingForm(forms.ModelForm):
meeting_date = forms.ModelChoiceField(widget=forms.HiddenInput(), queryset=Date.objects.all())
person = forms.ModelChoiceField(widget=forms.HiddenInput(), queryset=Person.objects.all())
class Meta:
model = MeetingAttendance
fields = ['meeting_date', 'person', 'attended',]
Models.py
class MeetingAttendance(models.Model):
meeting_date = models.ForeignKey('Date', on_delete=models.CASCADE)
person = models.ForeignKey('Person', on_delete=models.CASCADE)
attended = models.BooleanField()
def __str__(self):
return "%s - %s" % (self.person, self.meeting_date)
Views.py
def date_detail(request, slug):
people = Person.objects.all()
detail = Date.objects.get(slug=slug)
MeetingFormSet = formset_factory(MeetingForm, extra=len(people)-2, max_num=len(people))
if request.method == "POST":
form = MeetingFormSet(request.POST)
if form.is_valid():
formset = form.save(commit=True)
formset.save()
return redirect('date_detail', slug=slug)
else:
initial_data = [{'person': person, 'meeting_date': detail} for person in people]
form = MeetingFormSet(initial=initial_data)
context = {
'form': form,
'people': people,
}
return render(request, 'date_detail.html', context)
Template
<div class="directory panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Meeting Details</h3>
</div><!-- end paneil-heading -->
<div class="panel-body">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
</div>
</div>
Please, help.. I do not udersatand what I should do this code to work..
home.html:
<form class="subscribe-form" action="{% url 'subscribe' %}" method="POST">{% csrf_token %}
{{ form }}
<button class="btn btn-main btn-lg" type="submit">Подписаться!</button>
</form>
{% if success %}
<div class="subscribe-result">
{{ success }}
</div>
{% endif %}
urls.py:
url(r'^$', 'interior_app.views.home', name='home'),
url(r'^subscribe/$', 'interior_app.views.subscribe', name='subscribe')
models.py:
class Subscriber(models.Model):
email = models.EmailField('', max_length=100, null=True, blank=True)
forms.py:
class SubscriberForm(forms.ModelForm):
class Meta:
model = Subscriber
fields = ['email']
admin.py:
class SubscriberAdmin(admin.ModelAdmin):
list_display = ('email',)
admin.site.register(Subscriber, SubscriberAdmin)
views.py:
def home(request):
portfolios = PortfolioObject.objects.all()
photos = []
for portfolio in portfolios:
for obj in portfolio.photo_set.all():
photos.append(obj)
form = SubscriberForm()
context = {"photos": photos[::2], "form": form}
return render(request, "home.html", context)
def subscribe(request):
print request
success = ''
if request.method == "POST":
print request.POST
form = SubscriberForm(request.POST)
print form
if form.is_valid():
form.save()
success = "Ваш Email успешно отправлен"
form = SubscriberForm()
else:
form = SubscriberForm()
context = {"photos": photos[::2], "form": form, "success": success}
return render(request, "home.html", context)
I input email in the form, push button and nothing is happening.
Any data in admin, any {{ success }}.
I need not AJAX.. I would like to do this feature only with Django
I have a ModelForm that I'm using to upload files with and it doesn't want to work. I had it working yesterday but I'm not sure what was done to make it stop all of a sudden.
Here's my ModelForm:
class UserForm(forms.ModelForm):
description = forms.CharField(max_length=500, widget=forms.Textarea(attrs={'cols': 80, 'rows': 5}))
class Meta:
model = UserProfile
exclude = {'user', 'description'}
Here's the Model:
def get_image_path(instance, filename):
return os.path.join('images', str(instance.id), filename)
def get_video_path(instance, filename):
return os.path.join('videos', str(instance.id), filename)
def get_randfile_path(instance, filename):
return os.path.join('randfile', str(instance.id), filename)
class UserProfile(models.Model):
user = models.OneToOneField(User)
description = models.CharField(max_length=500, blank=True, null=True)
photo = models.FileField(upload_to=get_image_path, blank=True, null=True)
video = models.FileField(upload_to=get_video_path, blank=True, null=True)
rand_file = models.FileField(upload_to=get_randfile_path, blank=True, null=True)
def photo_name(self):
return os.path.basename(self.photo.name)
def video_name(self):
return os.path.basename(self.video.name)
Here's the View:
def detail(request, user_id):
user = get_object_or_404(User, pk=user_id)
userprofile = get_object_or_404(UserProfile, user=user)
year = datetime.now().year
userform = UserForm()
delvid = Del_Video()
if request.method == 'POST':
userform = UserForm(request.POST, request.FILES, instance=user)
delvid = Del_Video(request.POST)
if userform.is_valid():
userprofile.description = request.POST.get('description', userprofile.description)
userprofile.photo = request.FILES.get('photo', userprofile.photo)
userprofile.video = request.FILES.get('video', userprofile.video)
userprofile.rand_file = request.FILES.get('rand_file', userprofile.rand_file)
userprofile.save()
else:
messages.add_message(request, messages.INFO, 'Invalid Form')
userform = UserForm()
if delvid.is_valid():
if request.POST['Delete']:
userprofile.video.delete()
else:
delvid = Del_Video()
context = {'user': user, 'year': year, 'userform': userform, 'userprofile': userprofile, 'delvid': delvid}
return render(request, 'users/detail.html', context)
And here is the form in the template:
<div class="row">
<div class="col-md-4">
<h4>Update User:</h4>
{% if userform.errors %}
<h6>{{ userform.errors }}</h6>
{% endif %}
{% if messages %}
{% for message in messages %}
<h5>{{ message }}</h5>
{% endfor %}
{% endif %}
<form action="{% url 'users:detail' user.id %}" method="post" enctype="multipart/form-data" data-ajax="false">
{% csrf_token %}
{{ userform.as_p }}
<input type="submit" value="Update">
</form>
</div>
</div>