When I try to print a field (Many-to-Many)in the terminal I only get the result "None". Am I missing something?
view.py
def assign_skill (request, pk):
plan = get_object_or_404(Plan, pk=pk)
if(request.GET.get('assign_skill')):
print("nummer1")
print(plan.title)
print(plan.skillonplan)
return redirect('all-plan')
models.py
class Plan(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, editable=False)
subscriber = models.ManyToManyField(User, blank = True, related_name = 'plansubscriber')
title = models.CharField(max_length=100, default = '', null=True, blank=True)
description = models.TextField(max_length=10000, default = '', null=True, blank=True)
company = models.CharField(max_length=200, null=True, editable=False)
created_date = models.DateTimeField(default=timezone.now)
skillonplan = models.ManyToManyField(Skill, null=True, blank = True, related_name='planneke')
duration = models.IntegerField(default=0,
validators=[MaxValueValidator(36), MinValueValidator(1)]
)
def get_skills(self):
return '\n'.join([p.skills for p in self.skill.all()])
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse_lazy('plan_detail', kwargs={'pk': self.id})
you can use following code, in order to return many to many fields :
print(plan.skillonplan.all())
Related
While creating new products I'm getting such kind of error. Can someone help me?
class Product(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
name_geo = models.CharField(max_length=200, null=True, blank=True)
image = models.ImageField(null=True, blank=True, default='/placeholder.png')
brand = models.CharField(max_length=200, null=True, blank=True)
category = models.ForeignKey(Category, null=False, default=0, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
countInStock = models.IntegerField(null=True, blank=True, default=0)
createdAt = models.DateTimeField(auto_now_add=True)
_id = models.AutoField(primary_key=True, editable=False)
def __str__(self):
return self.name_geo
class Category(models.Model):
_id = models.AutoField(primary_key=True, editable=False)
name = models.CharField(max_length=200, null=True, blank=True)
createdAt = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
#api_view(['POST'])
def createProduct(request):
user = request.user
product = Product.objects.create(
user=user,
name_geo="Sample Name",
category="Sample Category",
price=0,
brand='Sample Brand',
countInStock=0,
)
serializer = ProductSerializer(product, many=False)
return Response(serializer.data)
Without separating category class in models.py everything works fine. I mean If i didn't use ForeignKey in Products class for category
It just has to be a Category Instance/Object
product = Product.objects.create(
user=user,
name_geo="Sample Name",
category=Category.objects.get_or_create(name="Sample Category"),
price=0,
brand='Sample Brand',
countInStock=0,
)
Notes:
You could just do a .get() or a .filter().first() if you don't want to create
If you use a form, you can get away with just the Category's PK/_id in the POST
this type of thing: f = form(request.POST) f.is_valid() f.save()
At the end that field will hold the PK/_id/Row# of the Category Obj
blog_id is not get. help me to solve this ---
models.py
class Blog(models.Model):
title = models.CharField(max_length=500)
body = models.TextField()
last_updated_on = models.DateTimeField(auto_now=True)
created_on = models.DateTimeField(auto_now_add=True)
author_instance = models.ForeignKey(AuthorInstance, on_delete=models.PROTECT)
status_draft = models.BooleanField(default=False, blank=True, null=True)
status_publish = models.BooleanField(default=False, blank=True, null=True)
likes = models.ManyToManyField(UserInstance, related_name='like', default=None, blank=True)
like_count = models.BigIntegerField(default='0')
def total_likes(self):
return self.likes.count()
views.py
def like_post(request):
post = get_object_or_404(Blog, id=request.POST.get('blog_id'))
how to solve????
views should be like
def like_post(request,id):
post = get_object_or_404(Blog, id=request.POST.get('blog_id'))
I'm have been struggling on this for 2 days, really. I want to populate Timesheet form field from Employees model as a select field / dropdown list.
Here are my files and I tried so far.
MODEL.PY
class Employees(models.Model):
# MONTHLY = 'MONTHLY'
# SEMIMONTHLY = 'SEMIMONTHLY'
# BIWKEEKLY = 'BIWKEEKLY'
# WEEKLY = 'WEEKLY'
# DAILY = 'DAILY'
PAY_PERIODS = [
('Monthly', 'Monthly'),
('Bi-weekly', 'Bi-weekly'),
('Weekly', 'Weekly'),
('Daily', 'Daily'),
]
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
is_active = models.BooleanField(default=True, verbose_name='Employee is actives')
first_name = models.CharField(max_length=50, verbose_name='First Name.', null=True, blank=False)
middle_name = models.CharField(max_length=50, verbose_name='Middle Name or Initials.', null=True, blank=True)
last_name = models.CharField(max_length=50, verbose_name='Last Name.', null=True, blank=False)
full_name = models.CharField(max_length=50, null=True, blank=True)
phone = PhoneField(blank=True, null=True)
email = models.EmailField(max_length=150, blank=True, null=True)
state = USStateField(null=True, blank=True)
street_address = models.CharField(max_length=150, blank=True, null=True, verbose_name='Street Address.')
zip_code = models.CharField(max_length=50, blank=True, null=True, verbose_name='Zip Code.')
hourly_rate = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
pay_frequency = models.CharField(max_length=100, choices=PAY_PERIODS, blank=True)
hire_date = models.TimeField(auto_now_add=True)
def __str__(self):
return self.full_name
def save( self, *args, **kwargs ):
self.full_name = f'{self.first_name} {self.middle_name} {self.last_name}'
super().save( *args, **kwargs )
class Timesheet(models.Model):
"""A timesheet is used to collet the clock-ins/outs for a particular day
"""
employer = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
full_name = models.ForeignKey(Employees, on_delete=models.CASCADE, null=True, blank=False, verbose_name='Select YOUR Name')
start_date = models.DateField(auto_now_add=True, null=True)
end_date = models.DateField(null=True, blank=False)
time_worked = models.DateField(null=True, blank=False)
def __str__(self):
return self.full_name
VIEWS.PY # I tried both function and class based views
class TimesheetView(CreateView):
model = Timesheet
fields = ('full_name', )
# form_class = TimesheetFrom
# queryset = Employees.objects.filter()
# print(queryset)
template_name = 'users/timesheet.html'
success_url = reverse_lazy('timesheet')
#login_required
def timesheet_view(request):
if request.method == 'POST':
form = TimesheetFrom(request.POST)
if form.is_valid():
emp = form.save(commit=False)
emp.user_id = request.user.pk
emp.save()
return redirect('dashboard')
else:
form = TimesheetFrom()
context = {
'form': TimesheetFrom(),
}
return render(request, 'users/timesheet.html', context)
FORM.PY
class TimesheetFrom(forms.Form):
class Meta:
model = Timesheet
fields = '__all__'
exclude = ('employer', )
#This is the current state of the form but I did tried many approaches.
I did search extensively here (Stackoverflow) but no use case for me. Any help will be greatly appreciated with a cup of coffee.
I am getting the following error and I am not able to figure it out:
TypeError: str returned non-string (type Leads)
class Leads(models.Model):
name = models.CharField(max_length=250, default=0)
contact_person_name = models.CharField(max_length=250, default=0 ,blank=True, null=True)
email = models.EmailField(max_length=250, default=0, blank=True, null=True)
created_by = models.ForeignKey("packsapp.Employee", on_delete=models.CASCADE, related_name='createdby')
def __str__(self):
return self.name
class Pfep(models.Model):
client = models.ForeignKey(Leads, on_delete=models.CASCADE, related_name='vendor_owner')
receiver = models.CharField(max_length=250, default=0 ,blank=True, null=True)
receiver_location = models.CharField(max_length=250, default=0 ,blank=True, null=True)
def __str__(self):
return self.client
class PPboxSol(models.Model):
box_length = models.IntegerField(default=0, blank=True, null=True)
box_breadth = models.IntegerField(default=0, blank=True, null=True)
box_height = models.IntegerField(default=0, blank=True, null=True)
created_on = models.DateField(auto_now_add=True)
pfep = models.ForeignKey(Pfep, on_delete=models.CASCADE, related_name='pfep_box_sol')
created_by = models.ForeignKey("packsapp.Employee", on_delete=models.CASCADE, related_name='ppbox_createdby')
Views.py
class PpboxsolFormView(CreateView):
model = PPboxSol
form_class = Ppboxsolform
template_name = 'pfep/PpboxsolForm.html'
def get_initial(self):
initial = super().get_initial()
initial['pfep'] = Pfep.objects.get(pk=self.kwargs['pk'])
return initial
def form_valid (self, form):
if self.request.user.employee.employee_role == 'admin':
product = form.save(commit=False)
product.created_by = Employee.objects.filter(user=self.request.user.id)[0]
product.save()
messages.success(self.request, 'The PP Box Solution was created with success!')
return redirect('emp:ppbox_table')
else:
messages.success(self.request, "You don't have permission to create Solution!")
return redirect('emp:ppbox_table')
return redirect('emp:pfep_table')
Urls.py
path('ppboxsol/add/<int:pk>/', PpboxsolFormView.as_view(), name='ppbox_form'),
Do I need to add def __str__(self): to model PPboxSol as well ?
Edit:
I have added the Leads model as well, but that also returns a str
add a lead field name you want to show for example user model if we want to show username so we need to use user.username
Try This:
class Pfep(models.Model):
client = models.ForeignKey(Leads, on_delete=models.CASCADE, related_name='vendor_owner')
receiver = models.CharField(max_length=250, default=0 ,blank=True, null=True)
receiver_location = models.CharField(max_length=250, default=0 ,blank=True, null=True)
def __str__(self):
return str(self.client.name)#name for example
I have this Model:
class Complaint(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1)
date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
name = models.CharField(max_length=255, unique=True)
definition = models.TextField(blank=False, default="")
is_violent = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.name
class Meta:
ordering = ['name']
def get_absolute_url(self):
return reverse('complaint-details', kwargs={'pk': self.pk})
class Service(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1)
date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
name = models.CharField(max_length=255, unique=True)
definition = models.TextField(blank=True, default="")
is_active = models.BooleanField(default=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('service-details', kwargs={'pk': self.pk})
class Location(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1)
date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
location_name = models.CharField(max_length=255, unique=True)
loc_lat = models.DecimalField(max_digits=9, decimal_places=6)
loc_long = models.DecimalField(max_digits=9, decimal_places=6)
pop = models.PositiveIntegerField(default=500)
is_AOR = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.location_name
class Blotter(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1)
date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True)#default=timezone.now().date()
date = models.DateField(blank=True)
time = models.TimeField(blank=True)
entry_number = models.CharField(max_length=255, unique=True,validators=[RegexValidator(r'^\d{1,255}$')])
complaints = models.ForeignKey(Complaint, on_delete=models.CASCADE, null=True, blank=True)
service = models.ForeignKey(Service, on_delete=models.CASCADE, null=True, blank=True)
information = models.TextField(blank=False, default="")
location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True, blank=True)
is_active = models.BooleanField(default=True)
class Meta:
ordering = ("date_created",)
def __str__(self):
return (self.entry_number)
def get_absolute_url(self):
return reverse('details-blotter', kwargs={'pk': self.pk})
And I have this serializer:
class APILocationListSerializer(serializers.Serializer):
address = serializers.CharField()
latitude = serializers.DecimalField(max_digits=9, decimal_places=5)
longitude = serializers.DecimalField(max_digits=9, decimal_places=5)
population= serializers.IntegerField()
crime_count=serializers.IntegerField()
crime_rate=serializers.DecimalField(max_digits=4, decimal_places=3)
is_aor = serializers.BooleanField()
class Meta:
model = Blotter
fields= [
'address',
'latitude',
'longitude',
'population',
'crime_count',
'crime_rate'
'is_aor',
]
def to_representation(self, value):
context = {
value['address']:
{
'coordinates':[value['latitude'],value['longitude']],
'Population': value['population'],
'Crime-Count': value['crime_count'],
'Crime-Rate': value['crime_rate'],
'Area-Of-Responsibility': value['is_aor'],
}
}
return context
And ListApiView:
class APILocationList(generics.ListAPIView):
serializer_class = APILocationListSerializer
def get_queryset(self):
q=Blotter.objects.values('location__location_name').annotate(
address=F('location__location_name'),
latitude=F('location__loc_lat'),
longitude=F('location__loc_long'),
population=F('location__pop'),
crime_count=Count('complaints', filter=Q(complaints__is_active=True) and Q(complaints__isnull=False)),
crime_rate=(Cast(F('crime_count'), FloatField())/Cast(F('population'), FloatField()))*100000,
is_aor=F('location__is_AOR')
)
q1 = q.filter(location__is_AOR=True).order_by('address')
query_search = self.request.GET.get("q")
if query_search:
q1 = q.filter(Q(location__is_AOR=True) and Q(location__location_name__icontains=query_search)).order_by('address')
return q1
I'm new to django and DRF. I want to achieve a result like this in my API Not Achieved
but this is the result that i've achieved so far Achieved
As you can see in the picture, I want to count the crime trend (highest count of a crime and the crime itself) in every location.
My questions are:
Is this even achievable/possible to get these results using just one query?
If yes, how?
If no, is there any other way to achieve these kind of results?
Thank you in advance!