I want to retrieve all image of a particular user. I need help.
here is my model
class image_archive(models.Model):
image_id = models.AutoField(primary_key=True)
event_id = models.ForeignKey(event_archive,db_column='event_id')
image_url = models.CharField(max_length=45)
screenshot_url = models.URLField(max_length=200)
image_title = models.CharField(max_length=45)
date_submitted = models.DateTimeField()
image_description = models.TextField()
original_image = models.ImageField(upload_to=file_upload_path)
formatted_image = ImageSpecField([FormatImage()],image_field='original_image', format='JPEG',
options={'quality': 90})
thumbnail_image = ImageSpecField([Adjust(contrast=1.2, sharpness=1.1),
ResizeToFill(50, 50)], image_field='original_image',
format='JPEG', options={'quality': 90}
here is my urls.py
urlpatterns = patterns('gallery.views',
url(r'^(?P<event_id>\d+)/images/$', 'eventimage'),
)
here is my views.py
def eventimage(request,event_id):
e_piclist = image_archive.objects.get(id = event_id)
return render_to_response('gallery/image.html',
{
'e_piclist' : e_piclist,
'image_archive':image_archive,
})
But this doest not show the images of a particular event's image. Need help.
Your query is incorrect, you can query it using
e_piclist = image_archive.objects.filter(event_id = event_id).
Also, try to use .filter() instead of .get().
from django.shortcuts import render, get_object_or_404
def eventimage(request,event_id):
my_event = get_object_or_404(Event, pk=event_id)
image_list = my_event.image_archive_set.all()
return render(request,'gallery/image.html',{'e_piclist':image_list})
Related
I new her and need help
I create a few models:
Customer
Orders
How to make the ADD button dynamic
If I use a filter and my url is http://127.0.0.1:8000/admin/catalog/order/?order_customer__id=3, in this case pass the following value to the button <a href="{% url opts|admin_urlname:'add ' %}?order_customer={{cl.result_list.0.order_customer.id}}"
To prompt you to fill out the form when creating a new record. Accordingly, the url should look like this
http://127.0.0.1:8000/admin/catalog/order/add/?order_customer=3
If the filter is missing url http://127.0.0.1:8000/admin/catalog/order/, the button has a default value
Accordingly, when switching to the creation form, the url has a standard value
http://127.0.0.1:8000/admin/catalog/order/add
Django 3.2.6
addons smart_selects
models.py
class Customer(models.Model):
"""docstring for Customer."""
customer_name = models.CharField(max_length=200, verbose_name='Назва юридичної особи/ФОП', help_text='Введіть поністю назву юридичної особи чи фізичної особи підприємця')
customer_inn = models.CharField(max_length=15, verbose_name='ЄДРПОУ', help_text='Введеіть ЄДРПОУ для юридичної особи чи ідентифікаційний код для ФОП')
customer_adress = models.TextField(max_length=200, verbose_name='Юридична адреса клієнта' , help_text='Притриймуйтесь формату аналогічно витягу ЄДР. Наприклад: 79000, Область, Район, Місто/Селище, вулиця/проспект Назва вулиці, Номебр будинку, квартира')
customer_ceo = models.CharField(max_length=50, verbose_name='Керівник/підписант')
class Meta:
verbose_name = 'Клієнт'
verbose_name_plural = 'Клієнти'
def __str__(self):
"""
String for representing the Model object.
"""
return self.customer_name
class Order(models.Model):
order_customer = models.ForeignKey('Customer', on_delete=models.CASCADE, verbose_name="Клієнт")
order_date = models.DateField(verbose_name='Дата заявки')
order_adress = ChainedForeignKey(
'MarketAdress',
chained_field = "order_customer",
chained_model_field= "customermarkeradress",
show_all = False,
auto_choose = True,
sort = True,
verbose_name= 'Адреса точки')
order_number = models.CharField(max_length=10, verbose_name='Номер заявки')
# oder_brand = models.ForeignKey('CustomerBrand', on_delete=models.CASCADE, verbose_name="Назва вивіски")
oder_brand = ChainedForeignKey(
'CustomerBrand',
chained_field = "order_customer",
chained_model_field= "customer",
show_all = False,
auto_choose = True,
sort = True,
verbose_name= 'Вивіска')
class Meta:
verbose_name = 'Заявка'
verbose_name_plural = 'Заявки'
def __str__(self):
"""
String for representing the Model object.
"""
return str(self.oder_brand)
admin.py
#admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
list_display = ['customer_name', 'customer_inn', 'сontract', 'orders_lists', 'orders_add']
inlines = [OrderInline, EnvironmentActInstanceInline]
def сontract(self, obj):
link_buttom = reverse('downloadWordcontarct', args=[obj.pk])
return mark_safe(f'<a class="button" label="Догорів" href="{link_buttom}">Сформувати</a>')
сontract.short_description = "Договір"
def orders_lists(self, obj):
argsus=obj.pk
link_buttom = reverse("admin:catalog_order_changelist") + "?" + "order_customer__id=" + str(argsus)
#return format_html('{} order', link_buttom)
return mark_safe(f'<a class="button" label="Заявки" href="{link_buttom}">Перейти до заявки</a>')
orders_lists.short_description = "Заявки"
def orders_add(self, obj):
argss=obj.pk
link_buttom = reverse ("admin:catalog_order_add") + "?" + "order_customer=" + str(argss)
return mark_safe(f'<a class="button" label="Заявки" href="{link_buttom}">Створити</a>')
orders_add.short_description = "Додати заявку"
#admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
list_display = ['order_customer', 'order_date', 'order_number', 'order_adress', 'oder_brand', 'butt_ord']
def butt_ord(self, obj):
link_buttom = reverse('downloadWordorder', args=[obj.pk])
return mark_safe(f'<a class="button" label="Заявка" href="{link_buttom}">Заявку</a>')
butt_ord.short_description = "Сформувати"
enter image description here
enter image description here
I have a models with FileField for videos.
When i upload only one video i can return it with this code in the view.py:
def cours(request, id, slug):
c = Cours.objects.get(id=id, slug=slug)
p = Plan_simple.objects.get(cours=c)
return render(request, 'upload/cours.html', locals())
But when i upload two or more videos whith formset, and i change get fuction by filter it doesn't work:
def cours(request, id, slug):
c = Cours.objects.get(id=id, slug=slug)
p = Plan_simple.objects.filter(cours=c)
return render(request, 'upload/cours.html', locals())
the models.py
class Cours(models.Model):
titre = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
auteur = models.CharField(max_length=42)
comment = models.TextField(null=True)
link = models.CharField(max_length=100)
date = models.DateTimeField(default=timezone.now, verbose_name="Date de parution")
categorie = models.ForeignKey('Categorie', on_delete=models.CASCADE)
def save(self, *args, **kwargs):
self.slug = slugify(self.titre)
super(Cours, self).save(*args, **kwargs)
class Meta:
verbose_name = "cours"
db_table = "cours"
ordering = ['date']
class Plan_simple(models.Model):
partie = models.CharField(blank=True, max_length=100)
date = models.DateTimeField(default=timezone.now, verbose_name="Date de parution")
vid = models.FileField(upload_to='file/', blank=True, null = True)
cours = models.ForeignKey(Cours, related_name = "plan_simple", on_delete=models.CASCADE)
def __str__(self):
return self.partie
class Meta:
db_table = "plan_simple"
Can you help me?
Thanks
The issue is with this line. It does not request anything from the database. It only specifies a filter.
p = Plan_simple.objects.filter(cours=c)
You should change it to this...
p = Plan_simple.objects.filter(cours=c).all()
How can I pass the foreign key values from my model to my serialised json object?
Now I have this three models,
class Fleet(models.Model):
fleet_id = models.IntegerField('Id flota', primary_key=True, unique=True)
fleet_name = models.CharField('Nombre flota', max_length=20, unique=True)
def __str__(self):
return self.fleet_name + ' ' + str(self.fleet_id)
class Device(models.Model):
dev_eui = models.CharField(max_length=16, primary_key=True, unique=True)
producer = models.CharField(max_length=20)
model = models.CharField(max_length=20)
dev_name = models.CharField(max_length=20, unique=True)
fleet_id = models.ForeignKey(Fleet, on_delete=models.CASCADE)
def __str__(self):
return self.dev_eui
class DevData(models.Model):
data_uuid = models.UUIDField(primary_key=True, default=uuid.uuid1, editable=False)
frequency = models.IntegerField()
data_1 = models.FloatField()
data_2 = models.FloatField(null=True, blank=True)
dev_eui = models.ForeignKey(Device, on_delete=models.CASCADE) #hay que saber porque añade _id
def __str__(self):
return self.dev_eui
And what I'm doing is call my view function in my JS code to obtain some data like this.
def getData(request):
ctx = {}
if request.method == 'POST':
select = int(request.POST['Select'])
data = DevData.objects.order_by('dev_eui','-data_timestamp').distinct('dev_eui')
nodes = Device.objects.all()
fleets = Fleet.objects.all()
data = loads(serializers.serialize('json', data))
nodes = loads(serializers.serialize('json', nodes))
fleets = loads(serializers.serialize('json', fleets))
ctx = {'Data':data, 'Nodes':nodes, 'Fleets':fleets}
return JsonResponse(ctx)
And inside my js file I filter it with some if else conditionals.
This works well, but I'm sure I can do it directly in my view but I don't know how. How can I obtain just one JSON object with the three models information combined?
Thank you very much!!
You can write a custom serializer like this:
from django.core.serializers.json import Serializer
class CustomSerializer(Serializer):
def end_object(self, obj):
for field in self.selected_fields:
if field == 'pk':
continue
elif field in self._current.keys():
continue
else:
try:
if '__' in field:
fields = field.split('__')
value = obj
for f in fields:
value = getattr(value, f)
if value != obj and isinstance(value, JSON_ALLOWED_OBJECTS) or value == None:
self._current[field] = value
except AttributeError:
pass
super(CustomSerializer, self).end_object(obj)
Then use it like this
serializers = CustomSerializer()
queryset = DevData.objects.all()
data = serializers.serialize(queryset, fields=('data_uuid', 'dev_eui__dev_eui', 'dev_eui__fleet_id__fleet_name'))
I have wrote an article regarding serializing nested data here. You can check that out as well.
This is the error am getting:
QuerySet.annotate() received non-expression(s): 17
What I want is a subquery that will do something similar to the
select * from inecdb.announced_pu_results
where polling_unit_uniqueid in
(
select uniqueid from polling_unit
where lga_id = (select uniqueid from lga where uniqueid= 17)
);
The subquery
obj3 = Pu_results.objects.filter(polling_unit_uniqueid__in=Subquery(Unit.objects.filter(lga_id=obj1)))
is not displaying any result please can any one help
This is my view
if request.method == 'POST':
selected_item = request.POST.get('item_id') #This is from html select box
obj = Lga.objects.get(lga_id=selected_item)
obj1 = obj.lga_id
obj3 = Pu_results.objects.filter(polling_unit_uniqueid__in=Subquery(Unit.objects.filter(lga_id=obj1)))
for obt in obj3:
print(obt.party_score) #I want looping results here
This is my Model
from django.db import models
from django.urls import reverse
#from django.urls import reverse
class Unit(models.Model):
uniqueid = models.IntegerField(primary_key=True)
polling_unit_id = models.IntegerField(blank=False)
ward_id = models.IntegerField(default=False)
lga_id = models.IntegerField(default=False)
uniquewardid = models.IntegerField(default=True)
polling_unit_number = models.CharField(max_length=50, unique=True)
polling_unit_name = models.CharField(max_length=51)
#pulling_unit_number = models.CharField(max_length=50)
polling_unit_description = models.CharField(max_length=300)
lat = models.CharField(max_length=255)
long = models.CharField(max_length=255)
entered_by_user = models.CharField(max_length=50)
date_entered = models.DateTimeField(blank=False)
user_ip_address = models.CharField(max_length=50)
def get_absolute_url(self):
#return f"/products/{self.id}/"
return reverse("polling:inec-pull-result", kwargs={"uniqueid": self.uniqueid})
class Lga(models.Model):
uniqueid = models.AutoField(primary_key=True)
lga_id = models.IntegerField()
lga_name = models.CharField(max_length=50)
state_id = models.IntegerField()
lga_description = models.TextField(blank=True, null=True)
entered_by_user = models.CharField(max_length=50)
date_entered = models.DateTimeField()
user_ip_address = models.CharField(max_length=50)
class Meta:
db_table = 'lga'
class Article(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()
active = models.BooleanField(default=True)
You need to make sure that the queryset you use for the subquery returns just one column, use values() for that. Note that Subquery isn't needed:
units = Unit.objects.filter(lga_id=obj1).values('uniqueid')
obj3 = Pu_results.objects.filter(polling_unit_uniqueid__in=units)
Read the documentation for the in lookup for a more detailed explanation of passing a QuerySet to in.
This also works:
obj3 = Pu_results.objects.filter(
polling_unit_uniqueid__in = Subquery(
Unit.objects.values('uniqueid').filter(lga_id=obj1)
)
)
I want to set the value of is_delete field True when i click delete button from list page.
This is my views.py file
def delete_faculty(request, faculty_id):
faculty = Faculty.objects.get(id=faculty_id)
faculty.is_delete = True
return redirect('faculty-list')
This is models.py
class Faculty(models.Model):
name = models.CharField(max_length=255, unique=True)
established = models.DateField()
about = models.TextField()
status_choice = (
('active', 'Active'),
('disabled', 'Disabled'),
('paused', 'Paused')
)
status = models.CharField(choices=status_choice, max_length=15)
is_delete = models.BooleanField(default=False)
def __str__(self):
return self.name
This code can not set the value of True in is_delete field . How can i solve this?
# You just need to save the data
def delete_faculty(request, faculty_id):
faculty = Faculty.objects.get(id=faculty_id)
faculty.is_delete = True
faculty.save()
return redirect('faculty-list')