I am trying to create a JobRequestFile form where you can upload multiple files involving a foreign key to my JobRequest model. However, when trying to save, it takes me to my JobRequest form and says these fields are required.
my form:
class Meta:
model = JobRequestFile
fields = [
'file'
]
widgets = {
'file': ClearableFileInput(attrs={'multiple': True}),
}
my view:
class FileUpload(FormView):
form_class = JobRequestFileForm
template_name = 'jobrequest/upload.html' # Replace with your template.
success_url = 'loggedIn'
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
files = request.FILES.getlist('file')
if form.is_valid():
most_recent_jr = JobRequest.get.latest('requestDate')
for f in files:
JobRequestFile.object.create(jobRequest=most_recent_jr, file=f)
return self.form_valid(form)
else:
return self.form_invalid(form)
My template:
<form action='.' method='POST' enctype='multipart/form-data'>
{% csrf_token %}
{{ form.as_p }}
<input type='submit' value='Save' />
</form>
The two models:
class JobRequest(models.Model):
customer = models.ForeignKey('account.Customer', on_delete=models.CASCADE)
partnerTypeNeeded = models.CharField('PartnerTypeNeeded', max_length=30, choices=PartnerMore.PartnerTypes.choices)
issueDescription = models.TextField(blank=True)
communa = models.CharField(unique=False, max_length=30, default='0')
serviceDate = models.DateTimeField()
requestDate = models.DateTimeField(auto_now_add=True, null=False, blank=False)
budget = models.FileField(upload_to='budget/%Y/%m/', null=True, blank=True)
jobCompleted = models.BooleanField(default=False)
partner = models.ForeignKey('account.Partner', on_delete=models.SET_NULL, null=True, blank=True, related_name='assignedPartner')
suggestedPartner = models.ForeignKey('account.Partner', on_delete=models.SET_NULL, null=True, blank=True, related_name='suggestion')
class JobRequestFile(models.Model):
jobRequest = models.ForeignKey('JobRequest', on_delete=models.CASCADE)
file = models.FileField(upload_to='files/%Y/%m/')
Related
I have created a form for a Post. The form loads and when I enter all the value and try to submit the form, it gets refreshed but the database is not updated.
Here is my Post Model:
class Post(models.Model):
no_people = models.IntegerField()
no_days = models.IntegerField()
tour_date = models.CharField(max_length=200, blank=True)
Gender_types = (
('M', 'Male'),
('F', 'Female'),
('O', 'Others'),
)
Gender_prefer = models.CharField(max_length=1, choices=Gender_types)
location = models.CharField(max_length=200, blank=True)
pic_location = models.ImageField(blank=True, upload_to="posts/")
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
detail = models.TextField()
liked = models.ManyToManyField(Yatru, blank=True, related_name= 'likes')
author = models.ForeignKey(Yatru, on_delete=models.CASCADE, related_name = 'posts',null=True)
def __str__(self):
return str(self.location)
def no_likes(self):
return self.liked.all().count()
class Meta:
ordering = ('-created',)
def save(self, *args, **kwargs):
self.location = self.location.upper()
return super(Post, self).save(*args, **kwargs)
LIKE_CHOICES = (
('Like', 'Like'),
('Unlike', 'Unlike'),
)
Here is the form.py:
from django import forms
from .models import Post
class PostModelForm(forms.ModelForm):
class Meta:
model = Post
fields = ('no_people','no_days','tour_date', 'Gender_prefer','location','detail')
Here is the views.py:
def post_add(request):
user = request.user
profile = Yatru.objects.get(user=user)
form = PostModelForm(request.POST or None, request.FILES or None, instance=profile)
if request.method == 'POST':
if form.is_valid():
newpost=form.save(commit=False)
newpost.user=request.user
newpost.save()
return render(request, 'posts/my_post.html',{'form': form})
This is the HTML file:
<form method="POST">
{% csrf_token %}
{{form.as_p}}
<button type='submit'>Submit </button>
</form>
Hi please follow instructions:
First insert "author" field in field tuple of model form
In your post_add view change below line
newpost.author=request.user
The general task: there is a list of the events which are displayed in a table view, the user clicks on the event and gets redirected to a single event page, which displays extra information about an event.
There is a button on this template that should give functionality to record some data of the event in the user-selected events list.
And I really don't get how to pass the event data into the form to create the user_event, maybe I chose the wrong way to create the instance of the model?
Models.py
class Event(models.Model):
LANGUAGE_CHOICES = [
('EN', 'English'), ('IT', 'Italian'), ('FR', 'French'), ('DE', 'German'), ('RU', 'Russian'), ]
STATUS_CHOICES = [('draft', 'Draft'), ('confirmed', 'Confirmed'), ]
FORMAT_CHOICES = [('live', 'Live'), ('online', 'Online'), ]
TOPIC_CHOICES = [('cataract', 'Cataract'),
('vitreo', 'Vitreoretinal'),
('optometry', 'Optometry'),
('multi', 'Multidisciplinary'),
('plastic', 'Plastic and Reconstructive surgery'),
('onco', 'Ocular oncology'),
('glaucoma', 'Glaucoma'),
('pediatrics', 'Pediatrics'), ]
title = models.CharField(
max_length=250, verbose_name='Event', db_index=True, default="Event")
slug = models.SlugField(max_length=250, unique_for_date='publish')
kol = models.ManyToManyField(
Kol, verbose_name='Presenter', db_index=True, blank=True)
body = models.TextField(verbose_name='Description', blank=True)
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
sponsor = models.CharField(
max_length=150, verbose_name='Sponsored by', default='')
organizer = models.CharField(
max_length=150, verbose_name='Organized by', default='')
topic = models.CharField(
max_length=100, choices=TOPIC_CHOICES, default='multi', verbose_name='Discipline')
status = models.CharField(
max_length=100, choices=STATUS_CHOICES, default='draft')
event_format = models.CharField(
max_length=50, choices=FORMAT_CHOICES, default='online', verbose_name='Format', db_index=True)
main_language = models.CharField(
max_length=50, choices=LANGUAGE_CHOICES, default='EN', verbose_name='Main language', db_index=True)
event_url = models.URLField(blank=True)
event_date_start = models.DateField(
verbose_name='Start date', db_index=True)
event_time_start = models.TimeField(default='09:00')
event_date_finish = models.DateField(
verbose_name='End date', auto_now=True)
event_time_finish = models.TimeField(default='18:00')
is_cme = models.BooleanField(
default=False, verbose_name='CME credits', db_index=True)
objects = models.Manager() # the default manager
published = PublishedManager() # published manager
futured = FutureManager() # future dates only
# follow check
users_follow = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name='events_liked', blank=True)
class Meta:
ordering = ('event_date_start',)
def __str__(self):
return self.title
def get_kols(self):
return "\n".join([str(p) for p in self.kol.all()])
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Event, self).save(*args, **kwargs)
#property
def _month(self):
return datetime.date(self.event_date_start).month
event_month = property(_month)
def get_absolute_url(self):
return reverse('events:event_detail', args=[self.publish.year,
self.publish.strftime(
'%m'),
self.publish.strftime(
'%d'),
self.slug])
class UserEvent(models.Model):
follower = models.ForeignKey(
User, related_name='user_events', on_delete=models.CASCADE)
my_event = models.ForeignKey(
Event, related_name='selected_event', on_delete=models.CASCADE)
title = models.CharField(
max_length=250, verbose_name='Event', db_index=True, default="Event")
event_url = models.URLField(blank=True)
event_date_start = models.DateField(
verbose_name='Start date')
event_date_finish = models.DateField(
verbose_name='End date')
class Meta:
ordering = ['-event_date_start']
def save(self, *args, **kwargs):
created = not self.pk
super().save(*args, **kwargs)
if created:
UserEvent.objects.create(user=self)
def __str__(self):
return self.title
forms.py
class UserEventForm(forms.ModelForm):
class Meta:
model = UserEvent
fields = ("title", "event_url",
"event_date_start", "event_date_finish")
detail.html with the button
{% extends 'bbase11.html' %} {% block title %} {{ event.title}} {% endblock %} {% block content %}
<div class="container">
<h1> {{ event.title }}</h1>
<p class='event_descr'> {{event.body}}</p>
<p> Presenting professionals {{event.get_kols}}</p>
<div>Organized by {{event.organizer}}</div>
<div>Sponsored by {{event.sponsor}}</div>
<div>
<form action= "{% url "events:add_event" %}" method = "POST" >
{{form.as_p}}
{% csrf_token %}
<input id='event' type='hidden' value = {{event.id}}>
<button type="submit" class="btn btn-outline-primary btn-sm m-0 waves-effect">Add to calendar</button></div>
</form>
</div>
{% endblock %}
views.py
def event_detail(request, year, month, day, event):
event = get_object_or_404(Event, slug=event,
status='confirmed',
publish__year=year,
publish__month=month,
publish__day=day)
return render(request, 'events/event/detail.html', {'event': event, 'add_event': add_event})
#login_required
def add_event(request):
if request.method == 'POST':
form = UserEventForm(request.POST or None)
if form.is_valid():
form.save()
messages.success(request, ("Event has been added"))
return redirect('event_list')
else:
messages.error(request, ("Event has not been added"))
return redirect('events:event_list')
else:
events = Event.futured.all()
return render(request, 'list.html', {'events': events})
Using a class based view instead of your function based one, you can override the get_initial method as follows:
class AddEventCreateView(CreateView):
model = Event
form_class = UserEventForm
template_name = 'your/template.html'
def get_initial(self):
initial = super().get_initial()
# Add your initial values here - for example
initial['title'] = 'Some value'
return initial
def form_valid(self, form):
self.object = form.save(commit=False)
# Do something here
return super().form_valid(form)
def get_success_url(self):
return reverse_lazy('your:url-name')
You can now pass as many initial values to your form as needed. See http://ccbv.co.uk/projects/Django/3.0/django.views.generic.edit/CreateView/#get_initial for details.
It looks like it may be a typo in the URL in the detail.html with the quotes.
Change this:
<form action= "{% url "events:add_event" %}" method = "POST" >
To this:
<form action="{% url 'events:add_event' %}" method="POST">
Models
class Head_of_department(models.Model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
email = models.CharField(max_length=30)
def __str__(self):
return self.first_name
class Employee(models.Model):
first_name = models.CharField(max_length=200, unique=True)
last_name = models.CharField(max_length=200, unique=True)
head_of_department = models.ForeignKey('Head_of_department', on_delete=models.SET_NULL, blank=True, null=True)
email = models.EmailField(max_length=100)
def __str__(self):
return self.first_name + ' ' + self.last_name
class Attendance(models.Model):
head_of_department = models.ForeignKey('Head_of_department', on_delete=models.SET_NULL, blank=True, null=True)
employee = models.ForeignKey('Employee', on_delete=models.CASCADE, )
attendance = models.CharField(max_length=8, choices=attendance_choices, blank=True)
Views
class Attendancecreate(CreateView):
model = Attendance
fields = ['employee']
success_url = '/dashboard/'
def get_context_data(self,** kwargs):
context = super(Attendancecreate, self).get_context_data(**kwargs)
email = self.request.user.email
hod = Head_of_department.objects.get(email=email)
context["objects"] = self.model.objects.filter(employee__head_of_department =hod)
print (context["objects"])
return context
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.head_of_department = get_object_or_404(Head_of_department, email=self.request.user.email)
self.object.save()
return super().form_valid(form)
Template
<div class="form-group">
{% for item in objects %}
{{ item.employee }}
{% endfor %}
</div>
The webapp has a login feature. The headofdepartment can mark the attendance . I want to render a list of employees under the respective logged in HOD and mark attendance . I want to do this in the same view .
I am unable to render the employees for logged in HOD.
I found the solution , I wrote views incorrectly.
model = Attendance
fields = ['employee']
success_url = '/dashboard/'
def get_context_data(self,** kwargs):
context = super(Attendancecreate, self).get_context_data(**kwargs)
email = self.request.user.email
hod = Head_of_department.objects.get(email=email)
context["objects"] = Employee.objects.filter(head_of_department =hod)
print (context["objects"])
return context
Template
{% for emp in objects %}
{{ emp.first_name }} {{ emp.last_name }}
{% endfor %}
I am very new to Django as well as Python. I am trying to build a small Resource management tool. Below is what I have come up with till now.
I Extended a User Model
I have created other required models like Current address Permanent Address etc.
I have a sample form in forms.py
I have a profile.html page.
As of now when a user is logged , and when he clicks on update profile he is redirected to Profile.html page where he gets fields from ModelForm Employee (Data pulled from DB) which is just a extended userModel. (Infact user should not be able to edit any of the field in this form, this should be just a read only field as this will be set by Admin, but this Problem is later part for me, I do not know how to bring as a ReadOnly field have not researched yet on this)
What I want to do is now I want to show all the other forms also (ModelForms of Current Address, Permanent address etc on the same same page for that particular user so he can update the records) Till now I tried different methods but I couldn't get hold of any proper solution Can anyone help me on this. Below are my models, views, forms and html page. I am open for any alternative solution which is easy and secure as this I have started recently so I am ok to change whatever required to be changed. All the other models are linked to foreign Key emp_id from Employee model. Apologies for the Long question but I am stuck at this point and I unable to go ahead from this point.
Forms:
#User Profile Form to update the user profile
class UserProfileForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
# If you pass FormHelper constructor a form instance
# It builds a default layout with all its fields
self.helper = FormHelper(self)
# You can dynamically adjust your layout
helper = FormHelper()
helper.form_class = 'form-horizontal'
helper.layout = Layout(
Field('text_input', css_class='input-xlarge'),
Field('textarea', rows="3", css_class='input-xlarge'),
'radio_buttons',
Field('checkboxes', style="background: #FAFAFA; padding: 10px;"),
AppendedText('appended_text', '.00'),
PrependedText('prepended_text', '<input type="checkbox" checked="checked" value="" id="" name="">', active=True),
PrependedText('prepended_text_two', '#'),
'multicolon_select',
FormActions(
Submit('save_changes', 'Save changes', css_class="btn-primary"),
Submit('cancel', 'Cancel'),
)
)
self.helper.layout.append(Submit('save_changes', 'Update'))
class Meta:
model = Employee
exclude = ('user',)
Views:
#login_required
def user_profile(request):
if request.method == 'POST':
form = UserProfileForm(request.POST, instance=request.user.profile)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/loggedin/')
else:
user = request.user
profile = user.profile
form = UserProfileForm(instance=profile)
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('profile.html', args)
profile.html:
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<h2> Profile </h2>
{% crispy form %}
{% endblock %}
Models.
#Department Model
class Dept(models.Model):
dept_name = models.CharField(max_length=30)
def __unicode__(self):
return self.dept_name
#Extending User Model
class Employee(models.Model):
user = models.OneToOneField(User, null=True, blank = True, verbose_name="User Id")
emp_id = models.IntegerField(primary_key=True, max_length=5, verbose_name="Employee Id")
emp_first = models.CharField('First Name',max_length=20)
emp_middle = models.CharField('Middle Name', blank=True, max_length=20)
emp_last = models.CharField('Last Name',max_length=20)
emp_email = models.EmailField('Email Id')
emp_dept = models.ForeignKey(Dept, verbose_name="Department")
def __unicode__(self):
return self.emp_first
User.profile = property(lambda u: Employee.objects.get_or_create(user=u)[0])
#Current Address Model
class CurrentContact(models.Model):
emp = models.ForeignKey(Employee)
emp_add = models.TextField('Current Address')
emp_city = models.CharField('City', max_length=20, default = 'Bangalore')
emp_state = models.CharField('State', max_length=20, default= 'Karnataka')
emp_country = models.CharField('Country', max_length=20, default = 'India')
emp_mobile1 = models.IntegerField('Mobile1',max_length=12)
emp_mobile2 = models.IntegerField('Mobile2', null=True, blank=True, max_length=12)
emp_landline = models.IntegerField('Land Line',null=True, blank=True, max_length=12)
emp_PerEmail = models.EmailField('Personal Email Id', blank=True)
def __unicode__(self):
return self.emp
#Permanent Address Model
class PermanentContact(models.Model):
emp = models.ForeignKey(Employee)
emp_add = models.TextField('Permanent Address')
emp_city = models.CharField('City', max_length=20, default = 'Bangalore')
emp_state = models.CharField('State', max_length=20,default= 'Karnataka')
emp_country = models.CharField('Country', max_length=20, default = 'India')
emp_mobile1 = models.IntegerField('Mobile1',max_length=12)
emp_mobile2 = models.IntegerField('Mobile2', null=True, blank=True, max_length=12)
emp_landline = models.IntegerField('Land Line',null=True, blank=True, max_length=12)
emp_PerEmail = models.EmailField('Personal Email Id', blank=True)
def __unicode__(self):
return self.emp
#Emergency Contact Model
class Emergency(models.Model):
emp = models.ForeignKey(Employee)
emrg_name = models.CharField('Full Name', max_length=30)
emrg_add = models.TextField('Full Address')
emrg_city = models.CharField('City', max_length=20, default = 'Bangalore')
emrg_state = models.CharField('State', max_length=20,default= 'Karnataka')
emrg_country = models.CharField('Country', max_length=20, default = 'India')
emrg_mobile1 = models.IntegerField('Mobile1', max_length=12)
emrg_mobile2 = models.IntegerField('Mobile2', null=True, blank=True, max_length=12)
emrg_landline = models.IntegerField('Land Line',null=True, blank=True, max_length=12)
emrg_PerEmail = models.EmailField('Email Id', blank=True)
def __unicode__(self):
return self.emp
Have you taken a look here:
Django: Changing User Profile by forms
It seems like an almost identical question to yours.
I'm using Pinax to create a new project. For this project I needed to create a new app 'Business' which is much like Profiles but they wanted to keep everything seperate for Businesses.
I'm trying to have the admin be able to change the logo or "avatar" for the business profile. Im using the ImageModel class from Photologue to control the image upload, etc but I ran into a problem. When going through the form, the form goes through and redirects but the image doesn't actually get updated. When you go through the django admin, the image uploads fine.
If someone could take a look and see if something is missing, I've been staring at it for too long, so I need a fresh pair of eyes.
Business Models.py
class Business(models.Model):
name = models.CharField(verbose_name="Name", max_length=140)
desc = models.TextField(verbose_name="Description", null=True, blank=True)
bus_type = models.CharField(verbose_name="Business Type", choices=BUSINESS_TYPES, max_length=20)
location = models.CharField(_("location"), null=True, blank=True, max_length=200)
website = models.URLField(_("website"), null=True, blank=True, verify_exists=False)
created_by = models.ForeignKey(User, related_name="Created By")
admin = models.ManyToManyField(User, related_name="Admin User", null=True, blank=True)
followers = models.ManyToManyField(User, related_name="Followed by", null=True, blank=True)
date_added = models.DateField(verbose_name="Date Added")
class Meta:
verbose_name = "Business"
verbose_name_plural = "Businesses"
def __unicode__(self):
return self.name
class BusinessLogo(ImageModel):
business = models.ForeignKey(Business, related_name="Business Association")
My views.py
#login_required
def changeLogo(request, bus_id):
user = request.user
b = get_object_or_404(Business, pk = bus_id)
if request.method == 'POST':
form = ChangeLogoForm(request.POST, request.FILES, instance = b)
if form.is_valid():
biz_logo = form.save(commit=False)
biz_logo.save()
return HttpResponseRedirect('/')
else:
form = ChangeLogoForm()
return render_to_response('business/changelogo.html',
{'user': user, 'form':form, 'b':b}, context_instance=RequestContext(request))
Forms.py
class ChangeLogoForm(ModelForm):
class Meta:
model = BusinessLogo
def save(self, force_insert=False, force_update=False, commit=True):
f = super(ChangeLogoForm, self).save(commit=False)
if commit:
f.save()
print "form save method was called with commit TRUE"
return f
And finally my changelogo.html
...
{% block body %}
<h1>Change Logo</h1>
<form method="POST" action="" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Upload">
</form>
{% endblock %}
...
Thanks everyone, for taking a look.
Steve
The ChangeLogoForm's model is BusinessLogo, but when calling it's constructor you pass it a Business instance:
b = get_object_or_404(Business, pk = bus_id)
...
form = ChangeLogoForm(request.POST, request.FILES, instance = b)
(And you should probably use a OneToOneField field instead of ForeignKey)