Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Login form using django
I'm doing a Python user login, using Django. I'm trying to create authentication my way, checking in my db if username exists and password is correct. When I type username and password,and both are correct, login does nothing, just reload login page. The same issue happens when I type wrong username and/or password, login page just reload, but in this case should show an error message. These are my forms.py and views.py: forms.py def login_view(request): title = 'LOGIN' if request.user.is_authenticated: return redirect('board.html') if request.method =='POST': form = UserLoginForm(request=request, data=request.POST) if form.is_valid(): username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.info(request, "You are now logged in as {username}") return redirect('/') else: messages.error(request, "Invalid username or password.") else: messages.error(request, "Invalid username or password.") form = UserLoginForm() return render(request=request, template_name="/login.html", context={"form": form}) views.py class UserLoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError('No user found with this username') if not user.check_password(password): raise forms.ValidationError('Wrong password') if not user.is_active: raise forms.ValidationError('This user is not active') return super(UserLoginForm, forms).clean(*args, **kwargs) Where am I wrong? I'm … -
Making multiple filters in function filter() (Django)
What I want to do is to have multiple values to filter out the data. I want to have ResourcePost objects with resource_category with values of user.helpseekerprofile.rc1 user.helpseekerprofile.rc2 and user.helpseekerprofile.rc3. So I tried like below: def message_list_view(request): user = request.user def filter_watchlist(post): filtered = ResourcePost.objects.all().filter(resource_category=user.helpseekerprofile.rc_1)\ + ResourcePost.objects.all().filter(resource_category=user.helpseekerprofile.rc_2)\ + ResourcePost.objects.all().filter(resource_category=user.helpseekerprofile.rc_3) if post in filtered: return True else: return False post_list = ResourcePost.objects.all().filter(filter_watchlist).order_by("-date_created") page = request.GET.get("page", 1) paginator = Paginator(post_list, 20) try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) timestamp_now = datetime.datetime.now() context = { "mapbox_access_token": "pk." + os.environ.get("MAPBOX_KEY"), "timestamp": timestamp_now, "posts": posts, } return render(request, "donation/messages_home.html", context) However, TypeError came out saying "cannot unpack non-iterable function object". How can I fix this? -
Creating an API with query string parameters
This code was used to create an API that could be searched through with start and end parameters. import time from django.http import JsonResponse from django.shortcuts import render # Create your views here. def index(request): return render(request, "posts/index.html") def posts(request): # Get start and end points start = int(request.GET.get("start") or 0) end = int(request.GET.get("end") or (start + 9)) # Generate list of posts data = [] for i in range(start, end + 1): data.append(f"Post #{i}") # Artificially delay speed of response time.sleep(1) # Return list of posts return JsonResponse({ "posts": data }) It's pretty basic and I am trying to replicate it but I would like to use this with a QuerySet of posts. I'm finding it quite difficult to work my way around this though. My first attempt: def posts_search(request): start = int(request.GET.get("start") or 0) end = int(request.GET.get("end") or (start + 9)) posts = Post.objects.all() data = [] for i in range(start, end + 1): for post in posts: data.append(post) time.sleep(1) return JsonResponse({ "posts": data }) But I got this TypeError: Object of type Post is not JSON serializable So for my second attempt, I altered the JsonResponse so it reads: return JsonResponse([post.serialize() for post in data], safe=False) On … -
Django insert pandas dataframe into model filefield
Closed. This question needs details or clarity. It is not currently accepting answers. Add details and clarify the problem you’re solving. This will help others answer the question. You can edit the question or post a new one. Closed 12 hours ago. (Private feedback for you) in Django I have multiple dataframes I want to insert df into the model as file field ( the target to add download links in html to down load those dataframes as Excel files ) I tried the below in model file from django.db import models class Script_files_mod(models.Model): title = models.CharField(max_length=500,blank=True,null=True) type_operation = models.CharField(max_length=500,blank=True,null=True) attachment = models.FileField(upload_to='attachments/',) inside view.py from django.core.files.base import ContentFile from .models import Script_files_mod df1= df.to_csv() updated_file = ContentFile(df1) Script_files_mod.objects.create(title='BB',type_operation='before_merge',updated_file ) but file return empty -
CSS on my index.html is not showing any changes. Static image is also not appearing on my help.html. All details are available in question
This is my site on PythonAnywhere: http://fatimatestpro.pythonanywhere.com/ I have a static folder under my main project folder. I have done setting for static files in settings.py, My folder tree is emailpro --emailpro ----settings.py --emailapp --templates ----emailapp ------index.html --static ----images ------djangoguitar.jpg ----css ------first.css In settings.py, I have created STATIC_DIR = os.path.join(BASE_DIR, 'static') variable and passed it at bottom as STATIC_URL = '/static/' STATICFILES_DIRS =[ STATIC_DIR, ] My first.css has following code: h1{ color: red; } body { background-color: coral; } and index.html has the following code: <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <link rel="stylesheet" href="{% static "css/first.css" %}"> <meta charset="utf-8"> <title>Index</title> </head> Also my static image is also not working. With the same above mentioned settings, I am displaying the image in help.html. the code is below: <!DOCTYPE html> {% load staticfiles %} <html lang="en" dir="ltr"> <head> <link rel="stylesheet" href="images/djangoguitar.jpg"> <!"{% static "css/first.css" %}">> <meta charset="utf-8"> <title> Help </title> </head> Can someone help me in displaying image and CSS changes? Thanks -
Cannot fix Django NoReverseMatch error despite URL being withing urls.py
Before I go into detail, here is the line from the html document that results in the error, as well as views.py and urls.py: <input class="search" type="text" name="q" placeholder="Search Encyclopedia" action="{% url 'encyclopedia:findpage' %}" method="get"> (Yes there is a space betweeen url and 'encyclopedia:findpage') views.py findpage function: def findpage(request, name): pages = util.list_entries() wanted_pages = set() wanted_page = None for page in pages: if not wanted_page and page == name: wanted_page = util.get_entry(name) continue if name in page: wanted_pages.add(page) if wanted_page: return render(request, 'encyclopedia/page.html', { "title": name, "entry": wanted_page }) if wanted_pages and not wanted_page: return render(request, 'encyclopedia/index.html', { "entries": wanted_pages }) else: return render(request, 'encyclopedia/noresults.html') urls.py: from django.urls import path from . import views app_name = "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("<str:name>", views.wikipage, name="wikipage"), path("<str:name>", views.findpage, name='findpage'), path("create", views.newpage, name="newpage") ] When I run the Django project, I get a NoReverseMatch at /. The error from the webpage reads: In template /home/quinn/Desktop/cs50web/pset1/wiki/encyclopedia/templates/encyclopedia/layout.html, error at line 17 Reverse for 'findpage' with no arguments not found. 1 pattern(s) tried: ['(?P<name>[^/]+)$'] Line 17 is the piece of html I left at the top of this page. I've checked numerous sources in an attempt to fix this, but I cannot figure … -
How to fix error in creating nested comment?
I'm working on creating comment api for my project. this is my comment model: class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='comments') parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True,blank=True, related_name='replys') body = models.TextField() created = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user} - {self.body[:30]}' class Meta: ordering = ('-created',) my serializers: class CommentSerializer(serializers.ModelSerializer): loadParent = serializers.SerializerMethodField("loadPrentData") def loadPrentData(self, comment): comments = Comment.objects.filter(parent=comment) comments_ser = CommentSerializer(comments, many=True).data return comments_ser class Meta: model = Comment fields = ['id', 'user', 'product', 'parent', 'body', 'created', 'loadParent'] class ProductSerializer(serializers.ModelSerializer): comments = serializers.SerializerMethodField("loadProductComments") def loadProductComments(self, _product): _comments = Comment.objects.filter(product=_product, parent__isnull=True) _comments_ser = CommentSerializer(_comments, many=True, read_only=True).data return _comments_ser class Meta: model = Product fields = ['id', 'category', 'name', 'slug', 'image_1', 'image_2', 'image_3', 'image_4', 'image_5', 'description', 'price', 'available', 'created', 'updated', 'comments'] lookup_field = 'slug' extra_kwargs = { 'url': {'lookup_field': 'slug'} } and this is my view for creating comment: @api_view(['POST']) def AddComent(request, parent_id=None): parent = request.data.get("parent_id") serializer = CommentSerializer(data=request.data) if serializer.is_valid(): if parent is not None: comment = Comment.objects.create(user=request.user, product=serializer.validated_data['product'], parent_id=serializer.validated_data['parent'], body=serializer.validated_data['body']) else: comment = Comment.objects.create(user=request.user, product=serializer.validated_data['product'], body=serializer.validated_data['body']) comments_ser = CommentSerializer(comment,many=False, read_only=True).data return Response(comments_ser, status=status.HTTP_200_OK) return Response(status=status.HTTP_400_BAD_REQUEST) when i go to the url i can not create comment this page shows and i can't post comment : this is … -
How to return list of dictionaries in the string representation format defined in Django Model?
I have a queryset, which returns the data I want after the application of a filter. This queryset gives me the data only given in __str__() method of the model. (However the type of the structure is <class 'django.db.models.query.QuerySet'> which I do not want.) Currently, I can only return a queryset, If I try using a serializer, it returns all kinds of metadata which I did not include in __str__() method of my class. .values() creates dictionaries that also includes metadata like "id" which I did not include in str() method of my class. I need a way to transform my QuerySet into a list of dictionaries (dictionaries which include model data given in __str__() method of the model class) -
Python Django : adding constrained field value into CBV view without all fields displayes
I am using a ClassBasedView, and asking Django to remove some fields in the auto-generated form (letting out : owner / owner_card_nb ) : class BristolCreateView(LoginRequiredMixin, CreateView): model = Bristol fields = [ "catalogue" , "recommanded_age" , "title" , "url" , "path_illustration" , "description" ] #letting out : owner / owner_card_nb I have to calculate the field owner_car_nb when the form is sent to the server. owner_card_nb= Bristol.objects.filter(owner=self.request.user) How can I push this data into the form which has been displayed in the html without the owner, neither the owner_car_nb value ? I tried several methods : Adding get_initial to the CBV : class BristolCreateView(LoginRequiredMixin, CreateView): def get_initial(self): return {'owner': self.request.user.id, 'owner_card_nb': 1} But the webpage still fails : IntegrityError at /bristol/create NOT NULL constraint failed: bristol_bristol.owner_id using form_valid : def form_valid(self, form): form.instance.created_by = self.request.user form.instance.owner_card_nb= Bristol.objects.filter(owner=self.request.user) return super(BristolCreateView, self).form_valid(form) But the webpage still fails : IntegrityError at /bristol/create NOT NULL constraint failed: bristol_bristol.owner_id What do I do wrong ? How can we set up values in a CBV form for non-displayed fields ? -
Check if element is in a model - Django templates
i'm trying to make a like button. And everything works fine except for the fact that i can't check (inside the template) if something is already liked by the user. In other words, i can't check for an existing row in the database. Im trying this for the template: If the user likes the post. That post shows a filled heart, otherwise it shows only a heart contour {% for post in posts %} {% if post in likelist %} <i class="fa fa-heart like" data-id="{{ post.id }}" id="like-{{ post.id }}" style="color:red;"></i> {% else %} <i class="fa fa-heart-o like" data-id="{{ post.id }}" id="like-{{ post.id }}" style="color:red;"> </i> {% endif %} {% endfor %} But the if statement is giving always False, even when the user actually likes the post. Here is the model: class Likelist(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE, related_name='liker') likes = models.ForeignKey('Posts', on_delete=models.CASCADE, related_name='likes') def __str__(self): return f"{self.user} likes {self.likes}" And i'm passing the context in views.py through render return render(request, "network/profile.html", { #[...]some other contexts "posts": Posts.objects.filter(user=user_id).order_by('-timestamp'), "likelist": Likelist.objects.filter(user=request.user), }) If i try to print it in a HTML tag ( {{likelist}} or {{posts}} ) the querysets appears so the context is passing fine. I don't know why the … -
Django static files don't load on production
I'm developping a Django project on windows but my production server is an ubuntu vps. All worked fine untill I add static files. It works fine on develoment (windows), but on production, I have [WARNING]: Not Found: /static each time I try to load a page. So the site works, there's just no css nor images on production. I've tryed the solutions given here : Django - Static file not found or here : Django: Not Found static/admin/css But none of them worked on my side. Here is my tree : my project In my settings.py, I have STATIC_URL = '/static/' I also have this kind of headers in my htmls to load static files: html Is there a different way of doing when adding static files on ubuntu rather than on windows ? -
How can i solve Django error Field 'id' expected a number but got ObjectId('5fb024de125430062daac949').?
I'm using django and mondogb for my project and keep getting this error then trying to register a new user. Here's my code: forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.forms import ValidationError class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = {"email", "username", "password1", "password2"} def clean_email(self): email = self.cleaned_data['email'] if not email.endswith('@student.upt.ro'): raise ValidationError('Email domain is not valid') return email def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.set_password(self.cleaned_data['password1']) user.is_active = False if commit: user.save() return user views.py def login_and_registration(request): register_form = NewUserForm() login_form = AuthenticationForm() if request.method == "POST": if 'login' in request.POST: login_form = AuthenticationForm(request=request, data=request.POST) print('login_form', login_form) if login_form.is_valid(): print('LOGIN HERE') username = login_form.cleaned_data.get('username') password1 = login_form.cleaned_data.get('password') user = authenticate(username=username, password1=password1) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}") return redirect('home') else: print(login_form.errors) messages.error(request, "Invalid credentials.") else: print(login_form.errors) messages.error(request, "Invalid credentials.") elif 'register' in request.POST register_form = NewUserForm(request.POST) if register_form.is_valid(): user = register_form.save() login(request, user) print(register_form.errors) messages.success(request, "Registration successful.") return redirect(reverse(home)) else: messages.error(request, "Unsuccessful registration. Invalid information.") context = {'login_form': login_form, 'register_form': register_form} return render(request, 'StartPage/reglog.html', context) After I complete the form and press submit I get the following … -
Django ORM postgresql type casting
I am trying to use Django's reverse generic relation for accessing and filtering related objects via Django's ORM. See below declared models: from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models class Status(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Package(models.Model): name = models.CharField(max_length=500) status = models.ForeignKey(Status, on_delete=models.PROTECT) hst_entries = GenericRelation("testapp.StatusHistory", related_query_name="package") def __str__(self): return self.name class StatusHistory(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT) object_id = models.TextField() object = GenericForeignKey("content_type", "object_id") status = models.ForeignKey(Status, on_delete=models.PROTECT) entry_added = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.content_type} - {self.object_id}: {self.status.name}" As you see there is generic relation between Package and StatusHistory models. For accessing related packages from StatusHistory model I tried: StatusHistory.objects.filter(package__name__startswith="pack") And result: ProgrammingError: operator does not exist: text = integer LINE 1: ...kage" ON ("myapp_statushistory"."object_id" = "myapp... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. I understand that PostgreSQL is complaining about type mismatch between object_id (of StatusHistory model) and id (of Package model) fields. This mismatch can be solved by PostgreSQL cast operator :: as below: ### WRONG join myapp_package on (myapp_statushistory.object_id = my_app_package.id) ### RIGHT join myapp_package on (myapp_statushistory.object_id = my_app_package.id::varchar) Is there possible way to make … -
Django static path of the image is not working
I am trying to load the static path of the image which is not working but the static path of the css files are working perfectly . I have tried every different way but still getting 404 this is i am trying to access the image which is inside the folder of ip in static folder <div class="col-auto"> <img src="{% static 'ip/best.png' %}"/> </div> I have load the static block above {% load static %} and the settings.py configuraion of static url STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static') ] -
Multiple images in Django + Postgres, by storing filepaths in ArrayField of CharField, or separate model for images, with foreignKey to product?
I'm creating an ecommerce site with Django and Postgres, where products will have multiple images. As I found out, using the ArrayField that Postgres provides, is not possible to store ImageField or FileField, it only works for integers, text etc. A very common approach to store multiple images per product, is to create another model called image, with a single ImageField, and a foreighKey to the product. But I am sceptical to use this, as I will need additional Get Requests to fetch the images. I am afraid these additional fetches will make my site slower. My calculation is, one Get Request to get all the products, which contain names, descriptions, and once I have their id's, I call another GET request to get the images, which reference to those foreign key id's in images. I had another idea, since the Postgres ArrayField, works fantastic using it as array of CharField, to just store the file paths to the images, to the media folder where I am storing them. I searched a lot all over stackoverflow and google, but I don't find anyone else mentioning this approach, although it makes sense to me. So, my question is: Is storing the … -
Django blog.models.Post.DoesNotExist: Post matching query does not exist
I am currently trying to add an Ajax to my like button to prevent refreshing, I am not an expert I am trying to learn from mistakes and small training exercises like this one but I am getting an error: blog.models.Post.DoesNotExist: Post matching query does not exist. and I don't know where the error is coming from Here is the views.py def like_post(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() context = { 'post_id': post_id, } if request.is_ajax: html = render_to_string('blog/like_section.html',context, request=request) return JsonResponse({'form': html}) return redirect('blog:post-detail', slug=post_obj.slug) Here is the template like-section.html <form action="{% url 'blog:like-post' %}" method="POST" class="like-form" id="{{post.id}}"> {% csrf_token %} <input type="hidden" name="post_id" value='{{post.id}}'> {% if user not in post.liked.all %} <button id="like" class="bwhite sm-button" style="color: grey; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none;"> <i class="far fa-thumbs-up" type="submit"></i> </button> {% else %} <button id="like" class="bwhite sm-button" style="color: blue;background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none;" > <i class="far fa-thumbs-up" type="submit"></i> </button> {% endif %} <div class="like-count{{post.id}}">{{ post.num_likes }} Likes</div> </form> … -
JavaScript - Display a bar graph with dictionary in ECharts
is there a way to display a bar graph with given source dataset in one dictionary? I'm using ECharts and it's hard to understand their documentation :( My data: {"TCP": 1003, "UDP": 232, "ICMP": 4, "IP": 0} And my option is right there: var option = { dataset: { source : myChart }, title: { text: 'Protocol' }, xAxis: { data: ['TCP', 'UDP', 'ICMP', 'IP'] }, yAxis: { data: [0, 100, 300, 500, 700, 900, 1100] }, series: [{ name: 'Protocol', type: 'bar', }] }; Thanks a lot for any advice ! @EDIT So the problem is in my JavaScript code... I can't access values, what's the problem ? const proto = JSON.parse(document.getElementById('proto').textContent); console.log(proto); console.log(proto['IP']); I forgot to mention proto element is from django variable {{ proto|json_script:"proto" }} @EDIT2 Only working is to put a variable with safe tag, is it okay? Or may it be vulnerable to xss? var proto = JSON.parse('{{ proto|safe }}'); -
cant create filters in django project
i want add filter in the project but this error comes to me in CMD AttributeError: module 'rest_framework.filters' has no attribute 'DjangoFilterBackend' the Project Name = frame the ProjectApp Name = framework Views.py from typing import Tuple from django.shortcuts import render from .serializer import TaskSerializers from rest_framework import viewsets from .models import Task from rest_framework import filters import django_filters # Create your views here. class myviewset(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializers filter_backends =(filters.DjangoFilterBackend,filters.OrederingFilter) filter_fields=('completed',) ordering = ('-date_created') Installed app: INSTALLED_APPS = [ 'framework', 'rest_framework', 'django_filters', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
Can not change parent abstract model name in Django
In part of my Django server I had this models: class Review(models.Model): time = models.DateTimeField(auto_now_add=True) ip = models.GenericIPAddressField() class Meta: abstract: True class Click(Review): view_delay = models.DurationField() ad = models.ForeignKey( to=Ad, related_name='clicks', on_delete=CASCADE ) class View(Review): ad = models.ForeignKey( to=Ad, related_name='views', on_delete=CASCADE ) But now I want to change the abstract class Review to BaseAdEvent due to code readability. When I want to Make new migrations I get following questions and I answer all of them with y(yes): Did you rename the advertising.Review model to BaseAdEvent? [y/N] y Did you rename click.review_ptr to click.baseadevent_ptr (a OneToOneField)? [y/N] y Did you rename view.review_ptr to view.baseadevent_ptr (a OneToOneField)? [y/N] y Migrations for 'advertising': advertising/migrations/0009_auto_20201114_1828.py - Rename model Review to BaseAdEvent - Rename field review_ptr on click to baseadevent_ptr - Rename field review_ptr on view to baseadevent_ptr but when I want to migrate the migrations I get following error: django.core.exceptions.FieldError: Auto-generated field 'review_ptr' in class 'View' for parent_link to base class 'Review' clashes with declared field of the same name. Is there anyway I could rename my parent model other than deleting the previous migrations and drop all tables? -
PostgreSQL: How to set up individual roles on PythonAnywhere (for Django)?
I am running my Django app on PythonAnywhere. The postgreSQL database was created with something like createdb -h xxx.postgres.eu.pythonanywhere-services.com -p 10077 -U super postgres It looks like this: postgres=# \du List of roles Role name | Attributes | Member of -----------------------+------------------------------------------------------------+----------- postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {} pythonanywhere_helper | Superuser | {} super | Superuser, No inheritance +| {} | 10 connections | PythonAnywhere says on the Postgres settings page: For security, it may be best to set up individual roles with lower privileges for each of your web applications. Sounds like a good idea, but how can I do that? I made some experiments (with postgreSQL via Docker, inspired by that article) and I found out, that I can do this: postgres=# CREATE USER django; CREATE ROLE postgres=# \du List of roles Role name | Attributes | Member of -----------+------------------------------------------------------------+----------- django | | {} postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {} I guess, there are some attributes missing. How can I configure this properly for my Django app? Is it even possible to change that in hindsight? -
Which one I should start design Ionic UI firstly or Django as a backend
As a title describe, Which one I should start design Ionic UI firstly or Django as a backend -
How to execute annotate in Django model with foreign keys?
Django novice question here :) I have the following model Domain: domain_name domain_description These domains can be scanned multiple times The other model is ScanHistory: last_scan_date scan_status domain_name = models.ForeignKey(Domain, on_delete=models.CASCADE) When scanned, these domains produce several subdomains ScannedHost: subdomain cname scan_history = models.ForeignKey(ScanHistory, on_delete=models.CASCADE) These subdomains will have vulnerabilities associated with it VulnerabilityScan: vulnerability_of = models.ForeignKey(ScanHistory, on_delete=models.CASCADE) severity vulnerability_name How do I find out the domain which are top 3 most vulnerable Domain? A most vulnerable Domain is any domain that has the highest count of Unique Vulnerability despite n numbers of time it is scanned. I stumbled upon Django annotate, but I don't seem to solve this. -
DRF Get likes and dislikes grouped by day
I have a models named Post and Like. How can i get json with ount of likes and dislikes grouped by date (date field in Like model)? Here is my models.py class Post(models.Model): """Post model""" author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255) body = models.TextField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Like(models.Model): """Like model""" LIKE = ( ('like', 'like'), ('dislike', 'dislike') ) user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='likes') like = models.CharField(max_length=255, choices=LIKE) date = models.DateField(auto_now=True) Here is my serializers.py: class AnaliticsSerializer(serializers.ModelSerializer): """Like analitic""" class Meta: model = Like fields = '__all__' Here is my vievs.py: class AnaliticView(ListAPIView): queryset = Like.objects.all() serializer_class = AnaliticsSerializer filter_backends = [DjangoFilterBackend] filter_fields = ['date'] result what i want [ { "date": "2020-11-14", "total_likes": 25, "total_dislikes": 17 }, { "date": "2020-11-15", "total_likes": 38, "total_dislikes": 8 }, { "date": "2020-11-18", "total_likes": 11, "total_dislikes": 0 } -
React Plus Django: Can't update the django backend while creating a new Todo item
I created a Django + React Todo App which is working as expected on the frontend but the functionality of updating the backend when a new item/todo is not know to me well. Also, i was able to manage the delete functionality but not the rest (got stuck with handleItem function). Need help to make the add items functionality work :( Frontend Code below, Backend code is here "https://bitbucket.org/Yash-Marmat/backend/src/master/" import React, { Component } from "react"; import axios from "axios"; import "bootstrap/dist/css/bootstrap.min.css"; import "font-awesome/css/font-awesome.min.css"; //import "@fortawesome/react-fontawesome"; import "./App.css"; class App extends Component { constructor() { super(); this.state = { newID: 11, edit: false, cloneID: 0, cloneTitle: "", todoData: [], // will come from django backend }; this.handleUserInput = this.handleUserInput.bind(this); this.handleAddItem = this.handleAddItem.bind(this); this.handleEdits = this.handleEdits.bind(this); this.renderEdits = this.renderEdits.bind(this); this.handleUpdates = this.handleUpdates.bind(this); this.onRemove = this.onRemove.bind(this); this.handleStrike = this.handleStrike.bind(this); this.refreshList = this.refreshList.bind(this); this.getTodos = this.getTodos.bind(this); this.increment = this.increment.bind(this); } // increment id increment() { this.setState((prevState) => ({ newID: prevState.newID + 1, })); } // Todo Creation Function (part 1) handleUserInput(event) { this.setState({ userInput: event.target.value, }); } // PROBLEM BELOW // Todo Creation Function (part 2) handleAddItem(id) { const someID = this.state.newID; //console.log(someID) this.setState((prevState) => ({ todoData: [ ...prevState.todoData, { id: someID, task: … -
Count of values between a certain range for columns of dataframe pandas and render from views.py as dictionary to Django html file
I am new to Python and Django. I need to calculate count values over a range, for dataframe columns and render it as a dictionary object so that I can view it as Django html. I don't know how to do so. I tried to see if I can use histrogram but could not find ways to get output in below format. Similarly I can see that Pandas has Cut function but it looks like it adds against an column. Below are columns from dataframe. In all I have 1190 records in each columns, these are basically percentages of deviations observed. Symbol Date Col1 Col2 XXX 16-02-2020 -0.67 -3.69 XXX 17-02-2020 1.18 4.47 XXX 18-02-2020 -3.02 -0.21 XXX 19-02-2020 -2.15 -0.64 XXX 20-02-2020 4.32 0.40 XXX 21-02-2020 3.89 4.73 . . . What I want to see is output as below. This will be one at a time. i.e Show output for Col1 if selected from list or col2 or col3 so on and so forth. Range Count Total Records More than 3% 7 1190 Between 2% and 3% 9 1190 Between 1% and 2% 97 1190 Between 0% and 1% 433 1190 Between 0% and -1% 528 1190 Between …