Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The map of google maps in a web (django) doesn't show the results in the first sending of data
I am using django and Maps Javascript API to create a website. User gives me an origen address and destination address (both with Places Autocomplete -https://developers.google.com/maps/documentation/javascript/places-autocomplete). I am trying to mark on the map both locations. Django's form: class userRequest(forms.Form): def __init__(self, *args, **kwargs): super(userRequest,self).__init__(*args, **kwargs) lat_Origin = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lat_Origin"}),required=False,initial=181) lon_Origin = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lon_Origin"}),required=False,initial=181) lat_Dest = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lat_Dest"}),required=False,initial=181) lon_Dest = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lon_Dest"}),required=False,initial=181) lat_currentLocat= forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lat_currentLocat"}),required=False,initial=181) lon_currentLocat= forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lon_currentLocat"}),required=False,initial=181) current_address=forms.CharField(max_length=200,widget=forms.HiddenInput(attrs={"class":"data","id":"current_address"}),initial='.') origin_address=forms.CharField(max_length=200,widget=forms.TextInput(attrs={"class":"data","id":"origin_address"})) destination_address=forms.CharField(max_length=200,widget=forms.TextInput(attrs={"class":"data","id":"destination_address"})) date=forms.DateField(widget=DateInput(attrs={"class":"data"})) Functions I am using in this process in JS: function init_autocomplete_map() { autocomplete_id("origin_address"); autocomplete_id("destination_address"); initMap(); } function initMap(){ list_address=['origin_address','destination_address'] save_lat_lon(list_address[0],'lat_Origin','lon_Origin'); save_lat_lon(list_address[1],'lat_Dest','lon_Dest'); latO=parseFloat(document.getElementById("lat_Origin").value); lonO=parseFloat(document.getElementById("lon_Origin").value); latD=parseFloat(document.getElementById("lat_Dest").value); lonD=parseFloat(document.getElementById("lon_Dest").value); let list_location=[]; let point_origin={lat:latO, lng:lonO}; let origin_exists=!(latO == 181 || lonO==181 || latD==181 || lonO==181) var map = new google.maps.Map(document.getElementById("google_map"), { scaleControl: true, center: point_origin, zoom: 6, }); if (origin_exists){ point_origin={lat:latO,lng:lonO} list_location.push(point_origin); list_location.push({lat:latD,lng:lonD}); list_location.forEach((element,index)=>{ const infowindow = new google.maps.InfoWindow(); contentString= '<div id="content-map">' + '<p>'+document.getElementById(list_address[index]).value+'</p>' + "</div>"; infowindow.setContent(contentString); const marker = new google.maps.Marker({ map, position: element }); marker.addListener("click", () => { infowindow.open(map, marker); }); }); }else{ map.setCenter({ //Madrid Coordinates lat : 40.4165, lng : -3.70256 }); } //get_currentLocation(map); } function save_lat_lon(id_address,id_latitude,id_longitude){ var address = document.getElementById(id_address).value if (id_address=='origin_address' && address==document.getElementById('current_address').value){ document.getElementById(id_latitude).value = document.getElementById('lat_currentLocat').value; document.getElementById(id_longitude).value= document.getElementById('lon_currentLocat').value; }else{ var geocoder = new google.maps.Geocoder(); geocoder.geocode( { 'address': address}, function(results, status) { document.write(status) if (status … -
Multiple field inheritance from Group excludes database fields in Django
I'm extending Django's Group class. However, after extending it a second time, the for referencing required group_ptr_id column is not created in the database table. See the following example: class MyGroup(Group): pass class AnotherGroup(MyGroup): pass Applying the migrations fails with the exception django.db.utils.OperationalError: near ")": syntax error. Printing out the query reveals that the group_ptr_id-column is not being created/missing, compared with the query for the table for the MyGroup-model: CREATE TABLE "users_mygroup" ("group_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "auth_group" ("id") DEFERRABLE INITIALLY DEFERRED) CREATE TABLE "users_anothergroup" () Why does this happen and how do I get Django creating the group_ptr_id column for the users_anothergroup-table, too? -
django reverse lookup using strings
I want to know is it possible to do reverse lookup between two tables without using foreign key in form of id. Means instead of matching between the two tables using a field id, can i make it using field values containing strings. example- if in both the tables i have column with different names but containing almost similar values in form of string. Is it then possible to reverse lookup other fields on behalf of these common string fields? table 1: SKILLS PROFILE python, R ml engineer python, java se table 2: NAME CandidateSKILLS Ajay Kumar python, java Suman python In this case is it possible to do reverse lookup using the skills and candidate skills columns if they contain almost similar string inside it. -
Same-value field in two different but related models
class Currency(models.Model): name = models.CharField(max_length=200) shortname = models.CharField(max_length=3) symbol = models.CharField(max_length=2) class Client(models.Model): name = models.CharField(max_length=200) base_rate = models.DecimalField(decimal_places=2, max_digits=15) country = models.CharField(max_length=200) currency = models.ForeignKey(Currency, on_delete=models.PROTECT) class Job(models.Model): title = models.CharField(max_length=200) start_date = models.DateField() rate = models.DecimalField(decimal_places=2, max_digits=15) client = models.ForeignKey(Client, on_delete=models.PROTECT) currency = models.ForeignKey(Currency, on_delete=models.PROTECT) I have above classes. Job and Client classes are related via the client field in the Job class. Both classes have a field called currency, which is related to the Currency class. In the current setup, obviously a Client object and a Job object that belongs to a Client can have different currency values. I want to tie these toghether so that the Job object always has the same currency value as the related Client object. How do I do this? -
Virtual Environment in Django
When we create virtual environment is it good practice to keep, our virtual environment folder and our project folder inside same root folder? If i am not wrong then every project have its own viretual environment so how can we remmember which project use which virtual environment if we have created too many virtual environment for many projects? -
django admin - custom action template
Im trying to add a custom action to django app, where i can redirect to a html (pdf) page i created. currently the html page only shows 1 result, What im trying to do is to show as many as objects i selcet from the action bar in django admin. here is my code def print_pdf(modelAdmin, request, queryset, **kwargs): from django.template.loader import get_template from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 from calculator.models import Transaction from xhtml2pdf import pisa chp = [] for f in queryset: chp.append(f.chp_reference) for q in range(len(queryset)): transaction = get_object_or_404(Transaction, chp_reference=chp[1]) #im not sure what to do here template_path = 'report-pdf.html' context = {"transactions":transactions} response = HttpResponse(content_type='Application/pdf') response['Content-Disposition'] = 'filename="report.pdf' template = get_template(template_path) html = template.render(context) pisa_status = pisa.CreatePDF(html, dest=response) if pisa_status.err: return HttpResponse('we had some errors' + html ) return response here is my code. I know its messed up, but i been trying to figure out to do this but im lost. help would be appreciated -
Problem with multiple file upload with formdata in django
i have an form, to take the inputs and for the multiple uploads trying with the Formdata {% load static %} {% block content %} <!doctype html> <html lang="en"> <head> <title>{{type}} | SE Learning</title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="robots" content="noindex"> <meta name="googlebot" content="noindex"> <meta content="width=device-width, initial-scale=1.0" name="viewport" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <!-- Fonts and icons --> <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Roboto+Slab:400,700|Material+Icons" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <!-- Material Kit CSS --> <link rel="stylesheet" href="{% static 'assets/css/material-dashboard.css' %} "/> <link rel="stylesheet" href="{% static 'assets/css/main.css' %} "/> <link rel="stylesheet" href="{% static 'assets/css/vendor.css' %} "/> <link rel="stylesheet" href="{% static 'assets/css/jquery.dataTables.min.css' %} "/> <link rel="stylesheet" href="{% static 'assets/fonts/font-awesome.min.css' %} "/> </head> <body> <div class="wrapper "> <!-- Tip 1: You can change the color of the sidebar using: data-color="purple | azure | green | orange | danger" Tip 2: you can also add an image using data-image tag --> <section ng-include="'views/partials/header.html'" id="header" class="ng-scope"> <header class="clearfix ng-scope"> <!-- Branding --> <div class="row headrow"> <div class="branding col-md-3"> <a class="brand" ui-sref="app.dashboard" href="#"> </a> <a href="javascript:;" class="offcanvas-toggle visible-xs-inline" offcanvas-sidebar=""> <i class="fa fa-bars"></i></a> </div> <!-- Branding end --> <div class="col-md-9"> <a class="nav-log" href="/logout">Logout<span class="sr-only">(current)</span></a> </div> </div> </header></section> <div class="sidebar" data-color="purple" data-background-color="white"> <div class="sidebar-wrapper"> <ul … -
Django many to many field not being saved correctly in database
When I try to save many to many field in django. It only save one item , even when I have selected 2 items from the template. My views.py looks like this @login_required() def create_class(request): tea_user = request.user.username validate = teacher_validation(tea_user) if validate: if request.method == 'POST': Link = request.POST.get('link') Subject = request.POST.get('Subject') Class = request.POST.getlist('Class') print(Class) teacher_user = Teacher.objects.get(User=request.user) teacher = Teacher.objects.get(id=teacher_user.id) created_class = Online_Class.objects.create( Link=Link, Subject=Subject,Created_by =teacher ) for classes in Class: created_class.Class.set([classes]) return redirect('home') return render(request, 'online_class/Teacher/class-create.html') else: messages.warning(request, 'Sorry You Dont have Permission to access this page') return redirect('logout') My models.py looks like this class Online_Class(models.Model): Created_by = models.ForeignKey(Teacher, on_delete=models.DO_NOTHING) Class = models.ManyToManyField(Classes) Subject = models.CharField(max_length=100) Link = models.CharField(max_length=200) Joined_by = models.ManyToManyField(Student, blank=True) created_at = models.DateTimeField(auto_now_add=True) choice = (('Yes','Yes'),('No', 'No')) Class_Ended = models.CharField(choices=choice, default='No', max_length=10) My template looks like this {% extends 'dashboard/teacher/base.html' %} {% block title %} Create Class {% endblock title %} {% block class %} active {% endblock class %} {% block body %} <div class="pc-container"> <div class="pcoded-content"> <div class="row"> <form method="POST"> {% csrf_token %} <div class="form-group"> <label >Zoom Link</label> <input type="url" class="form-control" name="link" placeholder="URL" required=""> </div> <div class="form-group"> <label>Subject</label> <select class="form-control" name="Subject" required=""> {% for subject in teacher.Subject.all %} <option>{{subject}}</option> {% endfor … -
How to Model Authenticated User Metadata in Django
I'm using Django (Django Rest Framework) and I'd like to design an API that outputs songs as JSON when the user is not authenticated and additional (meta data) fields when authenticated. Non authenticated: GET: /songs/{song_id} ... class Song(models.Model): created_at = models.DateTimeField(auto_now_add=True) composed_year = models.PositiveIntegerField( blank=True, null=True) title = models.CharField(max_length=50) lyrics = models.TextField(max_length=10000) artist = models.ForeignKey(Artist, on_delete=models.CASCADE) genre = models.ForeignKey(Genre, on_delete=models.CASCADE) key = models.CharField(blank=True, null=True, max_length=2) Authenticated: GET: /songs/{song_id}/{user_id}/ This endpoint would return all the original song data PLUS an additional key field for the authenticated user and an arbitrary number of fields (e.g. notes). How would I model this? I would need a table mapping user ID to song ID plus additional fields. Is this what a through table is for? This doesn't seem like a many to many...rather one-to-one: one song has one user preference (per user), and one user preference has only one song... -
Django Query ManyToMany
I want to do a query to select top 5 users with more likes in their posts. My models are: class Post(ModelBase): title = models.CharField('Title', max_length=255) description = models.TextField() finished = models.BooleanField(default=False) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post_author') likes = models.ManyToManyField(User, through='PostLike',) tags = models.ManyToManyField(Tag, related_name='tags') def total_likes(self): return self.likes.count() class PostLike(ModelBase): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) I have this, but it does not work for me correctly. Instead of telling the Likes of the users' post, count the Likes that each user has given. users = User.objects.annotate(likes_count=Count('postlike', Q(post__is_active=True)))\ .order_by('likes_count').reverse()[0:5] -
Show only link to file which exists Django Python
I have a four FileFields in my models.py like 2 below: file_1 = models.FileField(blank=True, upload_to='PN_datoteke/%Y/%m/%d/', verbose_name="Datoteka 1") file_2 = models.FileField(blank=True, upload_to='PN_datoteke/%Y/%m/%d/', verbose_name="Datoteka 2") Each time different number of files is uploaded and some are left empty. I use following in my .html page to offer a download option of the file which is uploaded: <p class="article-content mb-1"><strong>Datoteka 1: </strong><a href="{{post.file_1.url}}" download>Preuzmi</a></p> <p class="article-content mb-1"><strong>Datoteka 2: </strong><a href="{{post.file_2.url}}" download>Preuzmi</a></p> Problem is, I have 4 upload options and if some are not used I get following error: The 'file_2' attribute has no file associated with it How can I suppress the empty fields (.destroy, .remove) before they are generated on the page, if file doesn't exist? I guess I must use a javascript? How to check and not display a if a file doesn't exist? -
Django -JSON not serializable type-error while integrating paypal
Whenever I try to pay using paypal on my website it throws an error Internal Server Error: /paypal/create/18/ Traceback (most recent call last): File "C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\ukfle\Documents\pro\a\views.py", line 69, in create response = client.execute(create_order) File "C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\site-packages\paypalhttp\http_client.py", line 52, in execute data = self.encoder.serialize_request(reqCpy) File "C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\site-packages\paypalhttp\encoder.py", line 15, in serialize_request return enc.encode(httprequest) File "C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\site-packages\paypalhttp\serializers\json_serializer.py", line 7, in encode return json.dumps(request.body) File "C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type Decimal is not JSON serializable here are my views: def pay(request, pk): client_id = settings.PAYPAL_CLIENT_ID course = get_object_or_404(t_data,pk=pk) context={'course':course, 'client_id':client_id } return render(request, 'pay.html',context) def create(request,id): if request.method =="POST": environment = SandboxEnvironment(client_id=settings.PAYPAL_CLIENT_ID, client_secret=settings.PAYPAL_SECRET_ID) client = PayPalHttpClient(environment) course = t_data.objects.get(pk=id) create_order = OrdersCreateRequest() create_order.request_body ( { "intent": "CAPTURE", "purchase_units": [ { "amount": { "currency_code": "USD", "value": course.file_price, "breakdown": { "item_total": { "currency_code": "USD", "value": course.file_price } }, }, } ] } ) response = client.execute(create_order) data = response.result.__dict__['_dict'] return JsonResponse(data) else: … -
django.core.exceptions.FieldError: Unknown field(s) (phone) specified for User
Iam adding a new data storage in my models.py of django but this is not working I have make migrations and everything. models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(max_length= 1000) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) phone = models.CharField(max_length=10, default="Integer") def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) And this is my forms.py: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email','password1','password2','phone'] class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username','email','phone'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile field = ['image'] exclude = ['fields'] Please help me find a solution for this this is really stopping me to build my own website. Please tell if I should add any other details to it I will definetly do that. -
Troubles with saving UserCreationForm in Django
I have my registration view, that uses UserCreationForm. Here it is: def registration(request): if request.method == 'POST': form = UserCreationForm() if form.is_valid: user = form.save() login(request, user) return redirect('home') else: if request.user.is_authenticated: logout(request) form = UserCreationForm() context = {'form':form,} return render(request, "register.html",context) But somehow when I try to create new user, I get AttributeError, that says " 'UserCreationForm' object has no attribute 'cleaned_data'" even though I don't have any calls of cleaned_data whatsoever. I tried to create my custom registration form which used cleaned_data, but I threw this away and wiped my custom form from the project completely. Why could this happen? P.S. The line that causes problems according to my Django debug return is user = form.save() -
Django POST returns empty - DRF + recaptcha
I'm trying to make a POST request to Django and it arrives empty to the view. views.py from django.http import HttpResponse from rest_framework import generics, views class TESTViewSet(views.APIView): def post(self, request): st = f'test: {request.POST} - {request.data} ' s_obj = serializers.RecaptchaSerializer( data=request.data, context={"request": request} ) return HttpResponse(st) The purpose is to test recaptcha with django rest framework, but I haven't even got there yet. The issue is the request always arriving at the view empty of any info. The page renders renders "test: - " The template rendered in the page: <div class=""> test <form method="post" action="/api/test_recaptcha/"> {% csrf_token %} <label for="ntest">Select:</label> <select name="ntest" id="ntest"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <label for="stest">Text:</label><br> <input type="text" id="stest" name="stest" value=""><br> <script src='https://www.google.com/recaptcha/api.js'></script> <div class="g-recaptcha" data-sitekey="{MY CAPTCHA PUBLIC KEY}"></div> <button type="submit" class="btn btn-primary">Post</button> </form> </div> It renders what is in the view, so the route is ok. I inspected the browser request, and all the fields of the post request are filled, including the g-captcha. However when it arrives at the view it's empty. What am I missing? -
Django Query to Combine Multiple ArrayFields to one text string
I have an object model where Documents are long text files that can have Attachments and both sets of objects can also have spreadsheet-like Tables. Each table has a rectangular array with text. I want users to be able to search for a keyword across the table contents, but the results will be displayed by the main document (so instead of seeing each table that matches, you'll just see the document that has the most tables that match your query). Below you can see a test query I'm trying to run that in an ideal world would convert all of the table contents (across all attachments) to one long string, that I can then pass to a SearchHighlight to make the headline. For some reason, the test query returns the tables as different objects, rather than concatenated to one long string. I'm using a custom function that mimics the Postgres 13 StringAgg as I'm using Postgres 10. Thanks in advance for your help, let me know if I need to provide more information to replicate this. my models.py: class Document(AbstractDocument): tables = GenericRelation(Table) class Attachment(AbstractDocument): tables_new = GenericRelation(Table) main_document = ForeignKey(Document, on_delete=CASCADE, related_name="attachments") class Table(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id … -
What does *args and **kwargs do in Django?
I was following a Django tutorial when I came upon the following code: def index(*args, **kwargs): return HttpResponse("<h1>Hello World</h1>") The instructor did not really explain what *args and **kwargs were, and it confused me. Can someone please explain what this does in the simplest terms? I'm pretty good with Python but I've never heard of this before. -
How to get Object value Django
I want get member object value 1.models.py from django.db import models class Member(models.Model): pID = models.CharField(max_length=6, primary_key=True, null=False) pChName = models.CharField(max_length=20,null=False) pBirth = models.CharField(max_length=10,null=False) pMobile = models.CharField(max_length=10,null=False) pLineID = models.CharField(max_length=20,null=True) pTeam = models.CharField(max_length=20,null=True) pAccount = models.CharField(max_length=20,null=False) pPassword = models.CharField(max_length=20,null=False) class Meta: db_table = 'members' fields = '__all__' 2.views.py def register(request): try: if request.method == "POST": member = Member(request.body.decode('utf-8')) print(member) except Exception as e: print(e) return redirect('/') return render(request, 'register.html') 3.Log Member object (csrfmiddlewaretoken=xLnhz9mX3aYVCRgakvcbPokrnbNjhiYG6NW9Ocf0GkfzfGZWBUdA2Bn6rNTOzKBP&pChName=1&pBitrh=2&pMobile=3&pLineID=4&pAccount=5&pPassword=6&pTeam=A) I want get member object value -
Use django permission system without Django Users
I want to build an application similar to jitsi. So people can join rooms (django channels) without registration or log in. Although this should be optionally supported. In a room I need "Users". These have a name and permissions. For instance the first joined should be in an "admin group" and be allowed to kick others users. So my idea was to create a User for each "websocket connection" and assoziate that with the room. I therefore made my own Django User. class RoomUser(AbstractBaseUser, PermissionsMixin): """ A custom user model for rooms to allow using built in permission handling """ channelName = models.CharField( max_length=255, help_text="Reply channel for connection that is present" ) userName = models.CharField( max_length=255, help_text="Free choosen user name" ) USERNAME_FIELD = 'channelName' REQUIRED_FIELDS = ['userName'] objects = RoomUserManager() def __str__(self): return self.channelName The thing is that I get these error messages auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'UserManage.groups'. Basically, this is also what the docs say, I should set AUTH_USER_MODEL, so it replaced the django user with my custom user. But this is not what I want. I don't want to replace the default user model (I might wanna add real login to … -
Views Count wont increase by 1
Model: @python_2_unicode_compatible class Post(models.Model): description = models.CharField(max_length=255, blank=True) pic = models.ImageField(upload_to='path/to/img') date_posted = models.DateTimeField(default=timezone.now) user_name = models.ForeignKey(User, on_delete=models.CASCADE) tags = models.CharField(max_length=100, blank=True) hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') def __str__(self): return self.description def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) return super(Post, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) views.py: class UserPostListView(LoginRequiredMixin, ListView): model = Post template_name = 'feed/user_posts.html' context_object_name = 'posts' paginate_by = 10 def get_context_data(self, **kwargs): context = super(UserPostListView, self).get_context_data(**kwargs) user = get_object_or_404(User, username=self.kwargs.get('username')) liked = [i for i in Post.objects.filter(user_name=user) if Like.objects.filter(user = self.request.user, post=i)] context['liked_post'] = liked context.update({ 'popular_posts': Post.objects.order_by('-hit_count_generic__hits')[:3], }) return context def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.all().order_by('-date_posted') urls.py: path('post/<int:pk>/', views.post_detail, name='post-detail'), In my django template view: <p class="text-muted">Views: {% get_hit_count for post %}</p> I am getting Views:0 Where is the problem? -
Couldn't integrate a CSS file into my project
I would like to connect my layout.html file with a CSS file so that every other page extending my layout.html has access to this CSS file. That is the code: layout.html <!DOCTYPE html> <html lang="de"> <head> <title>Aufgabenzettel</title> <link rel="stylesheet" href="/aufgabenzettel/static/css/main.css"> </head> <body> {% block body %} {% endblock %} </body> </html> index.html {% extends "aufgabenzettel/layout.html" %} {% block body %} <h1>Meine Aufgaben</h1> {% endblock %} main.css h1 { color: aqua; } The href in layout.html is probably correct bacause I can be redirected to it in VS via ctrl + click. However, the h1 in index.html still appears in black instead of aqua... What am I doing wrong? I appreciate every kind of help! -
How to debug database connections pool in django
I'm using Django 3.1.5 with multi-threading and the default database is a PostgreSQL database and the problem is that for some reason when I keep the Django server running for minutes, the database server starts showing errors that no remaining connections available. In order to debug this problem and find out what's creating new database connections without closing old ones, I need a way to list all database connections, active and IDLE along with any possible details. So, how do I access such information in runtime? -
Django filter objects id and search for the full name in User model
I have a problem of solving this for the whole day and can't get it right. Please someone help me... book_obj = Book.objects.filter(status_sold=True).order_by('-date_sold') result will be something like this: id = 2 title = 'bla bla bla bla...' author = 3 ---> id from the User model (not a foreign key) status_sold = True date_sold = '2021-05-10' I want to view that data in the template, but the author I want to display the name instead of number 3 as an id of the author. How to solve this ? author_name = User.objects.get(id= ???????? ) so I can use {{ author_name.get_full_name }} later in the template Thx in advanced.... -
How to use model field in it's serializer
I would like to have my own error messages, which I've implemented in serializer like this: class TransactionsValuesSerializer(serializers.ModelSerializer): class Meta: model = Translations fields = ('id', 'value') extra_kwargs = {"value": {"error_messages": {"blank": f"Error"}}} It's model class Translations(models.Model): class Meta: db_table = 'merchants__translations' value = models.TextField() key = models.ForeignKey( TranslationsKeys, on_delete=models.CASCADE, related_name='translations' ) translation_language = models.ForeignKey( TranslationLanguages, on_delete=models.CASCADE, related_name='translations' ) Now, if user do not enter some of the fields for translations, it will show error message 'Error'. Image Is there a way to output error message like 'Error in {key}'? -
Filter database models based on input in form
I have the following models and a form in my Django app. These are the relevant snippets of my code. models.py C = 'C' I = 'I' A = 'A' CIA_CATEGORIES = ( (C, 'Confidentiality'), (I, 'Integrity'), (A, 'Availability') ) class security_incident(models.Model): asset = models.CharField(max_length=200) actor = models.CharField(max_length=200) action = models.CharField(max_length=200, primary_key=True) cia = models.CharField(max_length=9, choices=CIA_CATEGORIES, default=C) def __str__(self): return self.asset class defense_mechanism(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class attack(models.Model): attack_description = models.CharField(max_length=100) defense_mechanism = models.ManyToManyField(defense_mechanism) action = models.ForeignKey(security_incident, on_delete=models.CASCADE) def __str__(self): return self.attack_description form.py #Form to enter goal of attack-defense-tree class GoalForm(forms.Form): goal = forms.CharField(label='Goal of attack-defense-tree', max_length=100) categories = forms.MultipleChoiceField(choices='CIA_CATEGORIES', widget=CheckboxInput) Based on the input of the form (Goal and chosen categories) the database models should be filtered. If GOAL input(assuming goal form input = Database) matches an asset in security_incident model (security incident asset =Database) and category(or categories) have been chosen, the filter view should list all security incidents with related attacks and defense mechanisms for the goal/asset. The output should be something like this: generate.html <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="search btn btn-default">Search</button> </form> <div> {% for security_incident in filter.qs %} <h2>Form input: Goal</h2> <ul> <li>cia_category1</li> <ul> <li> {{ …