Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to delete data from database with a button using only DJANGO python, java script, and HTML?
I am working on a django project where my database gets populated from a post call, and for quality of life, I want to be able to clear the database at the click of a button. If it's possible, I'd like to only use python, javascript, and HTML. I've done some searching on here and haven't found any question like this so far with an answer. Here's a link to a similar question with no answer. There is a question that is similar to mine, but OP is using PHP, jquery, and SQL, which isn't ideal for me. I haven't attempted any code because I don't know where to start. If anyone has knowledge about this kind of thing, it would be much appreciated if you gave me a starting place. -
How do I retrieve file from server with graphene and Django?
How do I retrieve file from server with graphene and Django? I found graphene-file-upload, but it seems to take care of only uploading client's files to the server -
createsuperuser gives KeyError after implementing custom user
Hey I'm fairly new to Django and I'm trying to setup a pretty basic rest API. I am using djoser to handle authentication. However I want to use a custom user model. Where 1. the unique field is the email (instead of username) and 2. it is has one extra field. I tried to follow these two guides, https://testdriven.io/blog/django-custom-user-model/ (To use email instead of username) https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#abstractuser (To extend the usermodel) I create the model like so, class MyUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) DIET_CHOICES = ( ('vegan', 'Vegan'), ('vegetarian', 'Vegetarian'), ('meat', 'Meat') ) diet = models.CharField(max_length=10, choices=DIET_CHOICES) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [diet] objects = CustomUserManager() def __str__(self): return self.email Using the CustomUserManager() as shown in https://testdriven.io/blog/django-custom-user-model/. I have also registered the user in AUTH_USER_MODEL. Looking at the migration file I get what I expect. But after migrating when I then try to run createsuperuser, it instantly results in the following error Traceback (most recent call last): File "/home/frederik/Documents/andet/madklubTests/2madklubDjango/venv/lib/python3.9/site-packages/django/db/models/options.py", line 672, in get_field return self.fields_map[field_name] KeyError: <django.db.models.fields.CharField: diet> During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/frederik/Documents/andet/madklubTests/2madklubDjango/manage.py", line 22, in <module> main() File "/home/frederik/Documents/andet/madklubTests/2madklubDjango/manage.py", line 18, in main execute_from_command_line(sys.argv) File … -
everytime i do some activity on my website i get this error :- Wallpaper.models.Wallpaper.DoesNotExist: Wallpaper matching query does not exist
Views.py def home(request): WAllPAPER_PER_PAGE = 4 WALL = Wallpaper.objects.all() from django.core.paginator import EmptyPage, Paginator from django.db.models import Q qd = request.GET.copy() qd.pop('page', None) querystring = qd.urlencode() #link formatting for ordering ordering =request.GET.get('ordering', "") #link formatting for sorting search = request.GET.get('search', "") if search: wallpapers = Wallpaper.objects.filter(Q(name__icontains=search) | Q(category__category_name__icontains=search) | Q(tags__tag__icontains=search)).distinct() WALL = None else: wallpapers = Wallpaper.objects.all() if ordering: wallpapers = wallpapers.order_by(ordering) page = request.GET.get('page', 1) wallpaper_paginator = Paginator(wallpapers, WAllPAPER_PER_PAGE) try: wallpapers = wallpaper_paginator.page(page) except EmptyPage: wallpapers = wallpaper_paginator.page(wallpaper_paginator.num_pages) except: wallpapers = wallpaper_paginator.page(WAllPAPER_PER_PAGE) context = {'querystring': querystring, "wallpapers": wallpapers, 'page_obj': wallpapers, 'is_paginated': True, 'paginator': wallpaper_paginator, 'WALL': WALL} return render(request, "Wallpaper/Home.html", context) def All_category(request): Cat = Category.objects.all() context = {'Cat': Cat } return render(request, "Wallpaper/ALL_Category.html", context ) def category(request, Category_name): cat = Category.objects.get(category_name=Category_name) wallpapers = Wallpaper.objects.filter(category__category_name=Category_name) context = {'cat':cat, 'wallpapers': wallpapers} return render(request,'Wallpaper/Category.html', context) def download(request, wallpaper_name): wallpaper = Wallpaper.objects.get(name=wallpaper_name) similar_wallpapers = wallpaper.tags.similar_objects() context = {'wallpaper': wallpaper, 'similar_wallpapers': similar_wallpapers} return render(request, 'Wallpaper/download.html', context) error C:\Users\Atharva thaware\Desktop\aman\projects\Ongoing\WallpaperTown\WallpaperTown\Wallpaper\views.py:30: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <class 'Wallpaper.models. Wallpaper'> QuerySet. wallpaper_paginator = Paginator(wallpapers, WAllPAPER_PER_PAGE) [19/Jul/2022 22:29:39] "GET / HTTP/1.1" 200 10744 [19/Jul/2022 22:29:39] "GET /media/Wallpaper/Images/wp4589844-inosuke-hashibira-wallpapers.jpg HTTP/1.1" 304 0 [19/Jul/2022 22:29:39] "GET /media/Wallpaper/Images/wp2162463-shoto-todoroki-wallpapers.png HTTP/1.1" 304 0 [19/Jul/2022 22:29:39] "GET /media/Wallpaper/Images/wp2490700-haikyu-2018-wallpapers.jpg HTTP/1.1" 304 … -
ValueError in django project
I am getting the following error when running my code: ValueError at /company/3 The view company.views.dynamic_company_number didn't return an HttpResponse object. It download my project -
Django @property and setter for models field
I'm trying to create a field that should be updated by time and use getter and setter for it. Below is my code that should work but something went wrong, could you help me, what have I missed? How to add this field to the admin pannel (the result of setter)? _status = models.CharField(max_length=15, choices=status_choice, default=COMING_SOON) time_start = models.DateTimeField() time_end = models.DateTimeField() @property def status(self): return self._status @status.setter def status(self, value): if value == Lessons.COMING_SOON and self.time_end > datetime.now() > self.time_start: self._status = Lessons.IN_PROGRESS elif value == Lessons.IN_PROGRESS and self.time_end < datetime.now(): self._status = Lessons.DONE I have tried to check if it works by the manual changing value in ./manage.py shell but haven't result. Seems like @property doesn't work. -
TypeError: Failed to execute 'fetch' on 'Window': Invalid name while fetching token of jwt to authorize
trying to create a E-commerce website using django, django RestAPI & React! i'm using Rest framework simple jwt for authorization & created a view of ' MyTokenObtainPairView' to retreat token where the user data will be stored. everything is fine but i can't fetch the token from the front end after logging in & it shows me the error. what am i doing wrong & how to fix it?? #Settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=90), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } views: from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) # Add custom claims token['username'] = user.username # ... return token class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer @api_view(['GET','POST']) def getRoutes(request): routes = [ '/api/token', '/api/refresh', ] return Response(routes) Urls.py: from . import views from .views import * from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) urlpatterns = [ … -
Generate Table Columns automatically on Django with view
I'm using django and i'm creating a table from the tutorial data. As i was building my .html i easily got a loop to write the data from my choice instance, but i can't get the same thing to work for the column names. I saw here how to get the model fields but i can't get a loop to do write them for me. table.html {% extends 'base.html'%} {% block content%} <div class="container"> <div class="row"> <p><h3 class="text-primary"> Python Django DataTables </h3></p> <hr style="border-top:1px solid #000; clear:both;" /> <table id = "myTable" class ="table table-bordered"> <thead class = "alert-warning"> <tr> <!-- i would like not to have to write those one by one for future projects --> <th> Choice </th> <th> Votes </th> </tr> </thead> <tbody> <!-- this is the kind of loop I wanted for the columns--> {% for item in qs %} <tr> <td contenteditable='true'>{{item.choice_text}}</td> <td>{{item.votes}}</td> </tr> {% endfor %} </tbody> </table> {% endblock content%} views.py class ChoiceTableView(TemplateView): model = Question template_name = 'polls/table.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["qs"] = Choice.objects.all() return context models.py 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): return self.choice_text -
with custom user i have not the group form in admin django
I created a custom user, it works well, but I notice that in the django admin, if I create a new user, I don't have access to the form that manages the groups. If I use a standard user system, when you create a user, in the admin, you have access to the management of groups and permissions. On the other hand in my project group and user are not linked my models.py from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, email, password): if not email: raise ValueError('Vous devez entrer une adresse email.') email = self.normalize_email(email) user = self.model(email=email) user.set_password(password) user.save() return user def create_superuser(self, email, password): user = self.create_user(email=email, password=password) user.is_staff = True user.is_admin = True user.save() return user class CustomUser(AbstractBaseUser): email = models.EmailField( max_length=255, unique=True, blank=False ) nom = models.CharField(max_length=50, blank=False, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = "email" def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True def __str__(self): return self.email in the views.py from django.contrib.auth import authenticate from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth import login as log_user from django.contrib.auth import logout as logout_user from accounts.forms import … -
Django Allauth not included in URL Conf through template links but URL is functional
I am new to using AllAuth and somewhat new to Django. I am developing a site and wanted to overhaul the custom user authentication that I was using before. I have implemented AllAuth into an existing solution. Everything seems to be connecting, but the template links are not working and I get returned a 404 error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/url%20'account_login' Using the URLconf defined in QuoteTool.urls, Django tried these URL patterns, in this order: admin/ [name='home'] accounts/ form/ [name='entryForm'] form/success [name='success'] quotes/ [name='quotes'] The current path, url 'account_login', didn’t match any of these. For example in my Navbar ... {% if user.is_authenticated %} <div class="m-2"> <h6>Hello, {{ request.user.firstName }}!</h6> </div> <a class="btn btn-outline-secondary" href=" url 'account_logout' ">Logout</a> {% else %} <a class="btn btn-outline-secondary" href=" url 'account_login' ">Login</a> <a class="btn btn-primary ml-2 mr-2" href=" url 'account_signup' ">Sign Up</a> {% endif %} ... These links do not work! I am not understanding why not. Especially since if I manually type the URL "http://127.0.0.1:8000/accounts/login/" it returns and renders the proper page with my custom template. My url.py file is as follows from django.contrib import admin from django.urls import path, include from QuoteTool import views from accounts import … -
Django Project Permissions for Production
I’m struggling on how to properly set up my directory and file permissions for my Django apps on my Linux Server. I set the permissions on my Development Test machine to 755 for Directories and 644 for Files. However, I was unable to run pip from the Terminal in PyCharm until I increased the permissions for pip file. Are these the correct permissions for all folders/files in the Virtual Environment as well, especially the files in the Bin directory? Also, I have ownership of files set to a specific user I elevate privileges to perform certain ops. I am reading some people use root as owner of Django directory and files. Which is preferred in production environment? Any help would be greatly appreciated. -
Proper way to manage a list of form in Django
What is the best way to handle an array of forms in django? I am trying to create a custom permissions system and I have to do the form to create a role. The models involved are listed below: class CategoryPermissions(models.Model): upload = models.BooleanField(default=False) download = models.BooleanField(default=False) history = models.BooleanField(default=False) class Category(models.Model): name = models.CharField(max_length=250, unique=True) label = models.CharField(max_length=250) directory = models.CharField(max_length=250) class GroupPermissions(models.Model): role = models.ForeignKey('repository.Role',on_delete=models.RESTRICT) category = models.ForeignKey('repository.Category',on_delete=models.RESTRICT) category_permissions = models.OneToOneField("repository.CategoryPermissions",on_delete=models.RESTRICT) class Role(models.Model): name = models.CharField(max_length=250) For each Category (which are already created) I define a CategoryPermissions that contains the permissions and I link it to the Role with GroupPermissions. How do I create a multiple form that allows me to create GroupPermissions with related CategoryPermissions, maintaining the relationship between GroupPermissions, Category and Role? I tried with a CategoryPermissions formset, but when I extract it from request.POST I don't know which one I understand that it may be unclear so do not hesitate to ask for more explanations, I will try to do my best. -
a python script that binds a google table and postgresql
How to write a python script that can: Get data from the document using Google API made in [Google Sheets]. The data should be added to the database, in the same form as in the -source file, with the addition of the column "column_name." a. Need to create DB independently, DBMS based on PostgreSQL. The script runs constantly to ensure that the data is updated online (it is necessary to take into account that the rows in the Google Sheets table can be deleted, added and changed). And this script is wrapped in Django application I have made all the necessary API's and settings -
Unable to return user data properly in Django
I am following a tutorial and I got myself stuck. I've built the login page of the website and now I was just trying to display a dropdown in the Navbar, that displayed the user's name. Here is the code that is responsible for that to happen: {userInfo ? ( <NavDropdown title={userInfo.name} id="username"> <LinkContainer to="/profile"> <NavDropdown.Item>Profile</NavDropdown.Item> </LinkContainer> <NavDropdown.Item onClick={logoutHandler}> Logout </NavDropdown.Item> </NavDropdown> ) : ( <LinkContainer to="/login"> <Nav.Link> <i className="fas fa-user"></i>Login </Nav.Link> </LinkContainer> )} Trying to debug the issue I realized that 'userInfo' is just returning me the refresh and access token of the user, and basically userInfo.name does not exist. Here's the User action: import { USER_LOGIN_REQUEST, USER_LOGIN_SUCCESS, USER_LOGIN_FAIL, USER_LOGOUT, } from "../constants/userConstants"; import axios from "axios"; export const login = (email, password) => async (dispatch) => { try { dispatch({ type: USER_LOGIN_REQUEST, }); const config = { headers: { "Content-type": "application/json", }, }; const { data } = await axios.post( "/api/users/login/", { username: email, password: password }, config ); dispatch({ type: USER_LOGIN_SUCCESS, payload: data, }); localStorage.setItem("userInfo", JSON.stringify(data)); } catch (error) { dispatch({ type: USER_LOGIN_FAIL, payload: error.response && error.response.data.detail ? error.response.data.detail : error.message, }); } }; And the user views: from django.shortcuts import render from rest_framework.decorators import api_view, permission_classes … -
How to display data from Django manager's method in Django templates?
I'm implementing an app where a manager can control the products and their batches where he can activate or deactivate batches by selecting the,, so I'm trying to display a dropdown list to show all the available batches with their 'expiration status' and 'quantity availability status' and 'activation status'. What I did so far is that i have created a QuerySet and Manager classes in my Django model class, and I want to retrieve these classes and display them in my template. But the problem is that it didn't work, in my templates it displays nothing, and the select field doesn't show any choices. Here's what I did in models.py: class ExpirationStatus(models.TextChoices): VALID='VALID',_('Valid') ONE_MONTH= 'ONE_MONTH',_('One month or Less') THREE_MONTHS='THREE_MONTHS',_('Three Months Or Less') EXPIRED='EXPIRED',_('Expired') class BatchQuerySet(models.QuerySet): def annotate_expiration_status(self): one_month=date.today() - timedelta(days=30) three_months=date.today() - timedelta(days=90) today=date.today() return self.annotate(expiration_status= Case( When(expiry_date__lt=today,then=Value(ExpirationStatus.EXPIRED)), When(expiry_date__lte=one_month,then=Value(ExpirationStatus.ONE_MONTH)), When(expiry_date__lte=three_months, then=Value(ExpirationStatus.THREE_MONTHS)), When(expiry_date__gt=three_months, then=Value(ExpirationStatus.VALID)), )).order_by('arrival_date') class BatchManager(models.Manager): use_for_related_fields = True def annotate_expiration_status(self): return self.get_queryset().annotate_expiration_status() def get_queryset(self): return BatchQuerySet(model=self.model, using=self._db) class Batch(models.Model): class Status(models.TextChoices): ACTIVE = 'active', _('Active') INACTIVE = 'inactive', _('Inactive') product = models.ForeignKey(Product, on_delete=models.PROTECT, related_name='product_batch') expiry_date = models.DateField() quantity_bought = models.PositiveIntegerField() status=models.CharField(max_length=32, null=True, choices=Status.choices) arrival_date = models.DateField(auto_now_add=False) objects=BatchManager() def available_quantity(self): return self.quantity_bought-(self.issued_batches.aggregate(total_issued_quantity=Sum('issued_quantity')).get('total_issued_quantity') or 0) def __str__(self): return self.product.name + ' … -
Django login required message is not displayed
I was trying to flash some message when user tries to access user profile page without loging in. But it is not displaying on log in page. @login_required def profile(request): if request.user.is_authenticated: if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm( request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success( request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } else: # if not request.user.is_authenticated messages.info( request, f'Your account has been created! You are now able to log in.') return redirect('login') return render(request, 'users/profile.html', context) -
Groupby and Count doesn't include users that have no posts (OneToMany relationship between two models)
I have two models, User and Post, where each user can have many posts. class User(models.Model): first_name = models.CharField("First name", max_length=150) last_name = models.CharField("Last name", max_length=150) class Post(models.Model): created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") content = models.CharField(max_length=300) Now for a sample data like this: User id first_name last_name 1 Jon Skeet 2 Gordon Linoff 3 Another Soul Post user content 1 Jon #1 1 Jon #2 1 Jon #3 2 Gordon #1 2 Gordon #2 I'm trying to create an API that returns a response like this: [ { "first_name": "Jon", "last_name": "Skeet", "posts_count": "3", "recent_posts": [ { "content": "Jon #1", "created": "2022-07-22T07:48:12.299032Z" }, { "content": "Jon #2", "created": "2022-07-22T07:47:26.830772Z" }, { "content": "Jon #3", "created": "2022-07-22T07:02:31.654366Z" } ] }, { "first_name": "Gordon", "last_name": "Linoff", "posts_count": "2", "recent_posts": [ { "content": "Gordon #1", "created": "2022-07-22T09:59:36.965825Z" }, { "content": "Gordon #2", "created": "2022-07-22T09:59:18.544077Z" }, ] }, { "first_name": "Another", "last_name": "Soul", "posts_count": "0", "recent_posts": [] } ] So for each user, I want to include these info in the result: The count of their posts Their top three most recent posts Here's what I've done so far. I created two serializers, one for each model: class UserSerializer(serializers.ModelSerializer): posts_count = … -
Reverse for 'blogpost' with arguments '('',)' not found
Reverse for 'blogpost' with arguments '('',)' not found. 1 pattern(s) tried: ['blog/(?P[0-9]+)\Z'] I face this problem in every project. So please any devloper solve this problem my urls.py from django.urls import path from .import views urlpatterns = [ path('', views.index, name='Blog_home'), path('<int:pk>', views.blogpost, name='blogpost'), ] my views.py from django.shortcuts import render from blog.models import Post # Create your views here. def index(request): post = Post.objects.all() context = {'post':post} return render(request, 'blog/bloghome.html', context) def blogpost(request, pk): blog_post = Post.objects.get(id=pk) context = {'blog_post':blog_post} return render(request, 'blog/blogpost.html', context) my models.py from django.db import models # Create your models here. class Post(models.Model): post_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) content = models.TextField() author = models.CharField(max_length=50) date_and_time = models.DateTimeField(blank=True) def __str__(self): return self.title Template: bloghome.html {% extends 'basic.html' %} {% block title %} Blog {% endblock title %} {% block blogactive %} active {% endblock blogactive %} {% block style %} .overlay-image{ position: absolute; height: auto; width: 100%; background-position: center; background-size: cover; opacity: 0.5; } {% endblock style %} {% block body %} <div class="container"> {% for post in post %} <div class="row"> <div class="col-md-7 py-4"> <div class="row g-0 border rounded overflow-hidden flex-md-row shadow-sm h-md-250 position-relative"> <!-- <div class="col-auto m-auto img-fluid"> <img src="#"> </div> --> <div … -
How can I display movies and TVs side by side?
I want to display Movies and TV side by side with django_bootsrap. Movies left side TVs right side. But I don't know how display Movies left side TVs right side. I display Movies and TVs by django's for. Below html code. I'm not still CSS. <h1>TV Score_by</h1> <div class="row"> {% for m in movie %} <div class="card" style="width: 18rem;"> <img src="https://image.tmdb.org/t/p/w200{{ m.poster_path }}" class="card-img-top" alt="..."> <div class="card-body"> {% if not m.name %} <h5 class="card-title">{{ m.title }}</h5> {% else %} <h5 class="card-title">{{ m.name }}</h5> {% endif %} <p class="card-text">{{ m.overview }}</p> <a href="/movie/{{ m.id }}/" class="btn btn-primary">View Details</a> </div> </div> {% endfor %} </div> <h1>TV Score_by</h1> <div class="row"> {% for m in tv %} <div class="card" style="width: 18rem;"> <img src="https://image.tmdb.org/t/p/w200{{ m.poster_path }}" class="card-img-top" alt="..."> <div class="card-body"> {% if not m.name %} <h5 class="card-title">{{ m.title }}</h5> {% else %} <h5 class="card-title">{{ m.name }}</h5> {% endif %} <p class="card-text">{{ m.overview }}</p> <a href="/tv/{{ m.id }}/" class="btn btn-primary">View Details</a> </div> </div> {% endfor %} </div> -
django.core.exceptions.FieldError: Unknown field(s) (field_name) specified for ModelName
As stated in my title I am getting error: django.core.exceptions.FieldError: Unknown field(s) (total_price) specified for CERequest In admin panel everything works fine and it is displayed correctly but when I am trying to open html page with my form I get this error. Can you please let me know how to fix this error and how can I pass the total_price method to my form. models.py class CostRequest(models.Model): related_component = models.ForeignKey(CostCalculator, on_delete=models.CASCADE, default=1, blank=True) related_product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True, related_name='related_product_ce_request') number_of_units = models.IntegerField(default=0) @property def total_price(self): return self.related_component.rate.hourly_rate * self.number_of_units forms.py class CalculatorForm(forms.ModelForm): number_of_units = forms.IntegerField(min_value=0) class Meta: model = CERequest fields = ('related_product', 'related_component', 'number_of_units', 'total_price') # 'total_price here causes issues -
Creating a detailed plan for task execution (Android App Development)
My mentor has asked me to first prepare a very well detailed plan for task execution. My assigned task/project is to develop an android app using DjangoREST and React. The app will pull data from an API and notify users of events. How detailed is detailed and what are some of the things he expects to see in the document before he can authorize me to write a single line of code. I like the idea, its interesting but I am anxious to impress from the plan before he sees my pathetic code. Please help -
Django reply of comment function issue, have to reply all html form
It works when you enter a comment, but when i write reply of comment, there is an error that requires me to enter the form in all areas. I'm sorry I can't upload the code, so I'm taking a screenshot -
Manage User Data on Django HTML with passing data
I'm doing small example project by Django. I'm making a Blog. in views.py I could render index.html with posts by passing posts dictionary onto third argument of render function as below. def home(request): posts = post.objects.all() return render(request, 'index.html', {'posts':posts}) By doing this, I could use posts data on HTML as below {% for post in posts %} <a href="{% url 'detail' post.id %}"> <h3>{{ post.title }}</h3> <h4>{{ post.id }}</h4> </a> <p>{{ post.date }}</p> However, when my instructor taught me how to implement login/logout function, I discovered he didn't pass the user data but he could manage 'user' data on HTML as below {% if user.is_authenticated %} {{ user.username }}님 <a href="{% url 'logout' %}">Logout</a> {% else %} <a href="{% url 'login' %}">Login</a> {% endif %} def login(request): if request.method=='POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(request, username=username, password=password) if user is not None: auth.login(request, user) return redirect('home') else: return render(request, 'login.html') else: return render(request, 'login.html') How is if user_is_authenticated could be rendered successfully on HTML without passing 'user' data on views.py? -
what are depended package for install WeasyPrint in dockerfile?
I install WeasyPrint and config it for views.py ,urls.py,admin.py and my template. when i want convert html page to pdf , i have this error : (process:7): Pango-CRITICAL **: 13:27:29.635: pango_font_get_hb_font: assertion 'PANGO_IS_FONT (font)' failed base_shop_web_1 exited with code 245 my Dockerfile is : FROM python:alpine ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN mkdir /code ADD requirements.txt /code/ WORKDIR /code RUN apk add --update --no-cache curl jq py3-configobj py3-pip py3-setuptools python3 python3-dev RUN apk add cairo-dev pango-dev gdk-pixbuf-dev py-lxml shared-mime-info openjpeg-dev freetype-dev libpng-dev gettext libxml2-dev libxslt-dev RUN apk add make automake libffi-dev gcc linux-headers g++ py3-brotli musl-dev postgresql-dev zlib-dev jpeg-dev RUN pip3 install -r requirements.txt EXPOSE 8000 COPY . /code/ what things i shoud to add dockerfile ? -
Django - Form not showing in template
I'm trying to make a login with a bootstrap dropdown. The problem is my form isn't showing up. I tried different things, I watched if my settings were correct and for me everything is good. I think the problem comes from my view. <!-- navbar.html --> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a href="#" class="navbar-brand">Park<b>AUTO</b></a> <button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#navbarCollapse"> <span class="navbar-toggler-icon"></span> </button> <div id="navbarCollapse" class="collapse navbar-collapse justify-content-start"> <div class="navbar-nav"> <a href="#" class="nav-item nav-link">Home</a> <a href="#" class="nav-item nav-link">About</a> <a href="#" class="nav-item nav-link">Contact</a> </div> <div class="navbar-nav action-buttons ml-auto"> <a href="#" data-toggle="dropdown" class="nav-item nav-link dropdown-toggle mr-3">Login</a> <div class="dropdown-menu login-form"> <form action= {% url 'account:login' %} method="post"> {{ form.as_p }}{% csrf_token %} <input type="submit" class="btn btn-primary btn-block" value="Login"> </form> </div> <a href="#" class="btn btn-primary">Get Started</a> </div> </div> </nav> #views.py from django.shortcuts import redirect, render from django.contrib.auth.forms import AuthenticationForm # Create your views here. def login(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() login(request, user) return redirect("home:home") else: form = AuthenticationForm() return render(request, 'pages/home.html', {"form": form}) #urls.py from django.urls import path from .views import login app_name = 'account' urlpatterns = [ path('', login, name='login'), ] If someone could help me on that, it would be pretty nice.