Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The terminal gives me as error a path that I don't have in my code with Django
I'm working on Django, developing a site This gives me an error: Not Found: /plans/investment_per_plan_chart Not Found: /plans/active_running_plans I have searched with VSC but I can't find anything in my code that looks like this error. Please help me I'm lost -
Why is my Django FormModel is not submitted when I click submit button?
I am working on simple login and signup pages on Django. This is how they work: You create an account in the signup page. After the process is complete, it redirects you to the login page. However, when you click a button to submit information on the signup page, it is not submitted. Here are the codes: urls.py from django.urls import path, include from . import views urlpatterns = [ path('account/login', views.login_page, name='login'), path('account/signup', views.signup_page, name='signup') ] models.py from django.db import models class User(models.Model): username = models.CharField(max_length=30,) password = models.CharField(max_length=255) firstName = models.CharField(max_length=255) lastName = models.CharField(max_length=255) emailAddress = models.EmailField(max_length=255) def __str__(self): return self.username forms.py from .models import User from django.forms import ModelForm, TextInput, PasswordInput, EmailInput class UserForm(ModelForm): class Meta: model = User fields = ['username', 'password', 'firstName', 'lastName', 'emailAddress'] widgets = { 'username': TextInput(attrs={ 'class': 'signup_input', 'placeholder': 'Username' }), 'password': PasswordInput(attrs={ 'class': 'signup_input', 'placeholder': 'Password' }), 'firstName': TextInput(attrs={ 'class': 'signup_input', 'placeholder': 'First Name' }), 'lastName': TextInput(attrs={ 'class': 'signup_input', 'placeholder': 'Last Name' }), 'emailAddress': EmailInput(attrs={ 'class': 'signup_input', 'placeholder': 'Email Address' }) } labels = { 'username': '', 'password': '', 'firstName': '', 'lastName': '', 'emailAddress': '' } views.py from django.shortcuts import render, redirect from .forms import UserForm def login_page(request): return render(request, 'Account/login_page.html') … -
Firebase Cloud Messaging not working for programmatically sent messages using Python
If I go into my firebase console and setup a campaign my end devices receive the notification just fine, but for messages to specific devices using the device's registration token, sent from django/python, I get no notification on my mobile devices. Not sure if this matters but my app is still in development, it is not in production, so if this matters please let me know. My frontend is flutter, here is the flutter code I am using to get the registration token and send it to the backend: Future<StreamedResponse> AddProductPut(context, pk, name, quantity, cost, selling, XFile? chosenImage) async { String id_token = await FirebaseAuth.instance.currentUser!.getIdToken(); late String? fcm_token; await FirebaseMessaging.instance.getToken().then((token) async { fcm_token = token!; }).catchError((e) { print(e); }); print(fcm_token); var url = backend + "/pm/createproduct/" + pk.toString() + "/"; var request = http.MultipartRequest('PUT', Uri.parse(url)); print("FCM TOKEN"); print(fcm_token); request.headers["Authorization"] = "Token " + id_token; request.fields["name"] = name; request.fields["quantity"] = quantity.toString(); request.fields["cost_price"] = cost.toString(); request.fields["selling_price"] = selling.toString(); request.fields["barcode"] = "11111"; request.fields["token"] = fcm_token!; request.files.add( await http.MultipartFile.fromPath( 'image', chosenImage!.path ) ); return await request.send(); } Here is the python code in my django serializer to send the notification message: registration_token = self.context['request'].data["token"], print(registration_token[0]) print(type(registration_token[0])) # See documentation on defining a message payload. … -
change text content (like, unlike) Django Like Button
I'm asked to work on a networking website that is like Twitter. I work with HTML,CSS, Javascript for the client-side and Django for the server-side. I created a model that saves the likes by saving the liked post and the user that liked the post. I want to make a like button in the HTML page that has its inner text(like) if the user hasn't liked the post and unlike if the user liked the button by using arrays in models.py: class likes(models.Model): liked_post = models.ForeignKey("posts", on_delete=models.CASCADE) like_user = models.ForeignKey("User", on_delete=models.CASCADE) in views.py: def index(request): allposts = posts.objects.all() m = ['empty'] aa = [0] for post in allposts: postid = post.id print(postid) aa.append(int(postid)) liked__post = posts.objects.get(id = postid).id if likes.objects.filter(like_user = request.user, liked_post = liked__post).exists(): f = 'unlike' m.append(f) c = 'liked__btn' else: t = 'like' m.append(t) c = 'like__btn' print('like') print(m[0]) print(aa) return render(request, "network/index.html",{"allposts": allposts, 'm':m, 'c':c, 'aa':aa}) @csrf_exempt def like(request, post_id): liked__post = posts.objects.get(id = post_id) if request.method == 'PUT': print('we\'ve hit put') data = json.loads(request.body) if data.get('like') is not None: print('in like') # Note: [User Obj Itself] # follower = request.user (is: <User Obj>) # following = x (is: <User Obj>) likes.objects.create(liked_post=liked__post, like_user=request.user) elif data.get('unlike') is … -
Django block user from modifying a form input
I have a instance Form that is showing the user his Profile Data, the user can update some of his profile settings by modifying the input and clicking the update button. But I don't want the user to be allowed to change all the profile data, such as the subscriptions Charfields. How can I do that? models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) telegramusername = models.CharField(max_length=50, default=None) subscription = models.CharField(max_length=50, default=None) numberofaccount = models.CharField(max_length=50, default=None) def __str__(self): return self.telegramusername forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile labels = { "telegramusername": "Telegram Username", "subscription": "Subscription Plan", "numberofaccount": "Number of MT5 Account" } fields = ["telegramusername", "subscription", "numberofaccount"] views.py def dashboard(request): profile_data = Profile.objects.get(user=request.user) profile_form = ProfileForm(request.POST or None, instance=profile_data) if profile_form.is_valid(): print("worked") profile_form.save() context = { 'profile_form': profile_form } return render(request, "main/dashboard.html", context) -
Choice_set and id members are unknown
I'm getting started with django, I've been following the official tutorial and I've run into an issue. I have this block of code: def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST["choice"]) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render( request, "polls/detail.html", { "question": question, "error_message": "You didn't select a choice.", }, ) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse("polls:results", args=(question.id,))) The code works perfectly fine, however, for some reason VS Code highlights the ID and CHOICE_SET attributes. Here's my models.py: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField("date published") def __str__(self) -> str: return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self) -> str: return self.choice_text I suppose that there's an issue with VS Code because as I said the code works just fine and I can run it. I just really wanna remove the red highlighting and fix it. -
Debugger does not start in VSCode for Django
I'm trying to debug my Django project, but whenever I hit the play button on the run and debug window in VSCode, it thinks for a second, and then completely stops. My project runs completely fine when I run it with the "runserver" command. I've tried restarting VSCode, and restarting my computer. here is my launch.json file { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}\\manage.py", "args": [ "runserver", "9000" ], "django": true } ] } -
why does the image not appear in the template when I run Django
List item Tried several ways in all available ways to show the image in the template, but it did not appear, but in django - admin add and show List item Tried several ways in all available ways to show the image in the template, but it did not appear, but in django - admin add and show modles.py class Delivery(models.Model): # order = models.ForeignKey(Order, on_delete=models.CASCADE) ddesign = models.CharField(max_length=50,null=True) buyer = models.ForeignKey(Buyer, on_delete=models.CASCADE, null=True) dcolor = models.CharField(max_length=50,null=True) courier_name = models.CharField(max_length=120) frist_name = models.CharField(max_length=120,null=True) scand_name = models.CharField(max_length=120,null=True) therd_name = models.CharField(max_length=120,null=True) ford_name = models.CharField(max_length=120,null=True) fifth_name = models.CharField(max_length=120,null=True) dimg = models.ImageField(null=True, blank=True ,upload_to='media/') created_date = models.DateField(auto_now_add=True) def __str__(self): return self.ddesign forms.py > class DeliveryForm(forms.ModelForm): > class Meta: > model = Delivery > fields = '__all__' > > widgets = { > > 'ddesign': forms.TextInput(attrs={ > 'class': 'form-control', 'id': 'ddesign' > }), > 'buyer': forms.Select(attrs={ > 'class': 'form-control', 'id': 'buyer' > }), > 'dcolor': forms.TextInput(attrs={ > 'class': 'form-control', 'id': 'dcolor' > }), > 'courier_name': forms.TextInput(attrs={ > 'class': 'form-control', 'id': 'courier_name' > }), > 'frist_name': forms.TextInput(attrs={ > 'class': 'form-control', 'id': 'frist_name' > }), > 'scand_name': forms.TextInput(attrs={ > 'class': 'form-control', 'id': 'scand_name' > }), > 'therd_name': forms.TextInput(attrs={ > 'class': 'form-control', 'id': 'therd_name' > }), > 'ford_name': … -
CSS Is Not Rendering Correctly
So my project is running on a django backend with React for the frontend. The issue I am having is that my react components are rendering, but they are not structured correctly (margins messed up, no borders, components overlapping) even though my CSS is correct. I think the cause is in the base.html in the django portion of the project, as webpack is bundling through that. I tried adding link references to no avail. Note* I am importing Dashboard as a const into the UserApp class which, while I don't think is the cause of the issue, could be the culprit, not sure. How its supposed to look: https://postimg.cc/TKKtL00S How it looks: https://postimg.cc/qhwsZ6Qy Base.html: {% block css %} {% compress css %} <!-- <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> --> <link rel="stylesheet" href="{% static 'css/font-awesome.css' %}"> <link rel="stylesheet" href="{% static 'css/LineIcons.css' %}"> <link rel="stylesheet" href="{% static 'css/materialdesignicons.min.css' %}"> <link rel="stylesheet" href="{% static 'css/fullcalendar.css' %}"> <link rel="stylesheet" href="{% static 'css/fullcalendar.css' %}"> <link rel="stylesheet" href="{% static 'css/main.css' %}"> <!-- <link rel="stylesheet" href="../../../rsm-app-react/Dashboard.css"> --> {% endcompress %} {% compress css %} <!-- <link href="{% static 'css/app.css' %}" rel="stylesheet"> --> {% endcompress %} {% endblock %} {% block css_extra %} <link rel="stylesheet" href="https://cdn.syncfusion.com/ej2/material.css"> {% … -
django REST framework - allow only list of IP addresses to access?
I am trying to figure out the correct way to limit access to an API endpoint using IP address. I went through the docs, blocking is mentioned but limiting the call to API endpoint is not. What is the correct way to do this? -
How to see auto generated Primary Key of a model and to use it like FK in Django?
How I know that models in Django have by default auto incremented id, but I want to see it in Django Administration and to take this id in order to put it in other model like FK class Customer(models.Model): customer_id = #TO BE auto incremented PRIMARY KEY user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=60) def __str__(self): return self.name class Wallet(models.Model): customer_id = #to take customer_id (by default django generate it, but how to introduce here like fk) usd = models.FloatField(null=True) -
Output is not rendered on Django template for the same model whose output is rendered on another template
I am really new to Django and I am building a website while learning it. As per requirements, I have to show some news articles on both the home page and on another page that I navigate from the navbar. I have shown the articles list and individual details with the loop in my template files. Problem is, although I have written the for loop for rendering the news article on the home page, nothing is showing up. Following are my models.py, views.py, app/urls.py, and project/urls.py files : #models.py from django.contrib.auth.models import User from django.db import models from django.urls import reverse from django.utils import timezone from django.utils.translation import gettext_lazy as _ from taggit.managers import TaggableManager from ckeditor.fields import RichTextField class News(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) news_title = models.CharField(max_length=250) # slug = models.SlugField(max_length=250, unique_for_date='nw_publish', unique=True, null=True) slug = models.SlugField(max_length=300, unique_for_date='nw_publish') news_author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='news_posts') news_body = RichTextField() image_header = models.ImageField(upload_to='featured_image/%Y/%m/%d/', null=True, blank=True) nw_publish = models.DateTimeField(default=timezone.now) nw_status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') news_tags = TaggableManager() class Meta: ordering = ('nw_publish',) def __str__(self): return self.news_title #views.py from django.views import generic from django.views.generic import ListView, DetailView from django.http import Http404 from .models import Post, Report, News, Member, Project class NewsListView(ListView): … -
return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: FOREIGN KEY constraint failed
I have two models. What I tried doing was creating an instance of School and assigning a user to the created school at the time of creating a superuser. Below are the models. It returns an error part of which is shown below. Please someone help me out on what best to do. OR Is there any other way other than what I'm trying to do here that can help?? class School(models.Model): name = models.CharField(max_length=100,null=True,blank=True,unique=True) subscribed = models.BooleanField(default=True) invoice_date = models.DateField(null=True, blank=True) installed = models.BooleanField(default=False) def __str__(self): return str(self.name) def create_school(self): self.school.id = 1 self.school.name = "default" self.school.subscribed = True self.school.installed = False return self.school class CustomUser(AbstractUser): school = models.ForeignKey(School, on_delete=models.CASCADE, null=True, blank=True, default=1) is_librarian = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) phone = models.IntegerField(null=True,blank=True) def __str__(self): return self.username The error return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\FR GULIK\AppData\Roaming\Python\Python310\site-packages\django\db\backends\utils.py", line 75, in _execut e_with_wrappers return executor(sql, params, many, context) File "C:\Users\FR GULIK\AppData\Roaming\Python\Python310\site-packages\django\db\backends\utils.py", line 79, in _execut e with self.db.wrap_database_errors: File "C:\Users\FR GULIK\AppData\Roaming\Python\Python310\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\FR GULIK\AppData\Roaming\Python\Python310\site-packages\django\db\backends\utils.py", line 84, in _execut e return self.cursor.execute(sql, params) File "C:\Users\FR GULIK\AppData\Roaming\Python\Python310\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: FOREIGN KEY constraint failed -
request django token msg: 'set' object has no attribute 'items'
I'm trying to get a token from the Django authentication. But I'm getting following error: Exception type: <class 'AttributeError'> msg: 'set' object has no attribute 'items' My test code snippet looks like this: import os import requests import json from dotenv import load_dotenv load_dotenv() BASE_DEV_URL = "http://127.0.0.1:4000" def login(url=(BASE_DEV_URL + "/api/user/token")): headers = { 'accept: application/json', 'accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Content-Type:' 'application/x-www-form-urlencoded', } try: payload = {"email": os.getenv('TEST_USER_NAME'), "password": os.getenv('TEST_USER_PASSWORD')} print(payload) res = requests.post(url, data=json.dumps(payload), headers=headers) print(f'####### {type(res)}') except Exception as e: return f'Exception type: {type(e)} msg: {e}' return res response = login() print(response) However, when I test it with swagger with curl command it works fine curl looks like this curl -X 'POST' \ 'http://127.0.0.1:4000/api/user/token/' \ -H 'accept: application/json' \ -H 'Content-Type: application/x-www-form-urlencoded' \ -H 'X-CSRFTOKEN: T7wW385wMiYDERJU2yWvqGorrbKjtb9zhWqlAkAlE30QKgP7DoQMbc7MnQT3UAti' \ -d 'email=test%40example.com&password=123XVW174' Any idea how to make it work. I'm not sure, but it may because by serialized. I worked with request library a lot and never encountered such error. Will be grateful for any advice which could solve it. -
how to make primay or unique three field in django models?
I have the four models in my Django models.py ( User, Exam, Questions, Answers ) the Answer model has four fields ( user, exam, question, answer) after creating an exam and creating questions for that, the users come to take an exam I want to store the user's answers in the Answer model, therefore, I specify which user is taking which exam and answering which question, at the end I save the user's answers in the last field ( the 'answer' field in Answer modle ) but I want this user only once can answer this question in this exam, so I want to make these fields ( user, exam, question ) primary in the Answer model that my Answer model: class Answer(models.Model): exam = models.ForeignKey(Exam, on_delete=models.CASCADE, default=None) user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.CharField(max_length=8) I don't know how to do this action to primary three field actually, there is no matter whether the two or one fields of these three fields are similar, I just want to prevent storing records that user, exam, and question fields are already stored for example, I have this record in my database: user:1, exam:52, question:38, answer: "option_a" when I … -
Django model reference when using AbstractBaseUser model
I 'm following a tutorial of how to use AbstractBaseUser model in Django project. Now I would like to go one step further by creating other models for example address_book and product. When using defaulter user model, we put like this: class User(models.Model): .... class AddressBook(models.Model): .... class Product(models.Model): .... Now when I use like class MyUser(AbstractBaseUser): Which reference should I use in the AddressBook and Product class? (The user in the Address book is a foreign key from Class MyUser). class AddressBook(AbstractBaseUser) and class Product(AbstractBaseUser) or class AddressBook(models.Model) and class Product (models.model)? Thanks for your help in advance! -
How to do a search in Django correctly?
I'm quite new to Django. And I have a problem with the search implementation. I looked through quite a lot of material and tried many options, but nothing came out. I want to implement a search so that it searches for the product model. Can you help me with this problem? views.py from django.shortcuts import render from .filters import * from .models import index from .forms import * # Create your views here. def indexViews(request): search = request.GET['search'] indexAll = index.objects.all if search == None: posts = index.objects.filter(model__in=search) else: posts = index.objects.all() index_filter = IndexFilter(request.GET, queryset=all) context = { 'index_filters': index_filter, 'all': indexAll } return render(request, 'index.html', context) models.py from django.db import models # Create your models here. class index(models.Model): BRAND = [ ('apple', 'apple'), ('samsung', 'samsung'), ('huawei', 'huawei'), ] brand = models.CharField(max_length=20, choices=BRAND) model = models.CharField(max_length=50, default='None') price = models.FloatField(max_length=10, default=0.0) image = models.URLField() class Meta: verbose_name = 'Продукт' verbose_name_plural = 'Продукты' def __str__(self): return self.model urls.py from django.urls import path from .views import * urlpatterns = [ path('', indexViews, name='index') ] index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="get" action="{% url 'index' %}"> {{ index_filters.form }} <input type="search" placeholder="Поиск" … -
Google Cloud AppEngine and Django: how should I set the domain name for have it work?
I've deployed a Django project on Google Cloud standard AppEngine, My Domain Name is registered in Google Domains which confirms that it already points to my project when I try to customize my domains. On the Web, I've access my project under its project name: https://mooveup-9645.oa.r.appspot.com However when I try https://my-domain.fr the web site cannot be accessed. My Question is: Where should I add my domain name ? if APPENGINE_URL: # Ensure a scheme is present in the URL before it's processed. if not urlparse(APPENGINE_URL).scheme: APPENGINE_URL = f"https://{APPENGINE_URL}" ALLOWED_HOSTS = [urlparse(APPENGINE_URL).netloc, "www.my-domain.fr", "my-domain.fr"] Is this the appropriate solution in Django settings or is there another configuration step with GCP? -
having ImportError that i did not import
Please someone should help me out. I did not import ugettext_lazy from anywhere in my project am using django 4.2.1. i just install django-messages from then i cannot proceed with my project. this error keep showing an am stock in one place. I check all my import to see where the ugettext_lazy is comming from but i could not trace it. i even downgrade django 4 to django 3 but i was still having some import error in django 3. i upgrade it again to django 4. please help me out. thanks this is my views.py imports # from http.client import HTTPResponse # from django.contrib.auth import login from django.shortcuts import redirect, render from .forms import CustomUserCreationForm, PostForm, CommentForm, NovenaCommentForm from . models import About_us, My_blog, Like, Comment, Slider, Prayers, Description, Novena, NovenaComment from django.urls import reverse from django.http import HttpResponseRedirect from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from . like import new_likes, authmessage from django.contrib import messages from django.http import HttpResponse from django.urls import reverse_lazy from django.contrib.auth.models import User, auth from django.contrib.auth import authenticate # from django.contrib import messages from django.views.generic import ListView, DetailView, DeleteView from django.contrib.auth.decorators import login_required, user_passes_test, permission_required from authentications.message import infor this is admin imports from django.contrib … -
convert Queryset to array
Have been trying to work on this for some sometime maybe my mind is rusty so i am seeking another mind for help. below is a query set is get from the Database for equipment [0] that are used per month1. 0 01 1 () Name: 0, dtype: object 0 02 1 () Name: 1, dtype: object 0 03 1 () Name: 2, dtype: object 0 04 1 () Name: 3, dtype: object 0 05 1 ({'id': 1, 'qty': 1}, {'id': 2, 'qty': 2}) Name: 4, dtype: object 0 06 1 () Name: 5, dtype: object 0 07 1 () Name: 6, dtype: object 0 08 1 () Name: 7, dtype: object 0 09 1 ({'id': 2, 'qty': 1}) Name: 8, dtype: object 0 10 1 () Name: 9, dtype: object 0 11 1 ({'id': 1, 'qty': 1}) Name: 10, dtype: object 0 12 1 () Name: 11, dtype: object I would want to convert this Queryset to a PD dataframe to look like the below table where the table is filled with the qty coming from the query set with the equipment ID in each month: Dataframe required would appreciate your input! -
How to get a logged in user profile in context_processors.py Django?
I have a context_processors.py to display extra info at base.html. I need to get a request.user to get his profile and show all his user's posts in news.html. When I do profile = Profile.objects.filter(user=request.user.id) Django shows that no user matches to a given profile. How do I fix it ? context_processors.py from users.models import Profile def notification_to_base(request): counter = 0 profile = Profile.objects.filter().first() # I'm getting Admin_profile, but I need to get a logged in user profile subscribing = profile.subscribing.filter() # TestUser, TestUser_two for following in subscribing: posts = following.post_set.filter(is_checked=False) # post № 1, post № 2 for post in posts: counter += 1 return {'answers': answers, 'counter': counter} -
Join two models and group with SUM in Django but some fields are not display
I have two model name ProductDetails and InventorySummary. I want to join this two model and wants to group with product name and SUM product quantity. The quantity should be multiplication with product price. My models are given bellow: class ProductDetails(models.Model): id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=100, unique=True) purchase_price = models.DecimalField(max_digits=7, decimal_places=2) dealer_price = models.DecimalField(max_digits=7, decimal_places=2) retail_price = models.DecimalField(max_digits=7, decimal_places=2) remarks = models.CharField(max_length=255, blank=True) def __str__(self): return self.product_name class InventorySummary(models.Model): id = models.AutoField(primary_key=True) date = models.DateField(default=date.today) product_name = models.ForeignKey(ProductDetails, on_delete=models.CASCADE) quantity = models.IntegerField() def __str__(self): return str(self.product_name) My views are given bellow which are working good: def stockPrice(request): stock = ( InventorySummary.objects.annotate(total_amount=Sum(F("product_name__purchase_price") * F("quantity")))) return render(request, 'inventory_price.html', {'stock': stock}) But when I group then not working. Only total_amount working. product_name, purchase_price, and quantity not display def stockPrice(request): stock = ( InventorySummary.objects.values("product_name__product_name") .order_by("product_name__product_name") .annotate(total_amount=Sum(F("product_name__purchase_price") * F("quantity")))) return render(request, 'inventory_price.html', {'stock': stock}) -
DRF / POST view for two tables connected by foreign keys
How to write POST view for two tables that are mapped by foreignkey? here are my models.. class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE,null=True, blank=True, editable=False) title = models.CharField(max_length=255, null=False) description = models.TextField(null=True, blank=True) created_date = models.DateTimeField(auto_now=True) enable = models.BooleanField(default=True) class PostImages(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) images = models.ImageField(null=True, blank=True) serializer: class UserPostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ['author','title','description'] I made view but it doesn't do anything with PostImages table.. I want it to create post with images.. @api_view(['POST']) @permission_classes([IsAuthenticated]) def PostUpload(request): data = request.data user = request.user if request.method == 'POST': serializer = UserPostSerializer(data=data, many=False) if serializer.is_valid(): serializer.save(author=user) return Response(serializer.data) return Response(serializer.errors) -
How to add new plugins like HtmlEmbed in django-ckeditor-5?
I am using django-ckeditor-5 https://github.com/hvlads/django-ckeditor-5 for my project. But I am not able to add new plugins like HtmlEmbed. Can anyone please help me how can we add new plugins in django-ckeditor-5? -
Create dropdown menu for login account
I would like to create a dropdown menu from the logged-in user account. currently, the top-right button in the navigation bar is either "Login" or "Logout" based on if user is logged in. I would hope to create a dropdown menu when user is logged in, which contains options such as account and logout. The desired examples look like below: The login dropdown menu can contain two options (Account and Logout). how to achieve this, without using boostrap external stylesheet? Current HTML <div class="nav"> <div class="login-container"> {% if user.is_authenticated %} <form class="navbar-form navbar-right" action="{% url 'logout' %}" method="get"> <span>Welcome, {{ user }}.&nbsp;&nbsp;</span> <button type="submit">logout</button> {% else %} <form class="navbar-form navbar-right" action="{% url 'login' %}" method="get"> <span>Welcome, {{ user }}.&nbsp;&nbsp;</span> <button type="submit">login</button> {% endif %} </form> </div> </div>