Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django How to generate and save image when entity made with CreateView?
I'm currently developing a django aplication. With one of my models I need to generate a barcode and save it as an image and upload it in one of the models field. I tried to generate the image in the save function of the model as shown bellow. The image is generated and saved to the correct folder, but when I look at the entitys they always have the default image saved with them. models.py: class ItemEntity(models.Model): sub_type = models.ForeignKey(ItemSubType, on_delete= models.PROTECT) location = models.ForeignKey(WarehouseBin, on_delete= models.PROTECT) supplyer = models.ForeignKey(ItemSupplyers, on_delete= models.PROTECT) quantity = models.IntegerField() unit = models.ForeignKey(Units, on_delete= models.PROTECT) creation_date = models.DateTimeField(default= timezone.now) expiration_date = models.DateTimeField() time_of_consumption = models.DateTimeField(null= True) barcode = models.ImageField(default='default_barcode.jpg', upload_to= 'media/barcodes') def __str__(self): return self.sub_type.name + " " + str(self.quantity) + " " + str(self.unit) def save(self): super().save() datas=self.pk,self.location,self.sub_type # Datas to give to my barcode generator code self.img = Image.new('RGB',(1,1)) # Declaring an empty image variable BarcodeGenerator(datas,self) # Barcode generator the barcode it generates is put intu self.img variable self.img.save("/home/makiverem/projects/pina/media/media/barcodes/"+str(self.pk)+".jpg") # Saving the image to media/media/barcodes #I MISS SOMETHING FROM HERE I THINK self.barcode=self.img #Making the models barcode field equal to self.img views.py: class ItemEntityCreateView(CreateView): model=ItemEntity form_class = ItemEntityForm def get_form_kwargs(self, *args, **kwargs): kwargs … -
how to save Ratelimit result in Redis in Django
I'm using in ratelimit to limit the requests to my server in Django, I can see that ratelimit uses Django cache to count the request etc.. and I want to change it to be in Redis. my motivation is to change it only for the ratelimit and not for all of my application caching. there is any configuration for that? Thanks! -
Django Navbar No Reverse Match error - how do I fix this?
I'm receiving the below error when trying to link up my navbar in base.html in Django. NoReverseMatch at / 'home' is not a registered namespace I'm not sure why it's not working, any help would be much appreciated! base.html: <ul class="nav navbar-nav ms-auto"> <li class="nav-item"><a class="nav-link text-white" href="{% url 'home:home' %}"><strong>Home</strong></a></li> <li class="nav-item"><a class="nav-link text-white" href="{% url 'home' %}"><strong>My Health</strong></a></li> <li class="nav-item"><a class="nav-link text-white" href="{% url 'login' %}"><strong>Login</strong></a></li> <li class="nav-item"><a class="nav-link text-white" href="{% url 'signup' %}"><strong>Signup</strong></a></li> </ul> urls.py: urlpatterns = [ path('', views.home, name='home'), path('signup/', views.signup, name='signup'), path('login/', views.login, name='login'), path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url("favicon.ico"))), path('success/', views.success_view, name='success'), ] views.py: def home(request): return render(request, 'HealthHub/home.html') -
Django - Twilio schedule message is not sending
I am trying to send SMS via schedule message send functionality using Twilio. However, messages are not sent as per the scheduled time. Here is my code. message = clientSMS.messages.create( media_url=attachimage, body=editor, from_=settings.SERVICE_ID, to=selectedphone, schedule_type='fixed', send_at=FinalScheduleTime.isoformat() + 'Z', ) Message SID is generated successfully. But the SMS is sent at the scheduled time. Is there anything that I am missing out on, Please help me. -
how to collect all anchor_text_link and anchor_text with conataing single title and published_post in one object
[{'pubished_post': 4, 'anchor_title': 'another broken link article test', 'anchor_text_link': 'https://duhjodnon.fdgh', 'anchor_text': 'dhjijnjfoen'}, {'pubished_post': 4, 'anchor_title': 'another broken link article test', 'anchor_text_link': 'https://duhjodnon.in', 'anchor_text': 'nnnlnlkmn'}, {'pubished_post': 4, 'anchor_title': 'another broken link article test', 'anchor_text_link': 'https://dhdjjdnjn.connnn', 'anchor_text': 'mdnkbuhvsinksmjbxua'}, {'pubished_post': 3, 'anchor_title': 'this game title', 'anchor_text_link': 'https://googlabhgahbhe.cm', 'anchor_text': 'nbsuhguhbd'}, {'pubished_post': 3, 'anchor_title': 'this game title', 'anchor_text_link': 'https://gahihabb.insj', 'anchor_text': 'frfbrfbrbf'}, {'pubished_post': 3, 'anchor_title': 'this game title', 'anchor_text_link': 'https://googlabhgahbhe.cmajakn', 'anchor_text': 'fbwefibwe'}, {'pubished_post': 3, 'anchor_title': 'this game title', 'anchor_text_link': 'https://trwtfuhwbhbsguv.jcbc', 'anchor_text': 'wenfbiwebfjibewif'}, {'pubished_post': 2, 'anchor_title': 'jsbhbsjh valorent pc game', 'anchor_text_link': 'https://gdmskmksm', 'anchor_text': 'jhdjihdjnjdn'}, {'pubished_post': 2, 'anchor_title': 'jsbhbsjh valorent pc game', 'anchor_text_link': 'https://hrfsbsm.cm', 'anchor_text': 'vbhbdibejid'}] I want this object be like {'pubished_post': 4, 'anchor_title': 'another broken link article test', 'anchor_text_link':['https://duhjodnon.fdgh','https://duhjodnon.in','https://dhdjjdnjn.connnn'], 'anchor_text': ['dhjijnjfoen','nnnlnlkmn','mdnkbuhvsinksmjbxua']}, Similarly for same thing for other objects too PLZ someone help i wanted to covert all the objects in single object with one title and published_post with all the links and text -
django migrations not working in docker container
I have a project developed in djnago and when i add a new field to models.py and run makemigrations and migrations it works fine , my problem is when i run docker container it seems the migartions are not applied and new field is not added to model since i get this error when i try to open the admin panel : ProgrammingError at /admin/ column account_profile_user.uid does not exist LINE 1: ...er"."level", "account_profile_user"."user_photo", "account_p... which uid is new field that i added to models.py . this is Dockerfile: FROM python:alpine RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev \ && apk add jpeg-dev zlib-dev libjpeg libffi-dev ENV CRYPTOGRAPHY_DONT_BUILD_RUST=1 WORKDIR /app COPY requirements.txt /tmp/ RUN pip install --requirement /tmp/requirements.txt COPY . /app/ ENTRYPOINT [ "./entrypoint.sh" ] and this the entrypoint.sh : #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi python manage.py makemigrations python manage.py migrate python manage.py collectstatic --noinput exec "$@" and this is docker compose: services: account: build: context: . dockerfile: Dockerfile env_file: - ./envs/development.env volumes: - ./:/app - /store/account/media:/app/media - /store/account/static:/app/static … -
Why does it give an error "not a registered namespace"?
I'm trying to make a data entry form without using forms.py. When trying to display the form, it gives the error "'blog' is not a registered namespace". I think that I could confuse something with urls.py. urls.py from django.urls import * from . import * from django.conf.urls.static import * from django.contrib.auth import views as auth_views from django.conf import settings from blog import views blog = "blog" urlpatterns = [ path('', views.index), path('create', views.create, name='create') ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) vievs.py def create(request): if (request.method == 'POST'): obj, created = Posts.objects.get_or_create(title=request.POST.get("title")) obj.text=request.POST.get("text") obj.save() return render(request, 'create.html') -
Decrypt function not working in python, below is the code
import hashlib from binascii import hexlify from binascii import unhexlify from Crypto.Cipher import AES class AppCrypto: __KEY: str = None __iv = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" def __init__(self, key: str = None) -> None: """ Initialize the class. :param key: The key for the Encryption and Decryption. """ self.__KEY = key def pad(self, data: str): """ Pad the data to be encrypted. :param data: The str data to be encrypted. """ length = 16 - (len(data) % 16) data += chr(length) * length return data def unpad(data): return data[0:-ord(data[-1])] def __get_cipher(self) -> AES: """ Get the cipher object. :param key: The key to be used for encryption. """ bytearrayKey = bytearray() bytearrayKey.extend(map(ord, self.__KEY)) return AES.new( hashlib.md5(bytearrayKey).digest(), AES.MODE_CBC, self.__iv.encode("utf-8"), ) def encrypt(self, plainText: str) -> bytearray: """ :param data: The data to be encrypted. :return: The encrypted data. """ plainText = self.pad(plainText) enc_cipher = self.__get_cipher() return hexlify(enc_cipher.encrypt(plainText.encode("utf-8"))).decode("utf-8") def decrypt(self, encryptedText: str) -> str: """ :param data: The data to be decrypted. :return: The decrypted data. """ dec_cipher = self.__get_cipher() data = unhexlify(dec_cipher.decrypt(encryptedText).decode('utf-8')).encode("utf-8") return self.unpad(data) from AppCrypto import AppCrypto appCrypto = AppCrypto("729C6F92987DCEF8D955D23ED2269354") enc_data = appCrypto.encrypt("Hello, Ninranjan") Output: 0f657d48535896ab573a4cb7e9a967e8d409b7f4f537c3157949abd91e221bf2 plain_tx = appCrypto.decrypt("0f657d48535896ab573a4cb7e9a967e8d409b7f4f537c3157949abd91e221bf2") gives error like TypeError at /propertytax/receipt_entry/ Object type <class 'str'> cannot be passed to … -
how set model for comments-django-xtd
hi guys im new in django. i need to have comments,replay comments, like and dislike, count of replays, numbers of likes and dislikes. so i found django-comments-xtd package. i tried to set it in my project but i didnt found any documenttions that explains well about how use it. i found this link about that but it doesnt explain how i should define my model -
How do I fix my django admin page not loading css although having correct configuration?
I am aware this question has been asked a thousand times, but none of the solutions have worked for me... I was working on the Django tutorial, but when I created the superuser, and entered the admin page, the css was missing. The weird thing is, is that when I check the page source from chrome, and click one of the css references in the html, my computer manages to download the stylesheet. It only had a relative path, and when using chrome's debugger, I can see the page taking some time to download the css. So I guess the static paths are configured correctly, the page actually loads the css, but somehow it is not reflected in the view? I have no idea how such a thing can happen. Things I have tried until now: Setting STATIC_URL Setting STATIC_ROOT Setting PROJECT_DIR Setting static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) to urlpatterns Deleting static files and doing manage.py collectstatic every time i modified any files Making migrations again Adding base dir + "templates" to TEMPLATES Setting DEBUG from False to True again I must be missing something simple, but I can't see it. Any help is greatly appreciated. In settings.py: PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = … -
Django Grouping(annotating) by Order and Get all Values
I have following model class Attempt(BaseModel): category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True) answer = models.ForeignKey(to=ModelAnswer,null=True, blank=True,on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) order = models.PositiveIntegerField(null=True, blank=True) def __str__(self): return self.category.name class Meta: ordering = ['order'] This model will have 10 records for common order id i.e 1 if there are 10 records on the attempt model same order number will be assigned to them i.e order =1 for the next 10 attempt, same order will be assigned i.e order=2 because 10 records are added at once. I just want to show those 10 records inside the same array as the response having order = 1 and next array for order=2 here are my views class ListAttemptSerializer(generics.ListAPIView): serializer_class = serializers.AttemptSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): data = Attempt.objects.filter(user=self.request.user).values('order').annotate( total=Count('order') ).all() return data Serializer.py class AttemptSerializer(serializers.Serializer): answer = ListAnswerSeiralizer(many=True) category = serializers.CharField() class Meta: model = Attempt fields = [ 'category', 'answer', ] My expected response will somehow look like this [ {"answer": [{ "id": 1, "user": 1, "questions": "what are the facts of this situation?", "subcategory": "Circumstance", "is_intentional": "True", "answer": "string", "created_at": "2022-09-05T10:59:59.551583" }, { "id": 2, "user": 1, "questions": "what are the facts of this situation?", "subcategory": "Circumstance", "is_intentional": "True", … -
how add row dynamically in django formset
In my django app I have two models i.e Product and Real which are connected by many to many relationship. To add the data dynamically in my tables I want to use javascript to Add row or Remove Row button in my forms but unable to do so. Here are the details: Models.py from dataclasses import Field from django.db import models class Product(models.Model): name = models.CharField(max_length = 150) quantity = models.IntegerField() cost = models.DecimalField(max_digits=15, decimal_places=0) sell = models.DecimalField(max_digits=15, decimal_places=0) class Real(models.Model): payment_id = models.CharField(max_length = 150) company = models.CharField(max_length = 150) product = models.ManyToManyField(Product, symmetrical=False) Forms.py from .models import Product, Real from django import forms from django.forms import formset_factory class ProductForm(forms.Form): name = forms.CharField() cost = forms.DecimalField() sell = forms.DecimalField() quantity = forms.IntegerField() ProductFormset = formset_factory(ProductForm) class RealForm(forms.Form): payment_id = forms.CharField() company = forms.CharField() product = ProductFormset() Views.py from django.shortcuts import render, redirect from django.forms import modelformset_factory from .models import Product, Real from .forms import RealForm, ProductForm, ProductFormset def post(request): if request.POST: form = Real(request.POST) form.product_instances = ProductFormset(request.POST) if form.is_valid(): real = Real() real.payment_id = form.cleaned_data['payment_id'] real.save() if form.product_instances.cleaned_data is not None: for item in form.product_instances.cleaned_data: product = Product() product.name = item['name'] product.cost = item['cost'] product.sell = item['sell'] product.sell = … -
Plot Chart.js scatter graph in Django using huge data
I'm developing a scatter graph to visualize the trend of product volume for every product count. x: product count y: product volume From django view, two array list was pass to chart javascript in django template. Here is the code: <script> const volume = {{product_volume}} // <--- array list of product_volume const count = {{product_count}} // <--- array list of product_count const p1ctx = document.getElementById('VolumeChart'); const P1Chart = new Chart(p1ctx, { data: { datasets: [{ type: 'scatter', label: 'Volume', data: volume, // <-------------------- Target to assign 'x' and 'y' data backgroundColor: 'rgb(255, 99, 132)' }], }, . . . </script> However, with huge data (approx.: 15,000), how can I simplify the process of data labelling in the JavaScript using array list of product count and product volume? -
how to autoupdate category by the amount of products in django model
I have a model of the category with title and count and I also have another model called Products which has category as one of its foreign-key. How can I auto-update the category count field by the number of products that comes under the same category? class Category(models.Model): title = models.CharField(max_length = 20) count = models.IntegerFIeld() class Product(models.Model): title = models.CharField(max_length = 20) category = models.ForeignKey(Category, on_delete = models.CASCADE) -
Only one json displays on localhost [closed]
I simply put JSON in variable li and try to show in localhost by return JsonResponse(li) But from the original list [{'_id': 'SC', 'cast_count': 60576}, {'_id': 'General', 'cast_count': 562298}, {'_id': 'OBC', 'cast_count': 389510}, {'_id': 'ST', 'cast_count': 2700}, {'_id': '', 'cast_count': 1904}] I got only random one of this such as: {'_id': 'ST', 'cast_count': 2700} Instead of the full list that has to display Note: I know I'm lacking in basic concept of django so pls help me and if there is some problem in question pls comment or flag instead of downvote -
Error in Downloading Files from Django app in Production with Gunicorn & Nginx
I have deployed my Django app on AWS EC2 Instance using this guide. Everything is working fine but the error arises when I download an excel file. (Excel is created using opnenpyxl library). While downloading an xlsx file the application is returning download.htm file. Everything work great on a development server. I tried Adding and removing the download tag. <a href="{% url 'download_estimate_excel_file' project.id project.name %}" class="dropdown-item" download> Download Excel </a>. [Didn't Work] Adding [service] Environment="LANG=ru_RU.UTF-8" to gunicorn.service file (found this on StackOverflow also). [Didn't Work] Thanks in advance. -
Django annotate conditional value
Lets say i have a model like this : class modelA(models.model): name = models.Charfield() class modelB(models.model): model_A = models.ForeignKey('modelA', on_delete=models.CASCADE) value = models.IntegerField() class modelC(models.model): model_A = models.ForeignKey('modelA', on_delete=models.CASCADE) value = models.IntegerField() How can i annotate the query so i can achieve something like this : q = modelA.objects.all().annotate(value= # IF THERE IS modelC exist with related modelA THEN modelC.value ELSE modelB.value #) -
My user contact details from front-end not saved in django admin
I am trying to get the Contact information from my "Contact Us" page to my Django admin but its not displaying, I don't find what could be wrong... my models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=100) public_date = models.DateField() public_time = models.TimeField() image = models.ImageField(upload_to='images/',null=True) body = models.TextField() class Meta: verbose_name = "Post" verbose_name_plural = "Posts" ordering = ['public_date'] def summary(self): return self.body[:100] def pub_date(self): return self.public_date.strftime('%b %e,%y') # to give layout for time and date def __str__(self): return self.title class Contact(models.Model): msg_id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) email = models.EmailField(max_length=70, default="") phone = models.CharField(max_length=70, default="") desc = models.TextField(max_length=500, default="") timeStamp = models.DateTimeField() def __str__(self): return self.name + '---' + self.email # if we write only upto self.name, only name is visible in contact. forms.py from django.forms import ModelForm from .models import Contact class ContactForm(ModelForm): class Meta: model = Contact fields = '__all__' views.py from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from blog.models import Post from .forms import ContactForm from django.shortcuts import get_object_or_404 def allpost(request): post = Post.objects.all() #post = [post[i:i + 3] for i in range(0, len(post), 3)] return render(request,'posts.html',{'posts':post}) def detail(request,blog_id): detail = get_object_or_404(Post, pk = blog_id) #return render(request,'/home/deatils',{'post':detail}) return render(request,'details.html',{'post':detail}) def … -
Set xaxis range plotly dash
How can I set a maximum view of data so that the line graph will not be crowded. My graph looks like this image as you can see the lines are crowded. I want it too looks like this image. Only the recent 9 data will be viewed app.layout = html.Div([ html.Div(style={'display': 'flex'}, children=[ dcc.Graph( id='graph-ph', config={ 'displayModeBar': False, 'displaylogo': False, 'modeBarButtonsToRemove': ['zoom2d', 'hoverCompareCartesian', 'hoverClosestCartesian', 'toggleSpikelines'] }, figure={ 'data': [ {'x': [], 'y': [0, random.random()], 'mode':'lines+markers', }], 'layout': { 'title': 'pH (pH)', 'xaxis': { 'rangeslider': {'visible': True}, }, }, }, ), ]) @app.callback(Output('graph-ph', 'extendData'), [Input('interval-graph-update', 'n_intervals')], [State('graph-ph', 'figure'), ]) def update_extend_traces_traceselect(existing, n_intervals): trace_selection = 0 x_new = datetime.datetime.now() y_new = random.random() return dict(x=[[x_new]], y=[[y_new]]), [trace_selection] -
FileView.get() missing 1 required positional argument: 'request' - class FileView
so i want to called func to html. but when i click the button, it have error message. what i want is, i can save bytes to string and save it to file text. f contains with b'5&\xd7\x8c', it's the result from encryption FileView.get() missing 1 required positional argument: 'request' i don't know what's wrong, can someone check it please? def create_file(f): with open("file.txt", 'w') as file: return file.write(str(f)) class FileView(View): def get(f, self, request, *args, **kwargs): return HttpResponse(f, content_type='text/plain', headers={'Content-Disposition': 'attachment; filename=file.txt'}) def homepage(request): form = AudioForm() if request.method == "POST": form = AudioForm(request.POST, request.FILES) if form.is_valid(): form.save() last_audio = Audio_store.objects.all().last() plaintext = Audio_store.objects.all().values_list('password').last() key = Audio_store.objects.all().values_list('key').last() pt = plaintext[0] ky = key[0] print(pt) print(ky) context={'form':form, 'last_audio':last_audio} enc = encrypt(ky, pt) print(enc) download = create_file(enc) print(download) return render(request, "homepage.html", context) context={'form':form} return render(request, "homepage.html", context=context) in urls: path("", views.homepage, name="homepage"), # to call homepage path("", views.encrypt, name="homepage"), path("create_file", views.FileView.as_view(), name="create_file"), in html to called: <a href="{% url 'create_file' %}"> Download </a> -
Django nested serializer giving me None for all fields
So I'm working with Django and djangorestframework (versions 3.2.12 and 3.12.4, respectively) and I'm running into an issue with nested serializers. I've got FantasyLeague and FantasyLeagueSettings models. FantasyLeagueSettings has a FK to FantasyLeague models.py class FantasyLeague(models.Model): name = models.CharField(max_length=100) managers = models.ManyToManyField(User) yahoo_league_id = models.CharField(max_length=20, blank=True, null=True) class FantasyLeagueSettings(models.Model): league = models.ForeignKey(FantasyLeague, on_delete=models.CASCADE, related_name='settings') max_teams = models.IntegerField(blank=True, null=True) num_playoff_teams = models.IntegerField(blank=True, null=True) playoff_start_week = models.IntegerField(blank=True, null=True) I'm serializing them like so: serializers.py class FantasyLeagueSettingsSerializer(serializers.ModelSerializer): class Meta: model = FantasyLeagueSettings fields = ['max_teams', 'num_playoff_teams', 'playoff_start_week'] class FantasyLeagueSerializer(serializers.ModelSerializer): managers = UserSerializer(read_only=True, many=True) settings = FantasyLeagueSettingsSerializer(many=False, read_only=True) class Meta: model = FantasyLeague fields = ['id', 'name', 'managers', 'settings', 'yahoo_league_id' ] But for some reason FantasyLeagueSerializer(league).data gives me a value of None for all of the settings fields (even though the settings data exists) Testing code: league = FantasyLeague.objects.get(pk=1) print('🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥') print(FantasyLeagueSerializer(league).data) # FantasyLeagueSerializer(league).data: {'id': 1, 'name': 'PLAYING FOR KEEPS', 'managers': [OrderedDict([('id', 1), ('username', 'Smurflo'), ('settings', OrderedDict([('selected_theme', 'kanagawa')])), ('is_staff', True)])], 'settings': OrderedDict([('max_teams', None), ('num_playoff_teams', None), ('playoff_start_week', None)]), 'yahoo_league_id': '461051' } # Note how all of the settings fields are None # Even though league.settings clearly has data and FantasyLeagueSettingsSerializer works print('🎆🎆🎆🎆🎆🎆🎆🎆🎆🎆🎆🎆🎆🎆🎆🎆🎆🎆🎆') print(FantasyLeagueSettingsSerializer(league.settings.all()[0]).data) # {'max_teams': 12, 'num_playoff_teams': 6, 'playoff_start_week': 15} Anyone know what's going on here? … -
how to get django-taggit custom tags in view
I am trying to get two categories of tags to work using django-taggit on one model. Everything seems to be working right in the admin but I can't figure out how to write a view that will let me use two categories of tags. class Photo(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=255) created = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='photos/') submitter = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) year = models.ManyToManyField(Year, blank=True) people = TaggableManager(through=TaggedPeople, verbose_name='People') tags = TaggableManager(through=TaggedGeneric, verbose_name='Tags') def __str__(self): return self.title Then in my view I have class PhotoListView(ListView): model = Photo template_name = 'photoapp/list.html' context_object_name = 'photos' class PhotoTagListView(PhotoListView): template_name = 'photoapp/taglist.html' def get_tag(self): return self.kwargs.get('tag') def get_queryset(self): return self.model.objects.filter(tags__slug=self.get_tag()) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["tag"] = self.get_tag() context["tags"] = GenericTag.objects.all().order_by('name') context["people"] = PeopleTag.objects.all().order_by('name') return context The "tag" tag is working correctly. How do I get the "people tag" to work with a template to display all the photos with a certain person? -
How to integrate django rest framework with clamav
How can I integrate clamav with django rest framework? I am trying to scan uploaded files via drf with clamav? I installed clamav from https://www.clamav.net/ here is my code ... file = self.request.FILES.get('file') # check a file for viruses if file: print("checking file for viruses") from tempfile import mkstemp from py_clamav import ClamAvScanner import os tmpfile = mkstemp()[1] f = open(tmpfile, 'wb') f.write(file.read()) f.close() with ClamAvScanner() as scanner: # scan file by path infected, virname = scanner.scan_file(tmpfile) os.unlink(tmpfile) if infected: return Response({'message':"virus was detected in your file"},status=status.HTTP_400_BAD_REQUEST) ... I am getting the error: raise FileNotFoundError('Not found libclamav') FileNotFoundError: Not found libclamav Why are my getting this error? Is there a better library I can do this with? -
How I can get data to pop up in django
please how can I get attribut id_benevole Class Participer(Models) i need to show it in the pop up i use this method but nothing is displayed Thanks in advance This is -------->Models.py class Participer(models.Model): id_benevole = models.CharField(max_length=150,null=False,blank=False) id_mission = models.CharField(max_length=150,null=False,blank=False) # def __str__(self): def __str__(self): return self.id_mission This is ------->Views.py def getLB(request): participer=Participer.objects.all() context={ 'participer':participer } print(participerss) return render(request, 'home/Association.html',context) This is ----------> Association.html {% for miss in missions %} <th scope="row">{{miss.id}}</th> <td>{{miss.nom}}</td> <td>{{miss.domaine}}</td> <td>{{miss.lieu}}</td> <td style="white-space: nowrap;width: 1%;" >{{miss.date_publier}}</td> <td style="text-align: center;">{{miss.nombre_participant}}</td> <td>{{miss.association.association.nom_association}}</td> <td><a type="button" class="btn btn-danger mt-5" data-bs-toggle="modal" data-bs-target="#myModal" class="col-11 text-center mt-3">Voir liste des bénévoles</a></td> <div class="modal mt-5" id="myModal" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="d-flex justify-content-center text-danger"> <h4>Liste des bénévoles participants</h4> </div> {% for par in participer %} <div class="modal-header"> {{par.id_mission}} {{par.id_benevole}} </div> {% endfor %} <div class="modal-footer"> <div class="col-11 text-center mt-3"> <input class="btn gradient-bg" type="submit" value="Confirmer"/> <input type="button" class="btn gradient-bg" data-bs-dismiss="modal" value="Annuler"/> </div> <div> </div> </div> </div> {% endfor %} -
Get count of Options in Django ChoiceField
I have a choiceField in a model and I want to get the count of each choice in my homepage. I alos want the counts to be clickable so that when it is clicked, it redirects me to a page containing all buildings related to it. This is my models.py class Property(models.Model): landlord = models.ForeignKey(User, related_name="lanlord", on_delete=models.CASCADE) title = models.CharField( max_length= 500 ) description = models.CharField( max_length= 50000 ) BUILDING_CHOICES = [ ("Flat" , "Flat" ), ("Duplex" , "Duplex" ), ("Bungalow" , "Bungalow" ), ("Apartment" , "Apartment" ), ("Shop" , "Shop" ), ("Warehouse" , "Warehouse" ), ("Storey Building" , "Storey Building" ), ] buildingtype = models.CharField( max_length=20, choices=BUILDING_CHOICES, default='Bungalow' ) This is my home page <ul class="home4_iconbox mb0"> <li class="list-inline-item"><div class="icon"><span class="flaticon-house"></span><a> Storey Building</a></div></li> <li class="list-inline-item"><div class="icon"><span class="flaticon-house-1"></span><a>Shop</a></div></li> <li class="list-inline-item"><div class="icon"><span class="flaticon-house-2"></span><a>Duplex</a></div></li> <li class="list-inline-item"><div class="icon"><span class="flaticon-building"></span><a>Apartment</a></div></li> </ul> This is my views.py def home(request,): q = request.GET.get('q') if request.GET.get('q') != None else '' props = Property.objects.filter( Q(title__icontains = q) | Q(address__icontains = q) | Q(buildingtype__icontains = q) ) property = Property.objects.all() properties = Property.objects.filter(is_approved = True)[:5] context = {"props":props, "property": property, "properties": properties} return render(request, "base/index.html", context)