Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to access django bash in portainer?
I am able to access the django docker using the following in the cloud console docker exec -it backend bash How can I do the equivalent in Portainer GUI? It is just stuck in Exec into container as default user using command bash -
Check cell value, recalculate and overwrite xlwt
Trying to achieve the following: Loop through a list with this type of objects: #1 Cost: 12 Unit: per month Amount: 3 users #2 Cost: 32 Unit: per quarter Amount: 2 users etc And make a forecast xls export based on this for each month: Jan - 100 (312 + 322) Feb - 36 (312) March - 36 (312) Apr - 100 (312 + 322) etc My implementation of this was as follows: for po in queryset.select_related( 'quote__relatie', 'entity', 'delivery_address', 'requester', 'approver',): row_num += 1 ws.write(row_num, 0, str(po.costcode), font_style) ws.write(row_num, 1, str(po), font_style) ws.write(row_num, 2, str(po.quote.relatie), font_style) ws.write(row_num, 2, str(po.project), font_style) for cl in po.inkooppost_set.all(): data = {} if cl.eenheid.recurrent: for pc in range(cl.aantal): if cl.invoice_date: invoice_date = (cl.invoice_date + datetime.timedelta( days=(pc * cl.eenheid.frequency))) #find columnnumber r = relativedelta(invoice_date, month.order_date) col_num = (r.years*12) + r.months + 3 #check whether another cost has been inferred and update cell print(col_num) if data.get(col_num): data.update({col_num: data.get(col_num) + cl.eenheidprijs}) else: data.update({col_num: cl.eenheidprijs}) ws.write(row_num, col_num, data[col_num], font_style) else: invoice_date = cl.invoice_date r = relativedelta(invoice_date, month.order_date) print(r) col_num = (r.years *12) + r.months + 3 print(data.get(col_num)) if data.get(col_num): data.update({col_num: data.get(col_num)+ cl.eenheidprijs}) else: data.update({col_num: cl.eenheidprijs * cl.aantal}) ws.write(row_num, col_num, (cl.eenheidprijs * cl.aantal), font_style) Using a dict to build … -
Error while generating FCM token using django
This is error that i am getting in my javascript console An error occurred while retrieving token. DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded. at https://www.gstatic.com/firebasejs/8.6.3/firebase-messaging.js:1:25606 I am trying to send push notification from firebase but getting error. any one plz help me. i am trying to generate FCM token in javascript console but getting error here is my index.html file where i am getting import error index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://www.gstatic.com/firebasejs/8.6.3/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/8.6.3/firebase-analytics.js"></script> <script src="https://www.gstatic.com/firebasejs/8.6.3/firebase-messaging.js"></script> {% comment %} <script src="/static/js/firebase-messaging-sw.js"> {% endcomment %} <script> var firebaseConfig = { apiKey: "AIzaSyAcV-zkELH2kC2ylNcqfxcAF9LLmyJW3n8", authDomain: "fir-push-notification-ca088.firebaseapp.com", databaseURL: "https://fir-push-notification-ca088-default-rtdb.firebaseio.com", projectId: "fir-push-notification-ca088", storageBucket: "fir-push-notification-ca088.appspot.com", messagingSenderId: "123105123891", appId: "1:123105123891:web:59c426864dd7b8c35ecd46", measurementId: "G-NEZ3NC2GYL" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); firebase.analytics(); const messaging = firebase.messaging(); console.log(messaging.getToken()) messaging.getToken({ vapidKey: 'AAAAHKmjHjM:APA91bEWX1Mrp6HIfjx6Y4n2chW2GpfB3GzrwQp1T1KQ3i5a_4mVnEhEa_hd95c-N9ZADi8fTUobdhlvs5d0b1JMrYWE_sJ1KjsdnXLMg4rxOAFPem4nxpazNtimZEb2PGKtHZAB9sKX' }).then((currentToken) => { if (currentToken) { console.log(currentToken) } else { console.log('No registration token available. Request permission to generate one.'); } }).catch((err) => { console.log('An error occurred while retrieving token. ', err); }); messaging .requestPermission() .then(function () { console.log("Notification permission granted."); return messaging.getToken() }) .catch(function (err) { console.log("Unable to get permission to notify.", err); }); messaging.onMessage((payload) => { console.log('Message received. … -
Get sub One To Many relation from specific model in django
I have two models User and Sale, each sale has a buyer and a seller. I would like to get all buyers (also Users) from a specific user my_user. class User(models.Model): name = models.CharField(max_length=250, default='', blank=True) # more fields.... class Sale (models.Model): buyer = models.ForeignKey( User, blank=False, null=False, related_name='purchases', on_delete=models.CASCADE, ) seller = models.ForeignKey( User, blank=False, null=False, related_name='sales', on_delete=models.CASCADE, ) # more fields.... This works fine: User.objects.filter(purchases__seller = my_user) But I would like to know if there is a way to do it by using the my_user object directly. Something like this my_user.sales.buyer Thanks in advance guys -
What should i do to learn django-ninja
I am a beginner in programming, I'm trying to learn Django-ninja but I'm confused, what should I learn first, I know some basics of python. Will I need to learn Django first? I will be thankful if anyone have a map learn that leads to Django-ninja -
How to backup user files before pulling repository in jenkins
I have a django project which is deployed in a docker container. I created a pipeline in jenkins triggered via github webhooks. Everyting works fine but I have some user files in project directory which I want to backup before jenkins pull the repository. Is there a way to add a pre build step to my pipeline script or avoid deleting files when running git pull command ? -
django redirect to form view and autofill with previously entered values
I have following scenario. User fills out a form If the user clicks the "continue" button and the form is valid the user will be redirected to a summary view In the summary view the user checks the input again. He can either continue or go back. If he continues the data will be saved in the database, if he goes back he can edit the form. Since in step 4 the user is at the view summary I have to redirect him to the home view. I don´t want the user to fill out the entire form again, the previously entered data should be autofilled if he goes back. Something special: I am using django-tagify2 for one input in the form to get tags rather then text. If the user goes back the tags should be rendered correctly in the tagify specific form. So here are my files: home.html {% extends "messenger/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="message-container"> <form method="POST" autocomplete="off"> {% csrf_token %} {{ form|crispy }} <button name="sendmessage" class="btn btn-outline-info" type="submit">Continue</button> </form> </div> {% endblock content %} summary.html {% extends "messenger/base.html" %} {% block content %} <h4>Zusammenfassung</h4> <p><b>Empfänger: </b>{{ receiver }}</p> <br> <p><b>Betreff: … -
Upload file to server temporarily to process it from django
I am developing a website in django which will convert one file type to another. Main core logic of conversion is done in python, but now as for website, the file needs to be uploaded temporarily on the server, so that server can do the conversion and produce new file to be downloaded. How is this to be accomplished? -
How can I serialize one to many models in Django Rest?
So I have two models Invoice and Items. Invoices can have many Items. Here's how they are defined: class Invoice(models.Model): customer_name = models.CharField(max_length = 200, verbose_name='Customer Name') customer_phone = models.IntegerField(null = True, blank = True, verbose_name='Customer Phone') customer_address = models.TextField(null = True, blank = True, verbose_name='Customer Address') invoice_id = models.UUIDField(primary_key = True, unique = True, default=uuid.uuid4, verbose_name='Invoice ID') invoice_date = models.DateField(auto_now_add=True, verbose_name='Invoice Date') def __str__(self): return self.customer_name + ' - ' + str(self.invoice_id) class Meta: verbose_name = 'Invoice' verbose_name_plural = 'Invoices' class Items(models.Model): invoice = models.ForeignKey(Invoice, on_delete = models.CASCADE, related_name='invoice') item_name = models.CharField(max_length = 200, null = False) item_quantity = models.IntegerField() item_price = models.IntegerField() item_id = models.AutoField(primary_key=True) def __str__(self): return self.item_name class Meta: verbose_name = 'Items' verbose_name_plural = 'Items' I want to implement two API endpoints, one to get the list of invoices, and another to get a specific invoice with its items. For example, /api/ will return all invoices [ { "customer_name": "John Doe", "customer_phone": 111666, "customer_address": "Palo Alto, California", "invoice_id": "a8aeb5a8-5498-40fd-9b4f-bb09a7057c71", "invoice_date": "2022-05-04" }, { "customer_name": "Cassian Green", "customer_phone": 111000, "customer_address": "2112 Illinois Avenue", "invoice_id": "7d7b7878-3ffc-4dd2-a60a-fa207c147860", "invoice_date": "2022-05-04" }, { "customer_name": "Chelsea Davis", "customer_phone": 666777, "customer_address": "2260 Coplin Avenue", "invoice_id": "3dda2054-49d7-49dc-9eba-ddc0fdacfd3b", "invoice_date": "2022-05-04" }, { "customer_name": "Derek Elliott", … -
access variable in template from views.py - Django
This is my first time messing with django and I am having trouble passing variables from a view function to a template html file. views.py def index(request): try: ms_identity_web.acquire_token_silently() authZ = f'Bearer {ms_identity_web.id_data._access_token}' graph_user_picture = requests.get(settings.USERPHOTO, headers={"Authorization": authZ}) file = open("Sample/static/user_iamge"+str(ms_identity_web.id_data.username).split(" ")[0]+".png", "wb") file.write(graph_user_picture.content) file.close() clamdata = context_processors.context(request) print(clamdata["claims_to_display"]["preferred_username"]) userdata = requests.get(settings.ENDPOINT+"/"+clamdata["claims_to_display"]["preferred_username"], headers={"Authorization": authZ}).json() print(userdata) return render(request, "flow/index.html", userdata) except Exception as e: print(e) return render(request, "flow/start.html") and I am trying to send userdata over to index.html like so: <div class="ms-Persona-details"> <div class="ms-Persona-primaryText">{{ userdata["displayName"] }}</div> <div class="ms-Persona-secondaryText">{{ userdata["jobTitle"] }}</div> <div class="ms-Persona-tertiaryText">{{ userdata["businessPhones"][0] }}</div> <div class="ms-Persona-tertiaryText">{{ userdata["userPrincipalName"] }}</div> </div> However, I am getting either no variables showing up on the screen or I get an error like this: Could not parse the remainder: '["displayName"]' from 'userdata["displayName"]' I assume I am missing something basic in index.html to pass variables from the views.py to the index.html file -
I use Django with PostgreSQL on docker compose, but django-test can't access database
I practice Writing your first Django app, part 5, it's django test section. And my environment is: Django 4.0 Python 3.9 Database PostgreSQL 14.2 Docker compose In addition, the connection to PostgreSQL is configured via .pg_service.conf and .pgpass. docker-compose.yml version: "3.9" services: web: build: context: . container_name: web restart: unless-stopped tty: true working_dir: /opt/apps volumes: - .:/opt/apps/ - .pgpass:/root/.pgpass - .pg_service.conf:/root/.pg_service.conf entrypoint: "./entrypoint.sh" command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" depends_on: - db db: image: postgres container_name: db environment: POSTGRES_USER: ${DB_USER} POSTGRES_PASSWORD: ${DB_PASSWORD} ports: - ${DB_PORT}:5432 volumes: - postgres_data:/var/lib/postgresql/data volumes: postgres_data: networks: django-tutorial: compose .env file DB_USER=postgres DB_PASSWORD=postgres DB_HOST=db DB_PORT=5432 .pg_service.conf [DB] host=db user=postgres dbname=django_tutorial port=5432 .pgpass db:5432:postgres:postgres:postgres When docker-compose up -d is executed with the above configuration and python manage.py migrate is executed, the migration is performed no problems and the database is accessible. However, when I try to run the test as in python manage.py test polls, I get the following error. (The test is the same as the code in the link at the beginning of this article.) Do I need any additional configuration for the test DB? docker compose exec web python manage.py test polls ✔ 15:20:03 Found 1 test(s). Creating test … -
Is there any article or book which guide reverse engineering for the django framework?
I want to learn how to reverse engineering the django framework. If there is some article or book available for it then please suggest me. -
Django giving "Reverse for 'view' not found" error when view is defined
While using django 4.0.4 I have encountered the error "Reverse for 'upload' not found. 'upload' is not a valid view function or pattern name". It was working earlier in the day, and I can't figure out the problem for the life of me. I'll include my views.py, urls.py, and the relevant section of my html file, all three of which are in the same folder of the project. If anyone has any advice I would greatly appreciate it. Views.py def welcome(request): return render(request, 'welcome.html') def contact(request): return render(request, 'contact-us.html') def how(request): return render(request, 'How-to-use.html') def upload(request): if request.method == 'POST': if 'scatter_plot' in request.POST: form = UploadFileForm(request.POST.get, request.FILES) file=request.FILES['document'] csv = CSV.objects.create(doc=file) os.system('python ../scatter_plot.py') if 'line_plot' in request.POST: form = UploadFileForm(request.POST.get, request.FILES) file=request.FILES['document'] csv = CSV.objects.create(doc=file) os.system('python ../line_plot.py') return render(request, 'uploaded.html') else: form = UploadFileForm Urls.py urlpatterns = [ path('', views.welcome), path('admin/', admin.site.urls), path('contact-us/', views.contact), path('upload.html', views.upload), path('upload/', views.upload), path('welcome/', views.welcome), path('How-to-use/', views.how), path('contact-us.html', views.contact), path('welcome.html', views.welcome), path('How-to-use.html', views.how) ] Welcome.html <form method="POST" enctype="multipart/form-data" action="{% url 'upload' %}"> {% csrf_token %} <input type='file' name='document' accept='.csv'> <button type='submit' name='line_plot'>Graph as a line Graph</button> <button type='submit' name='scatter_plot'>Graph as a Scatter Plot</button> </form> -
How to test correctly this func in Django?
I have a test which check user can create a news or not. But my test doesn't work. I suppose I do something wrong with 'category' and 'author', but I don't know how to change it correctly. When I create a news in site by myself, everything work right. Test: @classmethod def setUpTestData(cls): user = User.objects.create(username='test1') user.set_password('test1') user.save() Profile.objects.create(user=user) NewsCategory.objects.create(category='Sport') def test_if_user_can_create_news(self): user = self.client.login(username='test1', password='test1') self.client.post(reverse('create_news'), { 'title': 'News 1', 'description': 'Description news 1', 'category': NewsCategory.objects.get(category='Sport'), 'author': user }) self.assertTrue(News.objects.filter(title='News 1').exists()) Models: class News(models.Model): title = models.CharField(max_length=200, verbose_name='Title') description = models.TextField(verbose_name='Description') category = models.ForeignKey(NewsCategory, on_delete=models.CASCADE, verbose_name='Category') author = models.ForeignKey(Profile, on_delete=models.CASCADE, verbose_name='Author') class NewsCategory(models.Model): category = models.CharField(max_length=100, verbose_name='Category') Form: class NewsForm(forms.ModelForm): class Meta: model = News fields = 'title', 'description', 'category' -
how to implement raw sql query in DRF with paramters
Hi Everyone i am trying to implement raw sql query to create api in django framework and input paramter is team_id, start_date and end_date. like team_id=1 and start=2022-04-25 and end_date=2022-05-01, and temp1 query date like 7 date from 2022-04-25 to 2022-05-01. how will do this,please help me out. SELECT temp1.car_number,temp1.trips,temp1.status, case when temp1.date= %s then temp1.trip else 0 end as day1_trips, case when temp1.date= %s then temp1.trip else 0 end as day2_trips, case when temp1.date= %s then temp1.trip else 0 end as day3_trips, case when temp1.date= %s then temp1.trip else 0 end as day4_trips, case when temp1.date= %s then temp1.trip else 0 end as day5_trips, case when temp1.date= %s then temp1.trip else 0 end as day6_trips, case when temp1.date= %s then temp1.trip else 0 end as day7_trips from (SELECT date, car_number,driver_id,trips,car_status,status, case when trips=0 THEN else trips end as trip FROM fleet_car_dash_daily /this is input paramter/ WHERE team_id= %s and (date BETWEEN %s and %s))as temp1 group by temp1.date -
RuntimeError: __class__ not set defining 'AbstractBaseUser'
Django app works fine local, but when pushed to heroku build works, but deploy fails: RuntimeError: __class__ not set defining 'AbstractBaseUser' as <class 'django.contrib.auth.base_user.AbstractBaseUser'>. Was __classcell__ propagated to type.__new__? reading older posts this has been attributed to Django version / python version incompatibilities. This is a recent version: Django 3.2.13 and Python 3.9.12. This is confirmed to work together. Tried downgrading / upgrading, but without succes. Any one has an idea how to resolve? -
Error Using Ajax when I load from a differente file with Django
Im using JaxaScript(Jquery with Ajax) and my HTML Page all in the same file, but when I tried to code my JS and HTML in different files, I get an error when trying to ajax with Django. JS: $(document).on('click', '#add-button', function (e) { e.preventDefault(); value = $(this).data("forloopcounter"); value = value - 1 let variation_id = document.getElementsByClassName("select-variations")[value].attributes[2].nodeValue console.log(variation_id) $.ajax({ type: "POST", url: '{% url "cart:add" %}', data: { variationid: variation_id, productquantity: 1, csrfmiddlewaretoken: "{{csrf_token}}", action: 'post' }, success: function (json) { document.getElementById("cart-quantity").innerHTML = json.quantity }, error: function (xhr, errmsg, err) { console.log(xhr) } }); }) Note: I have a guess it's because of this url: '{% url "cart:add" %}', but I don't know how to fix. Note: when I ajax with all in the same page it works. Note it's not an importation error, when i execute console.log it works Error I get in the web: jquery.min.js:4 POST http://127.0.0.1:8000/%7B%%20url%20%22cart:add%22%20%%7D 404 (Not Found) -
Can I use "-" in django project name
While I am trying to create a new project in Django I got this error command used : django-admin startproject test-service 'test-service' is not a valid project name. Please make sure the name is a valid identifier. Then I tried with django-admin startproject test_service and it is working. Can you please confirm whether i can use dash in project name. I am planning to do a uniq naming convention for upcoming projects also. -
Django : stop access to my web app from being accessed on port 8000 and access only using the IP
I have deployed my Django web app on a digital ocean droplet. The python server is running on port 8000. python manage.py runserver 0.0.0.0:8000 I have configured apache web server to serve the requests. /etc/apache2/sites-available/000-default.conf <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /etc/myproject ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined #Serving static files Alias /static/ /etc/myproject/static/ <Directory /etc/myproject/static> Require all granted </Directory> <Directory /etc/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/etc/myproject python-home=/etc/myprojectenv WSGIProcessGroup myproject WSGIScriptAlias / /etc/myproject/myproject/wsgi.py </VirtualHost> Now when I am accessing my web app using the IP address X.X.X.X, I am able to see my app, however the app is also accessible on port 8000, X.X.X.X:8000. I want to prevent my app from being accessed on any other port except being accessed ousing IP. How can I do that? -
How Can I Search One Model and get Related Fields from Another Model in Django
I am working on a project in Django where I have two Models; Profile and submitted_apps. How do I efficiently relate these Models such that I would be able to get applicant's profile details like username, nation, state, upon search of submited_app Model. Is it good to use a OneToOneFields where as I did here on all Models. Understand that the submitted_apps Model is recording those applicants who successfully submitted their application form. I also have a ModelForm form named Applicant_Search_Form. Profile Model Code below class Profile(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True) surname = models.CharField(max_length=10, null=True) othernames = models.CharField(max_length=30, null=True) gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True) nation = models.CharField(max_length=10, choices=NATION, blank=True, null=True) state = models.CharField(max_length=20, null=True) address = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=11, null=True) image = models.ImageField(default='avatar.jpg', upload_to ='profile_images') Submitted Model Code below" class submited_apps(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null=True) application = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4) confirm = models.BooleanField() date = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): self.application == str(uuid.uuid4()) super().save(*args, **kwargs) def __unicode__(self): return self.applicant def __str__(self): return f'Application Number: {self.application}-{self.applicant}' Here is my code for the ModelForm class Applicant_Search_Form(forms.ModelForm): class Meta: model = submited_apps fields = ['applicant'] Here is my view for the search … -
How to set Password Protected Pages on WeasyPrint PDF Builder?
I want to set Password Protected Pages onWeasyPrint PDF Builder. I am generated PDF using Weasyprint in Django and I want password encrypted after download PDF File. ** Here is code for generate PDF file.** def build_pdf(request,html_content, header_html=None, footer_html=None): def get_page_body(boxes): for box in boxes: if box.element_tag == "body": return box return get_page_body(box.all_children()) def get_page_and_body(html, css): if html is None: return None html = weasyprint.HTML( string=html, base_url=getattr(settings, "WEASYPRINT_BASEURL", None), url_fetcher=django_url_fetcher, ) css += "@page { margin 0 !important; }" document = html.render(stylesheets=[weasyprint.CSS(string=css)]) document_page = document.pages[0] document_body = get_page_body(document_page._page_box.all_children()) return ( document_page, document_body.copy_with_children(document_body.all_children()), ) def preprocess_html(html, context): for key, value in context.items(): html = html.replace(f"{{{{ {key} }}}}", str(value)) return html document = weasyprint.HTML( string=html_content, base_url=request.build_absolute_uri(), # base_url=getattr(settings, "WEASYPRINT_BASEURL", None), url_fetcher=django_url_fetcher, ).render() return document.write_pdf() can anyone help me? -
Get user posts using Class-based views?
Creating a blog project, how do I get the specific user's posts using Class-based views? What I have so far works, but it's incomplete. I am able to sort any user posts, but if I try to get the current logged-in user's posts, this happens to my side navbar. Here's what I have so far views.py class UserIssueListView(ListView): model = Issue template_name = 'issues/user_issues.html' context_object_name = 'issues' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Issue.objects.filter(author=user).order_by('-date_posted') nav.html <div id="nav-menu"> <ul class="nav-menu-items"> <div id="navbar-toggle"> <a href="#" class="menu-bars" id="hide-menu"> <i class="fas fa-bars nav-icon"></i> </a> <a href="#"><h3 class="text-white">Bug Tracker</h3> </a> </div> <hr /> <div class="nav-section"> <li class="nav-text"><a href="{% url 'dashboard' %}"><i class="fas fa-home nav-icon"></i>Dashboard</a></li> <li class="nav-text"><a href="{% url 'issues-home' %}"><i class="fas fa-fire nav-icon"></i>Recent Issues</a></li> <li class="nav-text"><a href=""><i class="fab fa-youtube nav-icon"></i>My Projects</a></li> </div> <hr /> <div class="nav-section"> {% for issue in issues %} <li class="nav-text"><a href="{% url 'user-issues' issue.author.username %}"><i class="fas fa-play-circle nav-icon"></i>My Posts</a></li> {% endfor %} <li class="nav-text"><a href=""><i class="fas fa-history nav-icon"></i>User Profile</a></li> <!-- <li class="nav-text"><a href=""><i class="fas fa-clock nav-icon"></i>Subscriptions</a></li> --> </div> </ul> </div> I suspect it's because of the for loop, but I'm stuck on how to proceed. How do I get only the current logged-in user's posts? -
How to add field to Django queryset
I'm learning DRF and trying to make website, where users can leave reviews for some products and also rate (like or dislike) this reviews. So now I'm stuck in like system. For example I have these models: class Review(models.Model): author = models.ForeignKey(User) text = models.TextField() created_at = models.DateTimeField(auto_now_add=True) class Reaction(models.Model): author = models.ForeignKey(User) review = models.ForeignKey(Review, related_name='reactions') like = models.BooleanField() # True = like, False = dislike And I want to show list of posts with like and dislike counters and also somehow mark that logged user already liked or disliked a post. I made view to list posts with counters, but don't know how to include information about post was rated by user. class ListReviews(generics.ListAPIView): serializer_class = ProductReviewSerializer def get_queryset(self): product_slug = self.kwargs['product_slug'] queryset = Review.objects.filter(product__slug=product_slug).annotate( likes_count=Count('reactions', filter=Q(reactions__like=True)), dislikes_count=Count('reactions', filter=Q(reactions__like=False)), user_reaction=... ) return queryset Is it possible at all? Or it's better to just make another endpoint to get user reactions for current page? -
Django password change view
I am trying to implement password changing in my django app, with my own template and form. So i decided to create my own view function instead of using django's. The problem Im having is the change password page doesn't change the password. I can't figure out what my problem is and could really use some help, thanks. chgpwd.html template {%extends 'auth_base.html'%} {%load static%} {%block title%} CX Labs SOC LogIn {% endblock%} {%block content%} <div class="wrapper" style="max-width:450px"> {%if form.errors %} <p style="text-align:center; margin-bottom:30px; color:red;">something went wrong</p> {%endif%} <div class="logo"> <img src="{%static 'website/cxlabs.jpg'%}" alt=""> </div> <div class="text-center mt-4 name"> CXLabs SOC <br/> Password Change</div> <form method="post" class="p-3 mt-3"> <div class="form-field d-flex align-items-center"> <span class="far fa-user"></span> {{form.oldPwd}} </div> <div class="form-field d-flex align-items-center"> <span class="far fa-user"></span> {{form.newPwd1}} </div> <div class="form-field d-flex align-items-center"> <span class="fas fa-key"></span> {{form.newPwd2}} </div> <button type="submit" class="btn mt-3">Change Password</button> {%csrf_token%} </form> </div> {%endblock%} Urls.py import django from django.contrib import admin from django.contrib.auth import views as av from django.urls import path, include from authentication.forms import CustomAuthForm, CustomPwdChgForm from website import views from authentication import views as authv urlpatterns = [ path('logout/', av.LogoutView.as_view(template_name='registration/logout.html', next_page=None), name='logout'), path('chgpwd/', authv.changepwview, name='chgpwd'), path('sign/', include('sign.urls')), path('download/<int:id>', views.zip_download, name='zipDL') ] views.py from django.shortcuts import render, redirect from django.contrib.auth … -
Django "duplicate key value violates unique constraint" because of the save method
I am trying to update an existing instance from a model in Django admin interface but I'm getting django.db.utils.IntegrityError: duplicate key value violates unique constraint because of the save method. According to the documentation, the save method should not have any problems UPDATING the model, but it seems like the primary key is set to a value that evaluates as False. https://docs.djangoproject.com/en/4.0/ref/models/instances/#how-django-knows-to-update-vs-insert . Django abstracts the need to use INSERT or UPDATE SQL statements. Specifically, when you call save() and the object’s primary key attribute does not define a default, Django follows this algorithm: If the object’s primary key attribute is set to a value that evaluates to True (i.e., a value other than None or the empty string), Django executes an UPDATE. If the object’s primary key attribute is not set or if the UPDATE didn’t update anything (e.g. if primary key is set to a value that doesn’t exist in the database), Django executes an INSERT. Now this is my model and the save method: class Examene(models.Model): saptamani = models.IntegerField(default=3, validators=[MinValueValidator(1), MaxValueValidator(5)]) zile = models.IntegerField(null=False, blank=True) profesor = models.ForeignKey(Materii_profesor, on_delete=models.CASCADE) materii = models.ManyToManyField(Materie) def save(self, *args, **kwargs): self.zile = (self.saptamani * 5) super(Examene, self).save(self, *args, **kwargs) I am …