I have 2 modules a module representing a company:
class ExternalService(models.Model):
# Fields
company_name = models.CharField(max_length=60)
address_street = models.CharField(max_length=60)
address_postcode = models.CharField(max_length=30)
address_city = models.CharField(max_length=30)
company_telephone = models.CharField(max_length=30)
company_email = models.CharField(max_length=60)
company_support_telephone = models.CharField(max_length=30)
company_support_email = models.CharField(max_length=30)
company_website = models.URLField(null=True, blank=True)
notes = models.TextField(max_length=448)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
class Meta:
pass
def __str__(self):
return str(self.company_name)
def get_absolute_url(self):
return reverse("asset_app_ExternalService_detail", args=(self.pk,))
def get_update_url(self):
return reverse("asset_app_ExternalService_update", args=(self.pk,))
and a module representing employees:
class ExternalServiceContact(models.Model):
# Relationships
company = models.ForeignKey("asset_app.ExternalService", on_delete=models.SET_NULL, blank=True, null=True)
position = models.ForeignKey("asset_app.ExternalServicePosition", on_delete=models.SET_NULL, blank=True, null=True)
# Fields
name = models.CharField(max_length=60)
email = models.CharField(max_length=30)
cellphone = models.CharField(max_length=30)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
class Meta:
pass
def __str__(self):
return str(self.name)
def get_absolute_url(self):
return reverse("asset_app_ExternalServiceContact_detail", args=(self.pk,))
def get_update_url(self):
return reverse("asset_app_ExternalServiceContact_update", args=(self.pk,))
In my views.py I want to get all the employees belonging to that company. So when I look at my DetailView I only get listed employees beloning to that company.
class ExternalServiceDetailView(generic.DetailView):
model = models.ExternalService
form_class = forms.ExternalServiceForm
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['employees'] = models.ExternalServiceContact.get(#######).order_by('name')
return context
just dont know what to insert into my get()
You can query with:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['employees'] = self.object.externalservicecontact_set.order_by('name')
return context
Related
the issue is that i have 3 users levels
1-superuser
2-jihawi
3-mahali,
I would like to separate the veiw from the "Quantite" function by request.user
models.py
class typestock(models.Model):
Type = models.CharField(max_length=50, blank=True, null=True)
def __str__(self):
return self.Type
class stock(models.Model):
Jihawi = models.ForeignKey(User, on_delete=models.CASCADE, related_name="stockjihawi", editable=True, blank=True, null=True)
Mahali = models.ForeignKey(User, on_delete=models.CASCADE, related_name="stockmahali", editable=True, blank=True, null=True)
Date = models.DateField(blank=True, null=True)
TypeStock = models.ForeignKey(typestock, on_delete=models.CASCADE, editable=True, blank=True, null=True)
Quantite = models.IntegerField()
def save(self, *args, **kwargs):
super(stock, self).save(*args, **kwargs)
return self.TypeStock
admin.py
class TypeStockAdmin(nested_admin.NestedModelAdmin, ImportExportModelAdmin):
inlines = [InlineStock]
list_display = ('Type', 'Quantite')
list_display_links = ('Type',)
list_filter = ('Type',)
search_fields = ('Type',)
def Quantite(self, obj):
result = stock.objects.filter(TypeStock_id=obj).aggregate(Sum("Quantite"))
return result["Quantite__sum"]
Quantite.short_description = "Quantité"
how to add this code in the Quantite function:
if request.user.is_superuser:
stock.objects.filter(StockType_id=obj).aggregate(Sum("Quantity"))
###must view all quantity from stock models###
elif request.user.is_jihawi:
stock.objects.filter(TypeStock_id=obj).aggregate(Sum("Quantity"))
###how to add filter Jihawi=request.user (Jihawi from stock models)###
elif request.user.is_mahali:
stock.objects.filter(StockType_id=obj).aggregate(Sum("Quantity"))
###how to add filter Mahali=request.user (Mahali from stock models)###
I have a model form that creates a new job entry, and on submission, I need an invisible field job_time_estimation to be set to a sum of 'service_stats_estimate_duration' values from ServiceItemStats objects associated with the JobEntry by a many-to-many relationship when submitting the form.
For example, if in my NewJobEntryForm I chose two existing ServiceItemStats objects that have service_stats_estimate_duration values 60 and 90, on submission, I want a value 150 to be saved in that JobEntry object's job_time_estimation attribute.
I tried doing this using aggregation by defining a save() method in the model but I am getting an error "name 'serviceItemStats' is not defined".
I am not sure if I am going about this the right way. Any help would be appreciated.
My code:
models.py:
class ServiceItemStats(models.Model):
service_stats_name = models.CharField(primary_key=True, max_length=20)
service_stats_estimate_duration = models.IntegerField()
# Many-to-many relationship with JobEntry.
def __str__(self):
return self.service_stats_name
class JobEntry(models.Model):
# PK: id - automatically assigned by Django.
jo
b_entry_date_time = models.DateTimeField(default=timezone.now)
jo
b_date = models.DateField(blank=True, null=True)
job_checked_in = models.BooleanField()
job_checked_out = models.BooleanField(default=False)
job_priority = models.IntegerField()
job_time_estimation = models.IntegerField(blank=True, null=True)
job_comments = models.TextField(max_length=200, blank=True, null=True)
job_parts_instock = models.BooleanField(default=False)
job_started = models.BooleanField(default=False)
job_finished = models.BooleanField(default=False)
job_expand_fault_evidence = models.ImageField(blank=True, null=True)
job_expand_comments = models.ImageField(blank=True, null=True)
job_expand_parts_required = models.CharField(max_length=200, blank=True, null=True)
vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) #One-to-one relationship
customer = models.ForeignKey(Customer, on_delete=models.CASCADE) #One-to-one relationship
serviceBay = models.ForeignKey(ServiceBay, on_delete=models.CASCADE, blank=True, null=True) #One-to-one relationship
serviceItemStats = models.ManyToManyField(ServiceItemStats, blank=True) #Many-to-many relationship
def __str__(self):
return self.id
def save(self, *args, **kwargs):
if not self.job_time_estimation:
self.job_time_estimation = serviceItemStats.objects.all().aggregate('service_stats_estimate_duration')
return super().save(*args, **kwargs)
def get_absolute_url(self):
return reverse("jobs:job_detail",kwargs={'pk':self.pk})
views.py
class JobCreateView(FormView):
template_name = "jobs/jobentry_form.html"
form_class = NewJobEntryForm
success_url = reverse_lazy("jobs:job_list")
def form_valid(self, form):
form.save()
return super(job_list, self).form_valid(form)
forms.py
class NewJobEntryForm(ModelForm):
class Meta:
model = JobEntry
fields = ['vehicle', 'customer', 'job_date', 'job_checked_in', 'job_priority', 'job_comments', 'job_parts_instock', 'serviceItemStats']
widgets = {
'job_date' : forms.DateInput(format=('%m/%d/%Y'), attrs={'class':'form-control', 'placeholder':'Select a date', 'type':'date'}),
'ServiceItemStats' : forms.CheckboxSelectMultiple(),
'job_priority' : forms.RadioSelect(choices=priorityOptions),
}
You can try this.
from django.db.models import Sum
class JobCreateView(FormView):
template_name = "jobs/jobentry_form.html"
form_class = NewJobEntryForm
success_url = reverse_lazy("jobs:job_list")
def form_valid(self, form):
job=form.save()
estimation = job.serviceItemStats.all().aggregate(total=Sum('service_stats_estimate_duration'))
job.job_time_estimation = estimation['total']
job.save()
return super(job_list, self).form_valid(form)
Good day.
I'm trying to create a object based on form input, i tesed out the data, everything is provided but, for some reason the form is not validated.
I've also tried overriding form_valid(self,form) but the problem with that method was django never went to it as if it didn't exist.
forms.py
class CreatePostForm(forms.ModelForm):
class Meta:
model = Post
fields = '__all__'
views.py
class CreatePost(CreateView):
form_class = CreatePostForm
template_name = 'dashboard/add-product.html'
# success_url = redirect('user_posts:post_detail')
def post(self, request, *args, **kwargs):
form = CreatePostForm(request.POST)
if self.form_valid(form):
post = form.save(commit=False)
post.user = request.user
post.save()
return redirect('user_posts:post_detail', args=post.slug)
print('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')
code in the template is basic form, not gona import it.
data that has been passed via request.POST
user
'b8a3b0b3-0eef-48ed-b257-a6f9bfdd5cda'
title
'theetitle'
main_description
'agdgdfg'
slug
''
main_image
'Bucee_Lee_smile.jpg'
subtitle1
''
sub_description1
''
sub_image1
''
subtitle2
''
sub_description2
''
sub_image2
''
subtitle3
''
sub_description3
''
sub_image3
''
total_likes
''
traceback points to this line
if self.form_valid(form):
model
class Post(models.Model):
id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200, unique=True)
main_description = models.TextField()
slug = models.SlugField(db_index=True, blank=True)
main_image = models.ImageField(upload_to=upload_image)
subtitle1 = models.CharField(max_length=200, blank=True, null=True)
sub_description1 = models.TextField(blank=True, null=True)
sub_image1 = models.ImageField(upload_to=upload_image,
blank=True, null=True)
subtitle2 = models.CharField(max_length=200, blank=True, null=True)
sub_description2 = models.TextField(blank=True, null=True)
sub_image2 = models.ImageField(upload_to=upload_image,
blank=True, null=True)
subtitle3 = models.CharField(max_length=200, blank=True, null=True)
sub_description3 = models.TextField(blank=True, null=True)
sub_image3 = models.ImageField(upload_to=upload_image,
blank=True, null=True)
posts_liked = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='posts_liked',
blank=True, null=True)
total_likes = models.PositiveIntegerField(blank=True, null=True, db_index=True)
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
objects = PostManager()
# TODO: get_absolute_url()
def get_absolute_url(self):
return reverse('user_posts:post_detail', args=[self.slug])
def __str__(self):
return self.title
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
if not self.slug:
self.slug = slugify(self.title)
super(Post, self).save(force_insert, force_update, using, update_fields)
class Meta:
verbose_name_plural = 'Posts'
try the following way
class CreatePost(CreateView):
form_class = CreatePostForm
template_name = 'dashboard/add-product.html'
success_url = ('url_name')
def form_valid(self, form):
valid_data = super(CreatePost, self).form_valid(form)
form.instance.user = self.request.user
return valid_data
I need to show a list of countries for users to select from the ship's country field. But it's showing the Country object(1), Country object(2)... instead of showing names of countries
I've created classes for Ship and Country with the Ship class having a foreign key of country.
class Ship(models.Model):
# Fields
name = models.CharField(max_length=255)
slug = extension_fields.AutoSlugField(populate_from='name', blank=True)
created = models.DateTimeField(auto_now_add=True, editable=False)
callsign = models.CharField(max_length=50)
last_updated = models.DateTimeField(auto_now=True, editable=False)
weight = models.DecimalField(max_digits=20, decimal_places=4)
# RelationShip Fields
shipflag = models.ForeignKey(
'manifest.Country', on_delete=models.SET_NULL,
related_name="Ships", null=True
)
class Meta:
ordering = ('-created',)
def __unicode__(self):
return u'%s' % self.slug
def get_absolute_url(self):
return reverse('manifest_Ship_detail', args=(self.slug,))
def get_update_url(self):
return reverse('manifest_Ship_update', args=(self.slug,))
class Country(models.Model):
# Fields
name = models.CharField(max_length=255)
slug = extension_fields.AutoSlugField(populate_from='name', blank=True)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
code = models.CharField(max_length=5)
# RelationShip Fields
continent = models.ForeignKey(
'manifest.Continent',
on_delete=models.CASCADE, related_name="Countrys",
)
class Meta:
ordering = ('-created',)
def __unicode__(self):
return u'%s' % self.slug
def get_absolute_url(self):
return reverse('manifest_Country_detail', args=(self.slug,))
def get_update_url(self):
return reverse('manifest_Country_update', args=(self.slug,))
In the 'create new ship' form at the country dropdown combo I expect to see a list of countries like United States, Mexico, Canada... but instead am seeing countries as objects like this object(1), Country object(2)...
add this method to your models. ;)
def __str__(self):
return self.name
I have two functions projectTimerStart to start the timer and projectTimerStop
i want to use the object which is created in projectTimerStart and i want to end the time when projectTimerStop , and this should be saved in a database
ps: Both the functions are not in class they are normal functions
def projectTimerStart(request, slug):
project_detail = Project.objects.get(slug=slug)
b = ProjectTimer(time_started=datetime.now(),
working_project=project_detail,
working_freelancer=request.user
)
b.save()
return HttpResponseRedirect(reverse('project_timer', kwargs=
{"slug":slug}))
def projectTimerStop(request, slug):
project_detail = Project.objects.get(slug=slug)
#i want something here super method or something
return HttpResponseRedirect(reverse('project_timer', kwargs=
{"slug": slug}))
models.py
class Project(models.Model):
project_title = models.CharField(max_length=100)
project_description = models.TextField()
created_by = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='created')
assigned_to = models.ManyToManyField(
User, blank=True, related_name='assigned_by')
slug = models.SlugField()
hourly_budget = models.PositiveIntegerField(blank=True, null=True)
technologies = models.ManyToManyField(
Technologies, related_name='technologies_used')
time_posted = models.DateTimeField(auto_now_add=True)
request_id = models.ManyToManyField(
User, related_name='requested_by', blank=True)
def __str__(self):
return self.project_title
def save(self, *args, **kwargs):
self.slug = slugify(self.project_title)
super(Project, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('project_detail', kwargs={'slug': self.slug})
def get_timer_url(self):
return reverse('project_timer', kwargs={'slug': self.slug})
def round_datetime(dt):
minutes = round((dt.minute + float(dt.second) / 60) / 15) * 15 -
dt.minute
return dt + datetime.timedelta(minutes=minutes, seconds=-dt.second)
class ProjectTimer(models.Model):
time_started = models.DateTimeField()
time_ended = models.DateTimeField(blank=True, null=True)
working_project = models.ForeignKey(Project, on_delete=models.CASCADE)
working_freelancer = models.ForeignKey(
User, on_delete=models.CASCADE, blank=True, null=True)
If each of your project objects will have one and only project timer objects, you can add project_timer = models.OneToOneField(ProjectTimer) to your Project model and access to the project timer by using project_detail.project_timer.
If not, you need to know at least one feature of that project_timer in order to fetch it from database. Or you can iterate all of your ProjectTimer objects that belongs to that Project and select the appropriate one by:
models.py
class Project(models.Model):
# Some fields
project_timers = models.ManyToManyField(ProjectTimer)
views.py
def projectTimerStop(request, slug):
project_detail = Project.objects.get(slug=slug)
for pt in project_detail.project_timers.all():
if pt.some_field == "THIS IS CORRECT TIMER":
# Here is your project_detail
print(str(pt))
return HttpResponseRedirect(reverse('project_timer', kwargs=
{"slug": slug}))