Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how do i get the repeating event details on all following dates in python django
models: from django.db import models class datecrt(models.Model): name=models.CharField(max_length=255) stdate=models.DateField() sttime=models.TimeField() endate=models.DateField() forms: import datetime from xml.dom.minidom import Attr from django import forms from .models import datecrt class dateform(forms.ModelForm): class Meta: model=datecrt fields='__all__' widgets={ 'stdate':forms.DateInput( attrs={'type':'date','class':'form-control'}, format='%D-%m-%yy', ), 'sttime':forms.TimeInput( attrs={'type':'time','class':'form-control'}, format='%H:%M', ), 'endate':forms.DateInput( attrs={'type':'date','class':'form-control'}, format='%D-%m-%yy', ) } def __init__(self,*args,**kwargs): super(dateform,self).__init__(*args,**kwargs) self.fields['stdate'].imput_format=('%D-%m-%yy',) self.fields['sttime'].imput_format=('%H:%M',) self.fields['endate'].imput_format=('%D-%m-%yy',) Views: from unicodedata import name from django.shortcuts import redirect, render from .forms import dateform from .models import datecrt def datecr(request): if request.method=='GET': form=dateform() return render(request, 'date.html', {'form':form}) else: form=dateform(request.POST) if form.is_valid(): form.save() return redirect('/dateview') def dateview(request): context={'dateview':datecrt.objects.all()} return render(request, 'dateview.html',context) When I create this booking on 1st of feb and end date will select as 5th of feb, my challenge is, created booking should display name, date, and time till 5th of feb automatically in dateview template, without me creating same for 2nd of feb, 3rd of feb till 5th of feb manually. -
Django-PolymorphicModel- How to create child class without fieldname
I didnot use PolymorphicModel befor. Its new to me. I want to both parent and child class. I want to access all the child class from parent class. So i am using this one.I want to create one child class without fields. because, Foreignkey it will create own if i try also it will through error. how can I achieve this?? models.py class EmploymentStatus(PolymorphicModel): status = models.CharField(max_length=255) employment = models.ForeignKey(Employment, on_delete=models.RESTRICT) from_date = models.DateField(null=False) status_from_date = models.DateTimeField(null=False, default=datetime.utcnow) status_turu_date = models.DateField() def __str__(self): return self.id class PendingEmploymentStatus(EmploymentStatus): -
Django Display count of database entries related via foreign key
I have two models, ProjectNotes and ProjectNoteComments. ProjectNoteComments are related to ProjectNotes via a foreign key. I want to display the number of comments each note has on a listview. I am just learning Django and so far I have not been able to figure out how to retrieve and display the comment count. My view: (I do import count) class ProjectNotesList(ListView): model = ProjectNotes template_name = 'company_accounts/project_notes.html' comments = ProjectNotes.comments def related_project(self, **kwargs): project = get_object_or_404(Project, id=self.kwargs.get('pk')) notes = ProjectNotes.objects.all return notes def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context['project'] = get_object_or_404(Project, id=self.kwargs.get('pk')) return context commentscount = ProjectNotes.objects.annotate(num_comments=Count('comments')) My template: {% extends 'base.html' %} {% block content %} <div class="section-container container"> <h1>Notes for {{ project }}</h1> {% if project.notes.all %} {% for note in project.notes.all %} <div class ="projectnotes-entry"> <div class="col-sm-8"> <div class="row-sm-6"> <div class="card mb-2"> <div class="card-body"> <div class="card-title"><a href="{% url 'project_note_detail' project.pk note.pk %}">{{ note.title }}</a></div> <div class="card-text">{{ note.body | safe | truncatewords:"20"|linebreaks }} <a href="{% url 'project_note_detail' project.pk note.pk %}">read more</a></div> </div> </div> </div> </div> </div> <h2>comments count</h2> {{ commentscount }} {% endfor %} {% else %} <p>No notes have been have been added yet.</p> {% endif … -
Number of Likes is not increasing in the template but it's works in admin
I follow a tutorial in youtube just to add a like button to my Blog application, but the number of likes is not increasing in the template. but its increase when i highlight a user and hit save in the admin area. I mean its working fine in the admin but not in template. how can i set that ? the model: class Photo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.CharField(max_length=30,null=True, blank=False) image = models.ImageField(null=False, blank=False) description = models.TextField(null=True) date_added = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, related_name='blog_posts') def total_likes(self): return self.likes.count() def __str__(self): return str(self.category) the view: def like(request, pk): post = get_object_or_404(Photo, id=request.GET.get('post_id')) post.Likes.add(request.user) return HttpResponseRedirect(reverse('view', args=[str(pk)])) def viewPhoto(request, pk): post = get_object_or_404(Photo, id=pk) photo = Photo.objects.get(id=pk) stuff = get_object_or_404(Photo, id=pk) total_likes = stuff.total_likes() return render(request, 'photo.html', {'photo': photo, 'post': post, 'total_likes': total_likes}) the templates: <form action="{% url 'Photo' photo.id %}" method="POST"> {% csrf_token %} {{ total_likes }} <button type="submit", name="post_id" value="{{ post.id }}">Touch</button> </form> the urls: path('', views.login, name='login'), path('home', views.home, name='home'), path('view/<str:pk>/', views.viewPhoto, name='Photo'), path('post/create', views.PostCreativeView.as_view(), name='post_create'), path('register', views.register, name='register'), path('comment/<str:pk>/', views.comment, name='comment'), path('like/<str:pk>/', views.like, name='like_post'), -
Django, custom auto increment charfields
I'm new in Django, with this method I wanna customize it to generate item code as the Primary Key, like this: PC.202202.001 PC => Primary Key in item_category model 202202 => year & month 001 => auto increments Now, my questions is how to get object/value ForeignKey field based on selected data into variable? So, it'll change the PrimaryKey in generate_code field every time a new data has been added. Also, how to make auto increments in proper way? Because, right now I'm just using queryset .count() Here's my model: class item_category(models.Model): id_item = models.CharField(primary_key=True, max_length=5, unique=True) name_item = models.CharField(max_length=150) def __str__(self): return self.name_item def auto_increment(): last_item_code = item_code.objects.all().last() total_item = item_code.objects.all().count() + 1 join_dates = datetime.now().strftime('%Y%m.') if not last_kode_barang: return 'NB.' + str(join_dates) + '00' + str(total_item) else: item_cat_id = last_kode_barang.id_item_category + '.' new_item_id = str(kat_barang_id + join_dates + '00' + str(total_item)) if total_barang >= 10: new_barang_id = str(kat_barang_id + join_dates + '0' + str(total_barang)) return new_item_id class item_code(models.Model): id_item_category = models.ForeignKey(kategori_barang, on_delete=models.CASCADE, db_column='id_barang') generate_code = models.CharField(primary_key=True, editable=False, default=auto_increment, max_length=20) -
Hi my friends, I'm learning Django recently and I have a problem that I tried to solve a lot and the problem is 'int' object is not iterable [closed]
from django.shortcuts import render from .models import Signup from .forms import SignupForm email = [] def checkSignup(name): count = Signup.objects.all().count() for i in range(count): i+=1 ch = Signup.objects.get(i) if ch.name==name: return True return False def signup_index(request): context = {'form':SignupForm} if request.method == 'POST': name = request.POST.get('name') password = request.POST.get('password') if checkSignup(name) == False: email.append(name) data = Signup(name = name , password = password) data.save() else: print("This email already exists") return render(request, 'signup_index.html',context) -
OnetoMany field in django models
From my search it comes to my understanding there is no OnetoMany Field in django, can someone explain or simplify a solution if i wanted to have these three classes connected to each other. a UserRank class which i can define as many as ranks i want,example (captain,2nd eng,chief mate...etc) a User class which can have one of the above ranks, a job class which can have 1 or many ranks from the UserRank class models.py class UserRank(models.Model): rank = models.CharField(blank=True,null=True,max_length=150) def __str__(self): return self.rank class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=150,unique=True) name = models.CharField(max_length=150,) phone = models.CharField(max_length=50) date_of_birth = models.DateField(blank=True, null=True) picture = models.ImageField(blank=True, null=True, upload_to='users_imgs') is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) last_login = models.DateTimeField(null=True) user_rank = models.ForeignKey(UserRank,related_name='userRank',null=True,on_delete=models.SET_NULL) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email','name'] def get_full_name(self): return self.username def get_short_name(self): return self.username.split()[0] class Job(models.Model): job_type = ( ('I', 'Interval'), ('O', 'One time'), ) name = models.CharField(max_length=100) description = models.CharField(max_length=100) type = models.CharField(max_length=1, choices=job_type) interval = models.IntegerField() is_critical = models.BooleanField() due_date = models.DateField() user_rank = models.ManyToManyField(UserRank,related_name='ranks',blank=True) component = models.ForeignKey( Component, related_name='jobs', on_delete=models.CASCADE) runninghours = models.ForeignKey( RunningHours, related_name="RHjobs", on_delete=models.CASCADE) def __str__(self): return self.name -
Use an input password in django models and hash it
I'm trying to make a password field and hash it to have more security, but it didn't work trying to use form.InputPassword. Someone could help me? :) PS: I saw on stackoverflow using "forms" form django but im doing with models from django.db import models from uuid import uuid4 from django import forms class Cliente(models.Model): id_usuario = models.UUIDField(auto_created=True, default=uuid4, editable=False) nome = models.CharField(max_length=100, blank=False, null=False) senha = models.CharField(max_length=100, blank=False, null=False) -
Weasy-print convert to pdf with border image
Im trying to create pdf file for payment receipt. But im not able to figure out how do i set border for it. For border im using this image Like This . But While converting it to pdf next page gets Like this How can i make it constant border for all page Python + Django code: from weasyprint import HTML html_string = render_to_string('receipt.html', DATA) html = HTML(string=html_string) result = html.write_pdf() f = open(str(os.path.join(MEDIA_URL + "invoice_receipt/", 'temp.pdf')), 'wb') f.write(result) file_obj = File(open(MEDIA_URL + "invoice_receipt/" + "temp.pdf", 'rb')) transaction.receipt_file = file_obj transaction.save() receipt.html template: <style> table tbody tr td{ border-top: unset !important; } table tbody tr:nth-child(7) td, table tbody tr:nth-child(8) td, table tbody tr:nth-child(9) td, table tbody tr:nth-child(10) td, table tbody tr:nth-child(11) td, table tbody tr:nth-child(12) td { padding-top: 0; padding-bottom: 0; } .amount-in-words{ border-bottom:3px solid black; } .table thead th { vertical-align: bottom; border-bottom: 4px solid black; } /* .invoice-template{ padding: 20px; border: 20px solid transparent; border-image: linear-gradient(to right,#633363 50%,#f3c53d 50%); border-image-slice: 1; } */ .logo{ margin-top: 2rem; } .logo2{ margin-top: 2rem; height: 160px; width:200px; } .invoice-template{ padding: 20px; background-image: url('https://dev-api.test.com/files/files/DumpData/Frame.png'); background-repeat: no-repeat; background-size: contain; break-inside: auto; } .main-container{ border: 1px solid black; padding: 20px 10px; background: white; } p … -
Form is not valid Django
I am a beginner in Django/Python and whenever I try to submit my form the is_valid() method returns false. I have tried to display the errors using form.errors but it returns nothing or {}. When i try running the following code: form.non_field_errors() field_errors = [(field.label, field.errors) for field in form] I get [('', []), ('Required', [])] form.py class ApplicationForm(forms.ModelForm): email = forms.EmailField(label='', max_length=100, required=True, widget=forms.TextInput( attrs={'class': 'form-group form-control input-lg ', 'placeholder': 'Email'}), ) required = forms.ModelMultipleChoiceField(queryset=Requirements.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model = Requirements fields = ['email', 'required'] views.py def application_form(request): try: form = ApplicationForm() context = {'form': form} if request.method == 'GET': return render(request, 'requirements/job_specs.html', context) if request.method == 'POST': print(form.is_valid(), form.errors) if form.is_valid(): form.save() return JsonResponse({'created': True}) form.non_field_errors() field_errors = [(field.label, field.errors) for field in form] print(field_errors) return JsonResponse(form.errors.as_json(), safe=False) except Exception as e: print(e) form = ApplicationForm(request.POST or None) context = {'form': form} return render(request, 'requirements/job_specs.html', context) HTML <form method="POST" id="application-form"> {% csrf_token %} {{ form }} <div class="bg-light row" > <div class="" id="btn-box"> <div class="col-md-12 d-grid gap-2 col-6 "> <button type="submit" class="btn btn-primary btn-lg">Save</button> </div> </div> </div> </form> I have tried to apply solutions from similar posts such as Django forms is not valid or Django forms is … -
Django automatically resubmitting the form on refreshing the page
Whenever I fill the form then I click on submit button of the form to store it in the database it stored the data perfectly but when I refresh the page it again submits. So the problem is it is showing the same data multiple times in the database. Here is my Django Template code <h4 class="text-center alert alert-success">Add New Students</h4> <form action="" method="POST"> {% csrf_token %} {{form.as_p}} <input type="Submit" class="btn btn-success" value="Add"> How can I tackle this ? Here is my view function def add_show(request): if request.method == 'POST': fm = StudentRegistration(request.POST) if fm.is_valid(): nm = fm.cleaned_data['name'] em = fm.cleaned_data['email'] pw = fm.cleaned_data['password'] reg = User(name=nm, email=em, password=pw) reg.save() fm = StudentRegistration() else: fm = StudentRegistration() stud = User.objects.all() return render(request, 'enroll/addandshow.html', {'form': fm, 'stu':stud}) -
Django pagination Listview inside a Detailsview
i'm trying to call listview inside a detailview of two different models and i want pagination of listview but passing paginate_by seem it dosent work, how have to do to? class TagsDetailView(DetailView): model = Tag paginate_by = 50 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) IL = ItemsListView(tag=tag.tag, paginate_by=8) setattr(IL, 'paginate_by', 8) context['test'] = IL.get_queryset() print(context['test']) return context -
Time out error while sending email in django
Below configs added in my settings.py, since there is no password or user name is required for this email settings, I haven't added the EMAIL_HOST_USER and EMAIL_HOST_PASSWORD settings.py file EMAIL_HOST = 'sample.outlook.com' EMAIL_PORT = 25 EMAIL_USE_TLS = True FROM_EMAIL = 'no-reply@sample.com' when I tried to execute the below comments from shell from django.core.mail import send_mail send_mail("test sub","test_msg","no-reply@sample.com",["ajith@gmail.com"]) getting the below error Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/ubuntu/.local/share/virtualenvs/paralel-P-lwtg7n/lib/python3.8/site-packages/django/core/mail/__init__.py", line 61, in send_mail return mail.send() File "/home/ubuntu/.local/share/virtualenvs/paralel-P-lwtg7n/lib/python3.8/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/ubuntu/.local/share/virtualenvs/paralel-P-lwtg7n/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/home/ubuntu/.local/share/virtualenvs/paralel-P-lwtg7n/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "/usr/lib/python3.8/smtplib.py", line 253, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python3.8/smtplib.py", line 339, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python3.8/smtplib.py", line 308, in _get_socket return socket.create_connection((host, port), timeout, File "/usr/lib/python3.8/socket.py", line 807, in create_connection raise err File "/usr/lib/python3.8/socket.py", line 796, in create_connection sock.connect(sa) TimeoutError: [Errno 110] Connection timed out -
Django: authenticate & login function works but user isn't actually logged in
i have a problem related to logging a user in in Django. in the lines of code below, i have tried to use the login function to log the user in, but when the user gets to the main page the page tells them to log in (meaning that django told me that they're not authenticated); the login function doesn't raise any errors at all. login/login.py def login_user(request): if request.method == "POST": form = forms.Login(request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] db_user = AuthBackend().authenticate(request, username=username, password=password) if db_user is not None: login(request, db_user, backend="django.contrib.auth.backends.ModelBackend") return HttpResponseRedirect(reverse("main:index")) else: return render(request, "login/login.html", {"form": form, "error": "Incorrect"}) else: return render(request, "login/login.html", {"form": form}) return render(request, "login/login.html", {"form": forms.Login()}) main/templates/main/index.html <!DOCTYPE html> <html> <head> <title>Timeline</title> </head> <body> {% if user.is_authenticated %} <a href="{% url 'account' %}">Account</a> {% else %} <a href="{% url 'login:login' %}">Log In</a> {% endif %} </body> </html> also, im very new to stack and making questions, so if i have to provide other info i would appreciate the reminder and ill try to be helpful as possible. thanks -
What is the best way to transfer large files through Django app hosted on HEROKU
HEROKU gives me H12 error on transferring the file to an API from my Django application ( Understood its a long running process and there is some memory/worker tradeoff I guess so. ) I am on one single hobby Dyno right now. The function just runs smoothly for around 50MB file. The file itself is coming from a different source ( requests python package ) The idea is to build a file transfer utility using Django app on HEROKU. The file will not gets stored in my app side. Its just getting from point A and sending to point B. Went through multiple discussions along with the standard HEROKU documentations, however I am struggling in between in some concepts: Will this problem be solved by background tasks really? ( If YES, I am finding explanation of the process than the direct way to do it such that I can optimise my flow ) As mentioned in standard docs, they recommend background tasks using RQ package for python, I am using Postgre SQL at moment. Will I need to install and manage Redis Database as well for this. Is this even related to Database? Some recommend using extra Worker other than … -
Django. How to filter posts with a date less than the current post?
I'm new to programming. And I don't understand methods. On the detailview post page I want to display a list of the next posts (i.e. whose time is less than the time of the current post) How do I access the date of the current post? I try: class PostDetailView(DetailView): model = Post slug_field = 'url' context_object_name = 'post' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['earlier_posts'] = Post.objects.filter(publication_date__lte=self.publication_date) return context Then I have an error: 'PostDetailView' object has no attribute 'publication_date' Thank you in advance -
Put Query Parameters in url request Django
I have a query that retrieves all the data but I would like to make another query with another url by adding query parameters in order to target my data search. For example when I request the following url: http://localhost:8000/api/calendars I have this result: [ { "id": 1, "plant_step_id": [ { "id": 3, "plant_id": { "id": 1, "name": "Agropyre" }, "step_title": "Sowing" } ], "start": [ 1 ], "end": [ 3 ] }, { "id": 2, "plant_step_id": [ { "id": 6, "plant_id": { "id": 6, "name": "Aubergine" }, "step_title": "Planting" } ], "start": [ 6 ], "end": [ 7 ] } ] And I would like by requesting this url: http://localhost:8000/api/plant/life/calendars?plant_id=1&step_title=Sowing I would like to have the data concerning what I requested in the url. I tried to achieve this in the view but didn't work. Here is the model: from django.db import models from multiselectfield import MultiSelectField MONTHS = ( (1, 'January'), (2, 'February'), (3, 'March'), (4, 'April'), (5, 'May'), (6, 'June'), (7, 'July'), (8, 'August'), (9, 'September'), (10, 'October'), (11, 'November'), (12, 'December') ) class PlantLifeCalendar(models.Model): plant_step_id = models.ManyToManyField('perma_plant_steps.PlantStep') start = MultiSelectField(choices=MONTHS, max_choices=3, max_length=6) end = MultiSelectField(choices=MONTHS, max_choices=3, max_length=6) Here is the serializer: class PlantSerializer(serializers.ModelSerializer): class Meta: model … -
mod_wsgi-express causing ModuleNotFoundError: No module named "mod_wsgi.server"
I'm trying to deploy the Django 3.2 project with Python 3.10 on CentOS 7 but I am facing issues in it. I'm trying to run the following command to run mod_wsgi-express: mod_wsgi-express start-server django_wsgi.py --server-root /var/www --user apache --group apache --port 80 --host XYZ where XYZ is the IP of the machine i'm running this command on. I had to specify a different server root as my /tmp is noexec. The contents of django_wsgi.py are: import os import sys project_dir=os.path.dirname(__file__) if project_dir not in sys.path: sys.path.append(project_dir) from django.core.wsgi import get_wsgi_application os.environ['DJANGO_SETTINGS_MODULE'] = 'MY_PACKAGE_WHERE_SETTINGS_ARE.settings' application = get_wsgi_application() but I keep getting this error: [mpm_event:notice] [pid 101737:tid 139778434865344] AH00489: **Apache/2.4.52 (codeit) mod_wsgi/4.9.0 Python/3.10** configured -- resuming normal operations [core:notice] [pid 101737:tid 139778434865344] AH00094: Command line: 'httpd (mod_wsgi-express) -f /var/www/httpd.conf -D MOD_WSGI_KEEP_ALIVE -D MOD_WSGI_WITH_LISTENER_HOST -D MOD_WSGI_MPM_ENABLE_EVENT_MODULE -D MOD_WSGI_MPM_EXISTS_EVENT_MODULE -D MOD_WSGI_MPM_EXISTS_WORKER_MODULE -D MOD_WSGI_MPM_EXISTS_PREFORK_MODULE -D FOREGROUND' mod_wsgi (pid=101741): Exception occurred processing WSGI script '/var/www/handler.wsgi'. [wsgi:error] [pid 101741:tid 139778434865344] Traceback (most recent call last): [wsgi:error] [pid 101741:tid 139778434865344] File "/var/www/handler.wsgi", line 7, in <module> [wsgi:error] [pid 101741:tid 139778434865344] import mod_wsgi.server [wsgi:error] [pid 101741:tid 139778434865344] ModuleNotFoundError: No module named 'mod_wsgi.server' The error says "handler.wsgi", I don't know if that is correct or it is not accepting my … -
Share database between local psql and docker compose postgres container
thanks for stopping here. i need some advices to share postgres database between local psql and docker compose postgres container. i'm on debian based linux stack is django 3.2 posgresql 12 so i have a compose file with a docker volume and local driver: version: "3.9" volumes: db_data: name: db_data driver: local services: db: container_name: db image: postgis/postgis:12-3.1 depends_on: - server volumes: - db_data:/var/lib/postgresql/data:rw ports: - "5432:5432" env_file: - "./.env" server: container_name: server build: ./server/ volumes: - ./server:/server ports: - "8000:8000" env_file: - "./.env" both container are running properly but my local psql don't see any database i created or modified: when i run docker-compose exec db psql -U postgres i see my database but locally impossible to link with those data i went through a lot of thread and tutorial and i worked around: container networks with network_mode :'host but didn't work ip addresses mapping changing dependencies of containers to depends_on: - db ... i'm not that experienced, and if you could provide a workaround it would be amazing. i spent days on this issues. Thanks in advance, -
How to include and execute JavaScript in Django templates?
I've read many other questions and answers, and of course the documentation. However, I still can't make my JS code run inside my templates. base.html {% load static %} {% load i18n %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>{% block title %}{% translate "DaniMundo" %}{% endblock title %}</title> <link href="{% static 'css/default.css' %}" rel="stylesheet" type="text/css" media="all" /> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <aside> {% include "navigation.html" %} </aside> <main> {% block content %}{% endblock content %} </main> <script src="{% static 'js/clipboard.js' %}"></script> <script src="{% static 'js/custom.js' %}"></script> </body> </html> blog/article_details.html {% extends "base.html" %} {% load i18n %} {% load custom_filters %} {% block title %}{{ article.title }} | {{ block.super }}{% endblock title %} {% block content %} <article> <header> <h1 class="title">{{ article.title }}</h1> <p>{% translate "Date of publication:" %} {{ article.date_created }}</p> <p>{% include "blog/article_authors.html" %}</p> </header> <p class="summary">{{ article.summary }}</p> {{ article.body|markdown|safe }} {% if article.date_updated != article.date_created %}<p>{% translate "Last update:" %} {{ article.date_updated }}</p>{% endif %}<hr /> <div class="comments"> {% include "blog/comments.html" with article_path=article.get_absolute_url article_slug=article|full_slug %} </div> </article> {% endblock content %} custom.js function checkAnswer(origin) { var question_name = $(origin).attr("data-question"); var correct_answer_element = $(origin).attr("data-correct"); var correct_answer_id = $("#"+correct_answer_element).val(); var correct_answer_label … -
Why does user.user_permissions.all() return an empty queryset in django even if the user has default permissions?
I would like to know the reason behind user.user_permissions.all() returning an empty queryset even if the user has default permissions. I read somewhere that user_permissions are the permissions that are defined explicitly, so I am not exactly sure when to assign these permissions explicitly if the user already has them defined. To demonstrate: from django.contrib.auth.models import Permission from apps.user.models import User user=User.objects.get(id=29) print(user.is_superuser) True # as a superuser has 272 permissions print(len(user.get_all_permissions())) 272 # no explicit assignment, returns an empty queryset print(user.user_permissions.all()) <QuerySet []> Now my main question is if the user has a given permission defined, such as print(user.has_perm('add_company')) True is there any benefit of doing #explicitly adding 'add_company' permission. permission=Permission.objects.get(codename='add_company') user.user_permissions.add(permission) print(user.user_permissions.all()) <QuerySet [<Permission: main | company | Can add company>]> Thanks in advance. -
Django Admin replace field with ModelChoiceField with specific query
I searched the net but did not find an answer - but I also a bloody beginner. I basically have to models from two apps, but I don´t want to make a relation between both because of dependencies. By creating an new sensor object in admin panel, I want that you only can choose between existing customer_names(Customer). I managed to override the field "owner" ins Sensor Admin panel and Django is also saving the values in the database. But everytime I revisit a sensor object in admin panel, owner is showing the default value "--" and I have to choose an owner. (Sensor App)models.py class Sensor(models.Model): owner = models.CharField(max_length=20, null=True) (Customer App)models.py class Customer(models.Model): customer_name = models.CharField(max_length=20, null=True) forms.py class SensorAdminForm(forms.ModelForm): owner = forms.ModelChoiceField(queryset = Customer.objects.all()) class Meta: model = Sensor fields = '__all__' admin.py class SensorAdmin(OSMGeoAdmin): list_display = ('owner',) form = SensorAdminForm admin.site.register(SensorRec, SensorRecAdmin) -
show all likes count in each post django REST API
models.py class Post(models.Model): title = models.CharField(max_length=150) class PostLike(models.Model): like = models.CharField(max_length=20) user = models.ForeignKey(User,on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) Serializer.py class PostSerializer(serializers.ModelSerializer): likes = serializers.SerializerMethodField("like_count") class Meta: model = Post fields = ("__all__") def like_count(self,obj): total_like = self.context.get("like_count") return total_like views.py @api_view(["POST"]) def allpost(request): id = request.data post_list = Post.objects.all() like_count = PostLike.objects.filter(post_id = id ).count() post_serializer = PostSerializer(post_list,many=True,context={"like_count":like_count}) return Response(request,post_serializer.data) output: [ { "id": 1, "likes": 1, "title": "post 1", }, { "id": 2, "likes": 1, "title": "post 2", }, { "id": 3, "likes": 1, "title": "post 3", }, ] db id like post_id user_id 1 1 1 1 2 1 2 1 3 1 1 2 actually in my db likes are: post 1 have 2 likes post 2 have 1 like post 3 don't have any like i want to show this like this . but it's showing the first post likes for every post . how can i fix this .? i know the problem in the like_count in view . but i don't know what to put there instead of id . sorry for my poor English Thanks in advance -
Adding answer count field in Django Rest Framework
I have got 2 models, Questions and Answers. class Question(models.Model): question_subject = models.TextField() question_text = models.TextField(default=None, null=True, blank=True) slug = models.SlugField(max_length=128, unique=True, null=False, editable=False) created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) animal = models.ForeignKey('animals.Animal', on_delete=models.PROTECT) class Answer(models.Model): answer = models.TextField() created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) question = models.ForeignKey('Question', on_delete=models.PROTECT) number_of_points = models.IntegerField(default=0) moderate_status = models.BooleanField(default=False) The answer is connected to the Question via question field(Foreign key), but now i'm creating API for this and i need to list all the questions and the answer_count related to them. Right now i have a simple class QuestionsSerializer(serializers.ModelSerializer): class Meta: model = Question fields = '__all__' class QuestionsList(generics.ListAPIView): queryset = Question.objects.all() serializer_class = QuestionsSerializer Do you have any idea how to display the count of answers in a Question? In django views i would use something like aggregate count, but it won't work in DRF. -
my form_valid method isn't working properly
I was working in a project and I am having trouble to understand why my form_valid method is not working for ProfileCreateView. I have created a profile model for user. This is the code: # views.py from django.views.generic import CreateView from .models import UserProfile from django.urls import reverse_lazy class ProfileCreateView(CreateView): model = UserProfile template_name = "profile/profile_create.html" fields = ('profile_picture', 'bio', 'occupation', 'hobbies', 'date_of_birth') success_url = reverse_lazy("login") def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) # template {% extends 'base.html' %} {% block title %}Create Your Profile{% endblock title %} {% load crispy_forms_tags %} {% block content %} <div class="container border border-success rounded mt-4 "> <h2 class="display-6 fst-italic mt-3 mb-3">Create Your Profile</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy}} <button type="submit" class="btn btn-outline-primary mt-4 mb-4">Create my profile</button> </form> {% endblock content %} # models.py from django.db import models from django.contrib.auth import get_user_model import uuid from django.core.files.storage import FileSystemStorage class UserProfile(models.Model): author = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) profile_picture = models.ImageField(upload_to='images/') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) bio = models.TextField(blank=True) occupation = models.CharField(max_length=100) hobbies = models.TextField(blank=True) date_of_birth = models.TimeField() def __str__(self): return self.author.username + ("'s profile") please tell me how to work this properly!