Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-filter filtering by relation model associated with the second model
Have a DRF, django-filter and 3 models: Product model that has properties. class Product(models.Model): id = models.UUIDField(primary_key=True, verbose_name='ID', default=uuid.uuid4, editable=False, unique=True) code = models.CharField(max_length=128, blank=True, default='',) name = models.CharField(max_length=250, blank=True, default='') group = models.ForeignKey(Group, on_delete=models.SET_NULL, null=True, blank=True, related_name='products_group') properties = models.ManyToManyField(PropertyVariant, blank=True) # <--- property value price = models.DecimalField(max_digits=10, decimal_places=2, default=Decimal('0')) quantity = models.IntegerField(default=0) is_active = models.BooleanField(default=False) def __str__(self): return f'{self.name}' A property model whose type is specified in its associated model. class PropertyVariant(models.Model): id = models.UUIDField(primary_key=True, verbose_name='ID', default=uuid.uuid4, editable=False, unique=True) value = models.CharField(max_length=256, blank=True, default='') property_id = models.ForeignKey(Property, on_delete=models.CASCADE, null=True, blank=True) # <--- next relation def __str__(self): return f'{self.value}' Model of property types. class Property(models.Model): id = models.UUIDField(primary_key=True, verbose_name='ID', default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=256, blank=True, default='') value_type = models.CharField(max_length=256, blank=True, default='') def __str__(self): return f'{self.name}' I need to filter Products by PropertyVariant , but also need to specify which values exactly the filtering is performed on (Property).. How to do it in django-filter?... Thanx! -
Django combining the names of my two apps, and saying no module named that, with a module not found error
I'm new to django and doing my first project, I have just made a second app for my project, and I had thought that I set everything up properly. But when I try to runserver it comes up with: "ModuleNotFoundError: No module named 'homepagecourses'". My two apps are called homepage and courses respectively. I tried to add "homepagecourses" into my installed apps in settings but then it just said it couldn't find "homepagecourseshomepagecourses". My file directory looks like this -
Passing variables from view to Javascript code in Django
I have a template like the below in Django {% extends 'reports/base.html' %} {% block title %} Report Name {% endblock %} {% block content %} <!-- <div class="container-fluid"> <div class="row"><div class="col"> <ul class="list-group"> {% for r in report_list %} <li class="list-group-item"><a class="link-offset-2 link-underline link-underline-opacity-0" href={% url 'reports' report_id=r.id %}>{{ r.report_name }}</a></a></li> {% endfor %} </ul> </div><div class="col"></div><div class="col"></div></div> </div>--> <div class="demo-container"> <div id="sales"></div> <div id="sales-popup"></div> </div> <script> $(() => { let drillDownDataSource = {}; $('#sales').dxPivotGrid({ allowSortingBySummary: true, allowSorting: true, allowFiltering: true, allowExpandAll: true, showBorders: true, showRowGrandTotals: false, showColumnGrandTotals: false, fieldChooser: { enabled: true, }, export: { enabled:true }, onCellClick(e) { if (e.area === 'data') { const pivotGridDataSource = e.component.getDataSource(); const rowPathLength = e.cell.rowPath.length; const rowPathName = e.cell.rowPath[rowPathLength - 1]; const popupTitle = `${rowPathName || 'Total'} Drill Down Data`; drillDownDataSource = pivotGridDataSource.createDrillDownDataSource(e.cell); salesPopup.option('title', popupTitle); salesPopup.show(); } }, onExporting: function(e) { var workbook = new ExcelJS.Workbook(); var worksheet = workbook.addWorksheet('Main sheet'); DevExpress.excelExporter.exportPivotGrid({ worksheet: worksheet, component: e.component, customizeCell: function(options) { var excelCell = options; excelCell.font = { name: 'Arial', size: 12 }; excelCell.alignment = { horizontal: 'left' }; } }).then(function() { workbook.xlsx.writeBuffer().then(function(buffer) { saveAs(new Blob([buffer], { type: 'application/octet-stream' }), 'PivotGrid.xlsx'); }); }); e.cancel = true; }, dataSource: { fields: [ /*{ caption: … -
Adding custom expensive field on Django model serializer
Normally, in Django, using rest_framework, to add a custom field to a model, you can use SerializerMethodField. From what I understand however, this works great for values that are easy to calculate, but if the value requires database queries to related tables, you're going to be performing these for every item being returned. If I have a ViewSet like this: class ProductViewSet(ModelViewSet): queryset = models.Product.objects.all() serializer_class = serializers.ProductSerializer ... And a Serializer like this: class ProductSerializer(ModelSerializer): class Meta: model = models.Product fields = "__all__" How do I run a bulk query to get some data from a related table for all the products being serialized, and attach it to a new field. Ex: if each product is attached to an Order, maybe I want to add an order_number field. I could do this: class ProductSerializer(ModelSerializer): order_number = SerializerMethodField() @staticmethod def get_order_number(obj): return obj.order.order_number class Meta: model = models.Product fields = "__all__" But if the view is returning 100 products, that will be 100 database queries. Is there a more efficient way to do this? -
wrong email is saved in the database in Django
I am working on a project where users have to signup first to use this application. I attached the signup code below. views.py # Create your views here. def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) # post request is gonna contain data in the message body and validate that form data if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}. You are now able to log in.') return redirect('login') else: form = UserRegisterForm() # display a blank form return render(request, 'users/signup.html', {'form': form}) {% extends 'users/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <section id="formHolder"> <div class="row"> <!-- Brand Box --> <div class="col-sm-6 brand"> <a href="#" class="logo">Bookstagram <span>.</span></a> <div class="heading"> <h3>Bookstagram</h3> <p>Show Off Your Bookish Aestheics</p> </div> </div> <!-- Form Box --> <div class="col-sm-6 form"> <!-- Signup Form --> <div class="login form-peice"> <form class="login-form" method="POST"> {% csrf_token %} <fieldset class="form-group"> {{ form|crispy }} </fieldset> <div class="CTA"> <input type="submit" value="Signup Now" id="submit"> <a href="{% url 'login' %}">I have an account</a> </div> </form> </div><!-- End Signup Form --> </div> </div> </section> </div> {% endblock content %} if I give a wrong email such as "cindrella@gmail.c" or "cindrella@g.com", the system save the user details in … -
Each time I create superuser, Django saves the user but throws an error that user already exists even if it has never existed
I am fairly new to advanced Django and using Django 4.2 and PostGreSql 9.5 with PgAdmin4. I am trying to create a website, where users can sign in with email and password. I have created the models like so: class Users(AbstractBaseUser): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) email = models.EmailField(db_index=True, unique=True, max_length=250, blank=True, null=True) is_email_verified = models.BooleanField(default=False, help_text='this designates if the user\' email is verified') is_active = models.BooleanField(default=True, help_text='this designates if the user is active') is_staff = models.BooleanField(default=False, help_text='this designates if the user is staff or not') password = models.CharField(max_length=200, verbose_name='password of user') is_superuser = models.BooleanField(default=False, help_text='this designates if the user is superuser or not') last_login = models.DateTimeField(verbose_name='Last login of user', auto_now_add=True) created_time = models.DateTimeField(auto_now_add=True, verbose_name='Time user was created') USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: unique_together = ['id', 'email'] objects = UserManager() my user manager class is like this: class UserManager(BaseUserManager): def _create_user(self, email, password=None, **kwargs): if not email: raise ValueError('Email must be provided') user = self.model( email = self.normalize_email(email), **kwargs ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **kwargs): kwargs.setdefault('is_active', True) kwargs.setdefault('is_superuser', False) kwargs.setdefault('is_staff', False) user = self.model( email=self.normalize_email(email), password=password, **kwargs ) user.save() return self._create_user(email, password, **kwargs) def create_superuser(self, email, password=None, **kwargs): kwargs.setdefault('is_active', True) kwargs.setdefault('is_staff', True) … -
Reference Django Model Field from iterator in a for loop
I am attempting to create a model record using a for loop and cannot figure out how to reference the model field in a django create() function. I have mirrored response keys to the model fieldnames and want to loop through the response keys and assign the values in the model. Here is a simplified example. r = requests.get(url) r = r.json() ModelOne.objects.create( for field in r: ModelOne.field = r[field] ) I am trying to create the equivalent of ModelOne.Objects.create( fieldone = r[fieldone] ,fieldtwo = r[fieldtwo] ) Model: class ModelOne(models.Model): fieldone = models.IntegerField(blank=True, null=True) fieldtwo = models.IntegerField(blank=True, null=True) What I do not think works is trying to use .field in ModelOne.field as the object attribute. It doesn't return any errors but does not save the record either. I have also tried using raw sql with the django connection library but run into many other hurdles with that method. Is there a way to do this using the QuerySet API or should I be looking into another way? -
How implement a transactions to cashbox report system in Django?
`models.py # Cash Testing Models class Balance(models.Model): date = models.DateTimeField() amount = models.FloatField() detail = models.CharField(max_length=50) class Meta: verbose_name_plural = '8. Balance' def __str__(self): return str(self.amount) #def save(self, *args, **kwargs): #super().save(*args, **kwargs) #cashsystem = Cashsystem.objects.filter(amount=self.balance.amount).order_by('-id').first() class Income(models.Model): amount = models.FloatField() details = models.CharField(max_length=50, blank=True) income_date = models.DateTimeField() class Meta: verbose_name_plural = '9. Income' def save(self, *args, **kwargs): super().save(*args, **kwargs) cashsystem = Cashsystem.objects.filter(amount=self.balance.amount).order_by('-id').first() if cashsystem: ending_cash= cashsystem.amount + self.amount cashsystem.save() else: Cashsystem.objects.create( amount=self.balance.amount, income=self, expenses=None, income_amount=self.amount, expenses_amount=None, ending_cash=self.amount, ) class Expenses(models.Model): amount = models.FloatField() details = models.CharField(max_length=50, blank=False) expenses_date = models.DateTimeField() class Meta: verbose_name_plural = '10. Expenses' def save(self, *args, **kwargs): super().save(*args, **kwargs) cashsystem = Cashsystem.objects.filter(amount=self.balance.amount).order_by('-id').first() if cashsystem: ending_cash=cashsystem.amount - self.amount cashsystem.save() else: Cashsystem.objects.create( amount=self.balance.amount, income=None, expenses=self, income_amount=None, expenses_amount=self.amount, ending_cash=self.amount, ) #super().save(*args, **kwargs) # cash Model Testing class Cashsystem(models.Model): #date=models.DateTimeField(default=Cash.objects.date()) # add default value here amount = models.ForeignKey(Balance, on_delete=models.CASCADE,default=Balance.objects.first()) income = models.ForeignKey(Income, on_delete=models.CASCADE, default=0, null=True) expenses = models.ForeignKey(Expenses, on_delete=models.CASCADE, default=0, null=True) income_amount= models.FloatField(default=0, null=True) expenses_amount= models.FloatField(default=0, null=True) ending_cash = models.FloatField() class Meta: verbose_name_plural = 'Cash Box Entries' #ordering = ('-income__income_date', '-expenses__expenses_date') def income_date(self): if self.income: return self.income.income_date def expenses_date(self):`your text` if self.expenses: return self.expenses.expenses_date - I am building a personal Cash box management system, That will store My opening balance to … -
one .html file not getting logo.png file from the correct location
I'm working on creating a web application running in python3.10 using Django, most pages are working as expected but one page does not display the logo correctly, I get the following error: Not Found: /products/media/logo.png [09/Apr/2023 11:45:03] "GET /products/media/logo.png HTTP/1.1" 404 3536 The issue with this is that all of my .html files are currently using a base.html file and all of the other extend that to maintain the sites formatting using {% extends 'base.html' %} the path to the logo file only exists in the base.html file and only one page doesn't load the image correctly, ALL of the others do. it's also odd because there is no 'products/media' path in my project, in fact there isn't even a products folder so I'm not sure why it's trying to use this path, I've double and triple checked everything I can think of and I can't figure out why this page is attempting to get the logo.png file from a different location than all the other pages, for reference the html for this page is very simple: `{% extends 'base.html' %} {% block content %} <h1>{{ toy.name }}</h1> <p>{{ toy.description }}</p> <p>Price: ${{ toy.price }}</p> <img src="{{ toy.image.url }}" alt="{{ … -
Apache 403 Error - I can't access outside my Virutal Machine
I have built and deployed a Django app on Apache Server 2.4 but when I try to access it outside my host computer; (It's a Windows Server 2019 on VirtualBox). It pops 403 error. This is the error I have granted all the permissions on the firewall and I keep getting this error. -
How to force the www. on heroku
I have my domain on infomaniak and my django application on heroku my application work when i go to https://WWW.{{domain}} but i can't access to https://{{domain}} (without WWW.) thanks -
Users - Change Account Info Using Forms
I was trying to create a site that is responsible for editing profile info: Edit_profile.html file: {% extends 'base.html' %} {% block body %} <div class="container"> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> <br> </div> {% endblock %} and edit_profile is defined by: def edit_profile(request): if request.method =='POST': form = UserChangeForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('/Nornik/profile') else: form = UserChangeForm(instance=request.user) args = {'form': form} return render(request, 'Nornik/edit_profile.html', args) Everything is working fine (system detects no issues.), but what i recive as request is a site with login data, that I can't edit, although I defined it it my file (in urls.py everything is set properly re_path('profile/edit_profile/', views.edit_profile, name='edit_profile')). That's why i think that i should be able to edit that. Other articles on stackoverflow didn't help. Thanks for help. -
Django / Postgres and random Operational Error - Connection closed
We are having a hairy Django issue for a while now that keeps coming and going randomly. Every once in a while we get Operational Error - Connection closed. (see error below). We are running Django 4.2 / Py3.11 - pgbouncer - PostgreSQL 14 (EC2 + RDS in AWS). We have never had anything like this, do nothing but plain-vanilla django create/save stuff and started happening once in a while in Django 4 and forward. Anyone experiencing similar things or have a clue what could be going on??? Error message OperationalError: the connection is closed File "django/db/backends/base/base.py", line 308, in _cursor return self._prepare_cursor(self.create_cursor(name)) File "django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "django/db/backends/postgresql/base.py", line 331, in create_cursor cursor = self.connection.cursor() File "psycopg/connection.py", line 840, in cursor self._check_connection_ok() File "psycopg/connection.py", line 479, in _check_connection_ok raise e.OperationalError("the connection is closed") OperationalError: the connection is closed Django DB settings are: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', ... "DISABLE_SERVER_SIDE_CURSORS": True, "CONN_MAX_AGE": None, "CONN_HEALTH_CHECKS": True }, } [gunicorn] workers = multiprocessing.cpu_count() * 2 + 1 keepalive = 120 timeout = 120 graceful_timeout = 120 worker_connections = 1000 worker_class = 'sync' [pgbouncer] pool_mode = transaction default_pool_size = 100 min_pool_size = 20 reserve_pool_size = 30 … -
DRF djoser. token is invalid error when i try to login
I use token authorization with djoser in DRF. I save token in httpOnly cookies: class TokenCreateView(TokenCreateView): def _action(self, serializer): token = utils.login_user(self.request, serializer.user) token_serializer_class = settings.SERIALIZERS.token response = Response() data = token_serializer_class(token).data response.set_cookie( key = 'access_token', value = data['auth_token'], secure = False, httponly = True, samesite = 'Lax' ) response.data = {"Success" : "Login successfully","data":data} return response When I login in two devices, I get the same token. But when I logout in one of device, token becomes not valid. But the second device still has token in cookies. And now it is not authorized,but can't login again, because get "Invalid token". I know that the token is invalid, but I can't login. How to solve this problem? And why it gives the same token to all diveces? -
Why is my submit button for a simple mortgage calculator website built using Django and PostgreSQL not working?
I am trying to create a simple mortgage calculator for my first Django project, but seem to have run into a problem right towards the end because my server when run isn't displaying properly. This is how it displays Here is my file structure: File Directory Image 1, File Directory Image 2 I have used chat_gpt and bard to try and help build as well as trouble shoot this issue but they haven't been able to help. Here is all of my code, starting with the html code: base.html: <!DOCTYPE html> <html> <head> <title>Mortgage Calculator</title> {% load static %} <!-- Include your CSS and JS files here --> <!-- For example: --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <script src="{% static 'js/script.js' %"></script> </head> <body> <header> <!-- Header content here --> <h1>Mortgage Calculator</h1> <nav> <ul> <li><a href="/">Home</a></li> <!-- Add other navigation links here --> </ul> </nav> </header> <main> <div class="container"> <!-- Content from other templates will be placed here --> {% block content %} {% endblock %} </div> </main> <footer> <!-- Footer content here --> <p>&copy; 2023 Your Mortgage Calculator. All rights reserved.</p> </footer> </body> </html> mortgage_calculator.html: {% extends 'base.html' %} {% block content %} <h1>Mortgage Calculator</h1> <form action=“/mortgage_calculator” method="post"> … -
When using UploadedFile in the PUT method of ninja Router? I get ["detail": \[{"loc": \["body", "profile_in"\], "msg": "field required"]
I'm trying to add an UploadedFile parameter to the PUT method in my Ninja router. The same parameter works perfectly fine with the POST method, but when I try to use it with the PUT method, Ninja returns the error: Code 422 Details Error: Unprocessable Entity Response body { "detail": [ { "loc": [ "body", "profile_in" ], "msg": "field required", "type": "value_error.missing" } ] } which doesn't make sense to me, because I'm passing all the required parameters in the profile_in. here's the curl command that the swagger is providing: curl -X 'PUT' \ 'http://127.0.0.1:8000/api/profile/edit_profile' \ -H 'accept: application/json' \ -H 'Authorization: Bearer <my token>' \ -H 'Content-Type: multipart/form-data' \ -F 'profile_in={ "name": "Hassan", "title": "Web Developer", "bio": "string", "skills": [ { "name": "Django" } ] }' here's my post method: @profile_controller.post("create_profile", response={200: ProfileSchemaOut, 404: MessageOut, 400: MessageOut, }, auth=CustomAuth(), ) def create_profile(request, profile_in:ProfileSchemaIn, img:UploadedFile=None): and the put method: @profile_controller.put("edit_profile", response={200: ProfileSchemaOut, 404: MessageOut, 400: MessageOut, }, auth=CustomAuth(), ) def edit_profile(request, profile_in: ProfileSchemaIn, img:Optional[UploadedFile]=File(None)): I don't know if this is relevant but this is my ProfileSchemaIn class ProfileSchemaIn(ProfileSchema): name: str title: str bio: Optional[str] = None skills: Optional[List[SkillSchema]] I know I can use bas64 for storing the img but I … -
Django Error 403 Forbidden - CSRF verification failed. Request aborted
I want to use group and users native from Django to authenticate and get access to features in my website. I created a view called login_vew, configured a login.html page and configured settings.py just like this doc (https://docs.djangoproject.com/en/3.2/ref/csrf/) says. But the error persist and I dont know what is the problem. When I run local with python manage.py runserver works fine with debug=True works. views.py: from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect from store.models import Product from store.forms import ProductForm def login_view(request): if request.user.is_authenticated: return redirect('painel') if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: try: login(request, user) except Exception as e: messages.error(request, 'Ocorreu um erro ao fazer login. Tente novamente.') return redirect('painel') else: messages.error(request, 'Usuário ou senha incorretos') return render(request, 'login.html') login.html: <div class="card-body text-center"> <h2>Login</h2> <form method="post"> {% csrf_token %} <div class="form-group"> <label for="username">Usuário:</label> <input type="text" class="form-control" id="username" name="username" required> </div> <div class="form-group"> <label for="password">Senha:</label> <input type="password" class="form-control" id="password" name="password" required> </div> <br> <button type="submit" class="btn btn-primary">Entrar</button> </form> </div> settings.py: DEBUG = False CSRF_COOKIE_SECURE = True AUTHENTICATION_BACKENDS = \[ 'django.contrib.auth.backends.ModelBackend', \] LOGIN_URL = '/login/' LOGIN_REDIRECT_URL … -
Django ORM fetching
i want to fetch data from Django model using Q(). what i want is obj = models.Products.objects(Q(description=[a list of descriptions])) I want all the objects matching the descriptions with the elements of the list -
bootstrap and css together is not working in django
I am working on a project where in the timeline.html file users can see their username, bio, url, profile picture and uploaded book photos. I am using bootstrap for navbar and I am using html, css for designing the uploaded book photos and user information. However, navbar design look okay before adding the html css codes of the uploaded book photos and user information. But when I added the codes of the uploaded books and user information, the navbar looks stretched. Can anyone help me solving this problem? base.html {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"> <link rel="icon" href="{% static 'books/images/logo.png' %}"> {% block link %}{% endblock %} <title>Bookstagram</title> </head> <body> <nav class="navbar navbar-expand-md navbar-dark bg-steel" style="background-color: #1DA1F2"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'timeline' %}"><strong><i>Bookstagram</i></strong></a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-info my-2 my-sm-0" type="submit">Search</button> </form> <ul class="navbar-nav ml-auto"> <li> <a class="nav-link" href="">Create Post</a> </li> <li> <a class="nav-link" href="">Profile</a> </li> <li> <a class="nav-link" href="">Logout</a> </li> … -
Submit form using Django views and redirect to React path
I have a form that on submit goes to http://127.0.0.1:8000/all/new/ in order to trigger a view function that creates a new object. booking.js form action="http://127.0.0.1:8000/all/new/" method="POST"> ... /form After creating the object, I want to go back to the homepage that's rendered by React ("http://localhost:3000/"). How can I do this? views.py @api_view(["POST"]) def create_object(request): ... return Response(serializer.data) urls.py urlpatterns = [ path("new/", views.create_booking, name="create_booking"), ] -
Getting task statuses in celery
I have a need to get task statuses in celery, but for some reason I can always get only the "PENDING" and "SUCCESS" statuses, but if I look through flower, I can also see the "STARTED" status Now I'm trying to get the status like this AsyncResult(task_uuid).status python 3.8.10 celery 5.2.7 -
Why can't my blog post be displayed in pythonanywhere.com
I am a beginner of Django, just followed the tutorial to create a blog of my own, but the posts of my blog cannot be displayed normally in pythonanywhere.com These are my files: base.html {% load static %} <!DOCTYPE html> <html> <head> <title>Kington's blog</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <link href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> </head> <body> <header class="page-header"> <div class="container"> <h1><a href="/">Kington's Blog</a></h1> </div> </header> <main class="container"> <div class="row"> <div class="col"> {% block content %} {% endblock %} </div> </div> </main> </body> </html> post_list.html {% extends 'blog/base.html' %} {% block content %} {% for post in posts %} <article class="post"> <time class="date"> {{ post.published_date }} </time> <h2><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h2> <p>{{ post.text|linebreaksbr }}</p> </article> {% endfor %} {% endblock %} post_detail.html {% extends 'blog/base.html' %} {% block content %} <article class="post"> {% if post.published_date %} <time class="date"> {{ post.published_date }} </time> {% endif %} <h2>{{ post.title }}</h2> <p>{{ post.text|linebreaksbr }}</p> </article> {% endblock %} urls.py from django.urls import path from . import views urlpatterns = [ path('', views.post_list, name='post_list'), path('post/<int:pk>/', views.post_detail, name='post_detail'), ] views.py from django.shortcuts import render from .models import Post from django.utils import timezone from django.shortcuts import render, get_object_or_404 … -
Hi. I already set up payment for site, but i cant set up Order status and Basket history in admin panel
'''views.py @csrf_exempt def stripe_webhook_view(request): payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, sig_header, settings.STRIPE_WEBHOOK_SECRET ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: return HttpResponse(status=400) if event['type'] == 'checkout.session.completed': # Retrieve the session. If you require line items in the response, you may include them by expanding line_items. session = stripe.checkout.Session.retrieve( event['data']['object'] ) line_items = session.line_items fulfill_order(line_items) return HttpResponse(status=200) def fulfill_order(line_items): order_id = int(line_items.metadata.order_id) order = Order.objects.get(id=order_id) order.update_after_payment() ''' When i purchase smthng i expect to change Order status and Basket history in admin panel. Now after payment in admin panel Order status doesn't change (i need to get Paid) and Basket history inside order is empty. I took this Webhook from Stripe documentation -
django how can I sort by user field
How can I make sure that when creating a task, a list of models created only by the author who is currently creating the task is displayed Code: class Tasks(models.Model): title = models.CharField(max_length=75) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="creator", editable=False) class Category(models.Model): title = models.CharField(max_length=30, db_index=True, verbose_name="category_name") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="category_creator", editable=False) class TaskCreateView(CreateView): form_class = TaskForm template_name = 'main/add_task.html' def form_valid(self, form): form.instance.user = self.request.user return super(TaskCreateView, self).form_valid(form) def get_queryset(self): return Tasks.objects.filter(user=self.request.user) I tried to do it with this code, but i couldn't: class TaskForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['category'].queryset = Tasks.objects.filter(category__category__user=self.request.user) self.fields['category'].empty_label = "Not selected" class Meta: model = Tasks fields = ['title', 'category'] -
UpdateView wont databind the from properties
class NewPostForm(forms.Form): post = forms.ChoiceField(choices = POSTTYPE_CHOICES) title = forms.CharField(max_length=100) content = forms.CharField(widget=SummernoteWidget()) # instead of forms.Textarea pic = forms.ImageField(required=False) tags = forms.CharField(max_length=200,required=False) @login_required def update_post(request,pk): user = request.user postToSave = get_object_or_404(PostForNewsFeed, pk=pk) form = NewPostForm(request.POST, request.FILES) if user.is_authenticated: if request.method == "POST": if form.is_valid(): post = request.POST['post'] title = request.POST['title'] content = request.POST['content'] tags = request.POST['tags'] postToSave.post = post postToSave.title = title postToSave.content = content postToSave.tags = tags if 'pic' in request.FILES: pic = request.FILES['pic'] postToSave.pic = pic postToSave.save() else: postToSave.save() return redirect('home3') else: form = NewPostForm() return render(request, 'feed/create_post.html', {'form':form,'page_title': 'Share a Post' }) <form class="form-signin" method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <br /> {{ form |crispy }} </fieldset> <div class="form-group"> <button class="btn btn-lg btn-info btn-block text-uppercase" type="submit" > Post</button ><br /> </div> </form>