Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
edit and delete django comments not working
my Edit/delete comments is not working. Anyone got any idea why its not editing or deleteing the review comments? In views.py its under views.py def product_detail, def delete_product and def delete_review last two on the bottom of the page. forms.py Its under class ReviewForm and in models its under class Review views.py from django.shortcuts import render, redirect, reverse, get_object_or_404 from django.contrib import messages from django.contrib.auth.decorators import login_required from django.db.models import Q from django.db.models.functions import Lower from .models import Product, Category, Review from .forms import ProductForm, ReviewForm # Create your views here. def all_products(request): """ A view to show all products, including sorting and search queries """ products = Product.objects.all() query = None categories = None sort = None direction = None if request.GET: if 'sort' in request.GET: sortkey = request.GET['sort'] sort = sortkey if sortkey == 'name': sortkey = 'lower_name' products = products.annotate(lower_name=Lower('name')) if sortkey == 'category': sortkey = 'category__name' if 'direction' in request.GET: direction = request.GET['direction'] if direction == 'desc': sortkey = f'-{sortkey}' products = products.order_by(sortkey) if 'category' in request.GET: categories = request.GET['category'].split(',') products = products.filter(category__name__in=categories) categories = Category.objects.filter(name__in=categories) if 'q' in request.GET: query = request.GET['q'] if not query: messages.error(request, "You didn't enter any search criteria!") return redirect(reverse('products')) queries … -
Django overriding User model for extra fields for already created project
I am new to Django and I just followed this tutorial online but the coder used Regular User model which has only "User_name, Last_name, Email, Password" fields. I am trying to add extra fields "age, sex, department etc.." for users to fill before finishing signup, So far I managed to add extra fields to User model using OnetoOneField relationship and I can access them in Admin panel and even register users with the extra fields but when I try create new user with my registration.html file or with Shell I get error: views.py user = User.objects.create_user(first_name="Test", last_name="Test2", username="Test3", password="Test3333", extra_field="test") TypeError: User() got an unexpected keyword argument 'extra_field' Using the form registrations.html I sign up no problem but the extra field is not filled or nulled. models.py from django.db import models from django.contrib.auth.models import User class EmployeeDetail(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) empcode = models.CharField(max_length=9, unique=True) nnum = models.CharField(max_length=13, default="") contact = models.CharField(max_length=15, null=True) gender = models.CharField(max_length=50, null=True) joiningdate = models.DateField(null=True) def __str__(self): return self.empcode + ' ' + self.user.first_name + ' ' + self.user.last_name class EmployeeSalary(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) salary = models.FloatField(default=0) x= models.IntegerField(default=520) x= models.BooleanField(default=False) x= models.IntegerField(default=0) def totalsalary(self): tsalary = 0 if self.x: tsalary = self.x* … -
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 2082-2084: ordinal not in range(256)
I don't know why this is happening. Whenever I add Arabic content it shows the above error, otherwise works fine with the English language Same code is working in another project perfectly but not here. views.py def generate_pdf_for_gift_and_add_to_cart(request): cart = Cart(request) if request.method == 'POST': id = request.POST.get('project_id') selectedAmount = request.POST.get('amount') senderNameDonatedDonationPage = request.POST.get( 'senderNameDonatedDonationPage') receiverNameDonatedDonationPage = request.POST.get( 'receiverNameDonatedDonationPage') phoneNumberDonatedDonationPage = request.POST.get( 'phoneNumberDonatedDonationPage') emailDonatedDonationPage = request.POST.get('emailDonatedDonationPage') params = { "project_id": id, "selectedAmount": selectedAmount, } pdf = render_to_pdf('pdfs/gift_pdf.html', params) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = f"Invoice_{emailDonatedDonationPage}_{datetime.now()}.pdf" content = "inline; filename='%s'" % filename download = request.POST.get("download") if download: content = "filename='%s'" % filename response['Content-Disposition'] = content receipt_file = BytesIO(pdf.content) return response utils.py I also tried utf-8 encoding, but that shows me blank boxes on the generated pdf page. from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None gift_pdf.html below is the example template, where will render that. <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Gift PDF</title> <style type="text/css"> @page { size: 6in; } … -
django inline add button missing on version 3.2
I have a Django site where the admin forms with inlines are missing the add button below the inlines. We are using Django jet if this is relevant. Thanks a lot. -
django- createview get id with which it was saved in database return none self.object.pk in form_valid is None
I have created a view with createview where I have a form, this view has the url: path('asignacionContact/<int:pk>/',AsignacionCreateView.as_view(), name='assignacion_contact') , I fill the form and effectively it is saved in the database, but I want to get the id with which it was saved in the database, so in the form_valid method I try to get the id with self.object.pk or form.instance.pk but it returns None , how can I fix this? urls.py app_name = 'gestionAsignacion' urlpatterns = [ path('asignacionContact/<int:pk>/',AsignacionCreateView.as_view(), name='asignacion_contact'), path('detalle/asignacion/<int:pk>',descargarAsignacion.as_view(), name='descargar_asignacion'), path('asignacionGeneral/',asignacionGeneral.as_view(), name='asignacion_general'), ] model.py class AsignacionContact(models.Model): id = models.IntegerField(primary_key=True) idasignacion_general = models.ForeignKey('AsignacionGeneral', models.DO_NOTHING, db_column='idasignacion_general') nombre_asignacion = models.CharField(max_length=100) fecha_inicio = models.DateField() fecha_fin = models.DateField() observacion = models.CharField(max_length=255, blank=True, null=True) estado = models.IntegerField(blank=True, null=True) def __str__(self): return self.nombre_asignacion # def get_absolute_url(self): # print('reverse') # return reverse('gestionAsignacion:asignacion_contact',kwargs={ 'pk': self.pk }) class Meta: managed = False db_table = 'asignacion_contact' view.py class AsignacionCreateView(CreateView): model=AsignacionContact form_class=AsignacionForm template_name='gestionAsignacion/asignacion_contact.html' # success_url = reverse_lazy('gestionAsignacion:asignacion_general') def form_valid(self, form): isvalid = super().form_valid(form) print('form_valid') print(form.instance.pk) print(self.object.pk) return isvalid def post(self, request, *args, **kwargs): print('post') return super().post(request, *args, **kwargs) def get_form_kwargs(self): kwargs = super(AsignacionCreateView, self).get_form_kwargs() kwargs['pk'] = self.kwargs.get('pk') return kwargs def get_success_url(self): print('hola succes') print(self.object.id) return reverse('gestionAsignacion:asignacion_general') -
How to get total cart in Django?
I have 2 models: order and cart this is the order's model: class Order(models.Model): user=models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE) product=models.ForeignKey(Product, on_delete=models.CASCADE) quantity=models.IntegerField(default=1) ordered=models.BooleanField(default=False) ordered_date= models.DateTimeField(blank=True, null=True) def __str__(self): return f'{self.product.name}({self.quantity})' def get_total(self): total=self.quantity * self.product.price return total and this is the cart'model: class Cart(models.Model): user=models.OneToOneField(AUTH_USER_MODEL, on_delete=models.CASCADE) orders=models.ManyToManyField(Order) def __str__(self): return self.user.username def get_total_cart(self): orderitem = self.orders.all() total = sum(item.get_total() for item in orderitem) return total How could I fix the get_total_cart() function please -
Strange AttributeError error due to Views (Django)
type object 'projects' has no attribute '_default_manager' I am getting this error when on a second view using the same model as the first. If the model changes, and the fields are adjusted, it works. Both views are indentical aside from their template names as I need one to simply list children in a checklist model. class project(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = projects fields = [ 'name', 'fk_state', ] template_name = '/project_details.html' context_object_name = 'projects' def form_valid(self, form): form.instance.fk_user = self.request.user form.save() # return super().form_valid(form) return HttpResponseRedirect(self.request.path_info) def test_func(self): post = self.get_object() if self.request.user == post.fk_user: return True return False class project_checklist(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = projects fields = [ 'name', 'fk_state', ] template_name = '/project_checklist.html' context_object_name = 'checklist' def form_valid(self, form): form.instance.fk_user = self.request.user form.save() # return super().form_valid(form) return HttpResponseRedirect(self.request.path_info) def test_func(self): post = self.get_object() if self.request.user == post.fk_user: return True return False Urls path('projects/project/<int:pk>',project.as_view(), name='project'), path('projects/checklist/<int:pk>',project_checklist.as_view(), name='checklist'), -
Why is my save method not returning any value
When I do investment.basic_interest I get 0. Why is it returning 0? I feel my save method is not properly written. Any idea where the problem is coming from? class Investment(models.Model): basic_deposit_amount = models.IntegerField(default=0, null=True) basic_interest = models.IntegerField(default=0, null=True) def save(self, *args, **kwargs): self.basic_interest = self.basic_deposit_amount * 365 * 0.02/2 #calculated field. super(Investment, self).save(*args, **kwargs) -
How do I include previous years in a Django Model form
Forgive me if this has already been asked I have a blog and use the template you can see on Djangos website (with minor amendments) When I create a new blog I can select the date from January 1st 2022 to December 31st However there are some writing I made last year and wish to include the correct date for them. Any help is appreciated p.s. I'm using Sqlite as my database View from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import get_object_or_404, render, redirect from django.views.generic import ( CreateView, ListView, UpdateView, DetailView ) from tags.models import Tag from .forms import BlogForm from .models import Blog class BlogCreateView(LoginRequiredMixin, CreateView): template_name = 'blog/create_blog.html' form_class = BlogForm queryset = Blog.objects.all() def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) class BlogUpdateView(LoginRequiredMixin, UpdateView): template_name = 'blog/create_blog.html' form_class = BlogForm queryset = Blog.objects.all() def form_valid(self, form): return super().form_valid(form) def blog_delete_view(request, slug): obj = get_object_or_404(Blog, slug=slug) if request.method == "POST": obj.delete() return redirect('blog:home') context = { "object": obj } return render(request, "blog/delete_blog.html", context) class BlogListView(ListView): template_name = "blog/home.html" model = Blog blog_public = model.objects.filter(is_public=True, tags__public=True) def get_context_data(self, *args, **kwargs): context = super(BlogListView, self).get_context_data(*args, **kwargs) request = self.request user = request.user blog_tag = Tag.objects.filter(name="blog").first() if user.is_authenticated: blog_user = self.model.objects.filter(user=user)[:5] … -
'set' object is not reversible is being raised but I'm not getting specific file or line
I'm getting this error and browser indicating that program is complaining to {% url 'login' %}. And what interesting is that I've never used set in this code. For now it's sounds stupid error for me because of error indicating html file and complaining to set type. Environment: Request Method: GET Request URL: http://0.0.0.0:8000/ Django Version: 2.2 Python Version: 3.7.13 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'users.apps.UsersConfig', 'pages.apps.PagesConfig', 'crispy_forms', 'allauth', 'allauth.account'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /code/templates/base.html, error at line 18 'set' object is not reversible 8 : &lt;link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" 9 : integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" 10 : crossorigin="anonymous"&gt; 11 : &lt;link rel="stylesheet" href="{% static 'css/base.css' %}"&gt; 12 : &lt;/head&gt; 13 : &lt;body&gt; 14 : &lt;header&gt; 15 : &lt;!-- Fixed navbar --&gt; 16 : &lt;div class="d-flex flex-column flex-md-row align-items-center p-3 px-md-4 17 : mb-3 bg-white border-bottom shadow-sm"&gt; 18 : &lt;a href=" {% url 'home' %} " class="navbar-brand my-0 mr-md-auto font-weight-normal"&gt;Bookstore&lt;/a&gt; 19 : &lt;nav class="my-2 my-md-0 mr-md-3"&gt; 20 : &lt;a class="p-2 text-dark" href="{% url 'about' %}"&gt;About&lt;/a&gt; 21 : {% if user.is_authenticated %} 22 : &lt;a class="p-2 text-dark" href="{% url 'logout' %}"&gt;Log Out&lt;/a&gt; 23 : {% else %} 24 : &lt;a class="p-2 text-dark" href="{% … -
Docker on windows8.1 can't run Django
cmd: Successfully built c16b1b66eff5 Successfully tagged django_docker_with_postgresql_web:latest Recreating django_docker_with_postgresql_web_1 ... done Recreating django_docker_with_postgresql_db_1 ... done Attaching to django_docker_with_postgresql_db_1, django_docker_with_postgresql_web_1 db_1 | db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db_1 | db_1 | 2022-06-26 14:22:42.826 UTC [1] LOG: starting PostgreSQL 14.3 (Debian 14.3-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit db_1 | 2022-06-26 14:22:42.828 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2022-06-26 14:22:42.830 UTC [1] LOG: listening on IPv6 address "::", port 5432 db_1 | 2022-06-26 14:22:42.834 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db_1 | 2022-06-26 14:22:42.843 UTC [24] LOG: database system was shut down at 2022-06-26 14:18:52 UTC web_1 | Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). web_1 | web_1 | You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. web_1 | Run 'python manage.py migrate' to apply them. web_1 | June 26, 2022 - 14:22:46 ''' Blockquote docker-compose.yml version: '3.3' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 db: … -
Django override django.contrib.auth login process
views.py from django.contrib import messages from django.http import HttpResponse from django.contrib.auth import authenticate, login from django.contrib.auth.views import LoginView from django.shortcuts import render def index(request): return render(request, 'index.html') def templates(request): return render(request, 'templates.html') def information(request): return render(request, 'information.html') def custom_login(request): if request.POST: username = request.POST['username'] password = request.POST['password'] user = authenticate(username = username, password = password) print("work") if user is not None: messages.success(request, 'Success') login(request, user) return HttpResponse('login') #logout(request) else: messages.error(request, 'Invalid username or password') print("error") return HttpResponse('wrong username or password') class CustomLoginView(LoginView): print("check") def form_valid(self): custom_login(self.request) urls.py from django.contrib import admin from django.urls import path, include from ArtisticCode import views urlpatterns = [ path('admin/', admin.site.urls), path('accounts/login/', views.CustomLoginView.as_view(), name='login'), path('accounts/', include('django.contrib.auth.urls')), path('', views.index, name = 'index'), path('templates/', views.templates, name = 'templates'), path('information/', views.information, name = 'information'), ] accounts/login.html <form method="post" class="login"> {% csrf_token %} <div class="login_input"> <img src="{% static 'img/bx_img1.png' %}" alt="image"/> <input type="text" placeholder="Username" name="username" required/> </div> <div class="login_input"> <img src="{% static 'img/bx_img1.png' %}" alt="image"/> <input type="password" placeholder="Password" name="password" required/> </div> <input type="submit" value="Send message"/> {% if messages %} {% for message in messages %} <strong style="color:white;">{{ message }}</strong> {% endfor %} {% endif %} </form> The idea is to display a message in case of a wrong password, but … -
Template - Parent Detailview w/ child for loop list
I've been trying solutions that have been suggested for others in similar situations, however almost all questions are regarding bizzarely unusual scenarios and I've been unable to adapt them to my situation. I'd like a for loop of child information in a parent's DetailView Models class Projects(models.Model): fk_user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.BooleanField(default=False) class Projects_items(models.Model): itemName = models.BooleanField(default=False) fk_project = models.ForeignKey(Projects,on_delete=models.CASCADE, related_name="item") value = models.FloatField() Views class projects(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Projects fields = [ 'name', ] template_name = 'games/project_details.html' context_object_name = 'projects' def form_valid(self, form): form.instance.fk_user = self.request.user form.save() # return super().form_valid(form) return HttpResponseRedirect(self.request.path_info) def test_func(self): post = self.get_object() if self.request.user == post.fk_user: return True return False Template - projects_details {% extends './underlay.html' %} {% load static %} {% load crispy_forms_tags %} <link rel="stylesheet" type="text/css" href="{% static 'details.css' %}"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins"> {% block content %} <H2>LIST OF ITEMS BELONGING TO THIS PROJECT</H2> ? SOMETHING LIKE: {% for projects.item in projects %} {{ projects.item.itemName }} - {{ projects.item.value }} {% endfor %} THIS GAVE AN ERROR OF 'PROJECTS' OBJECT NOT ITERABLE -
Saving related model objects in single view
I need some help from you folks! I am beginner and I am working on Django project - risk assessment application. I have a trouble to achieve saving on related objects for my application risk record. I am using MultiModelForm to achieve the following. I am successfully creating Whatif instance and connecting it with GuideWordi instance on save, however, I am not able to connect my RiskRecordi instance with GuideWordi instance, but RiskRecordi instance is saved into the db (I see it through admin). I tried lot's of research over the web, but confused now. My models.py: class WhatIf(models.Model): moc_no = models.CharField(max_length=12, blank=True) ra_scope = models.TextField(max_length=128, blank=True) facilitator = models.ForeignKey(User, related_name='facilitator', null=False, on_delete=models.SET_DEFAULT, default='0') def __str__(self): return self.moc_no def get_absolute_url(self): return reverse('whatif:whatif_form', kwargs={'pk': self.pk}) class GuideWordi(models.Model): whatif = models.ForeignKey(WhatIf, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=160, blank=True) def __str__(self): return self.name class RiskRecordi(models.Model): guidewordi = models.ForeignKey(GuideWordi, blank=True, null=True, on_delete=models.CASCADE) cause = models.TextField(max_length=128, blank=True) consequence = models.TextField(max_length=128, blank=True) safeguard = models.TextField(max_length=128, blank=True) My views.py class WhatIfCreateView(CreateView): Model = WhatIf form_class = WhatIfForm template_name = 'whatif/ra-initiate.html' def form_valid(self, form): obj = form.save(commit=False) obj.facilitator = self.request.user return super().form_valid(form) from multi_form_view import MultiModelFormView class RiskRecordView(MultiModelFormView): form_classes = { 'guideword_form' : GuideWordiForm, 'riskrecord_form' : RiskRecordiForm,} template_name = … -
Django squashmigrations: How to rollback effects of squashmigrations command?
I have squashed migrations and it created a new migration files by squashing all the migrations of the app. Due to some post squashmigrations issue I want to undo the effects of squashmigrations command. The problem is that now migrate command is not working because Django is not able to detect the presence of old migrations file that are squashed into a new migrations file. Example: Let's say all the four migrations from 0001 to 0004 are applied and then I squash them by running the following command. $ ./manage.py squashmigrations myapp 0004 Will squash the following migrations: - 0001_initial - 0002_some_change - 0003_another_change - 0004_undo_something Do you wish to proceed? [yN] y Optimizing... Optimized from 12 operations to 7 operations. Created new squashed migration /home/andrew/Programs/DjangoTest/test/migrations/0001_squashed_0004_undo_something.py You should commit this migration but leave the old ones in place; the new migration will be used for new installs. Once you are sure all instances of the codebase have applied the migrations you squashed, you can delete them. Now if I try to run the following command to rollback to previous state: python manage.py migrate myapp 0004 It throws an error saying CommandError: Cannot find a migration matching'myapp/migrations/0004_undo_something.py' from app 'myapp' -
Bootstrap dropdown list won't work in django html template
I just was trying to apply bootstrap in my shared html file in a Django project and the dropdown list just won't work I tried everything I could cdn local bootstrap and when I click the dropdown list nothing happens. that's my template script: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}"> <title> {% block title %}{% endblock %} </title> </head> <body> <nav class="navbar navbar-expand-md navbar-dark bg-dark"> <a class="navbar-brand" href="{% url 'home' %}">Home</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> {% if user.is_authenticated %} <ul class="navbar-nav ms-auto"> <li class="nav-item"> <a class="nav-link dropdown-toggle" href="#" id="userMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{ user.username }} </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="userMenu"> <a class="dropdown-item" href="{% url 'upload'%}">Upload</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'logout' %}"> Log Out</a> </div> </li> </ul> {% else %} <form class="form-inline ms-auto"> <a href="{% url 'login' %}" class="btn btn-outline-secondary"> Log In</a> <a href="{% url 'signup' %}" class="btn btn-primary ms-2"> Sign up</a> </form> {% endif %} </div> </nav> <div class="container"> {% block content %} {% endblock content %} </div> <script src="{% static 'js/bootstrap.bundle.js'%}"></script> <script src="{% static 'js/bootstrap.bundle.min.js' %}"></script> … -
In datatables, how can we show headers while loading, and then when data loads, show all the datatable?
I am running a django project in which I have a html page to render where I am displaying some data in tabular format using datatables. I am getting that data for the table from api, so it takes time of about 1 or 2 seconds. During this loading time I am using a spinner. But I want the table headers and the filters and search tab that comes with datatables to be displayed while those 2 seconds of loading time, and when the data is ready, complete datatable will be displayed. How can I do that? Thanks in advance. -
Deploy Django project on ubuntu
I have a Django project with written Dockerfile and docker-compose.yml. Projects works as expected on localhost and I want to deploy it to already created ubuntu machine. I tried to manage that with Ansible but haven't succeeded. I use postgresql to store data my docker file # syntax=docker/dockerfile:1 FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ CMD python manage.py runserver 0.0.0.0:80 docker-compose.yml version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:80 volumes: - .:/code ports: - "80:80" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db -
How can from the sum of invested amount and deposit amount using Django
I am trying to withdraw some amount from my investment using the line of code below but its not working. investment.basic_investment_return -= investment.basic_withdraw_amount Model from django.db import models class Investment(models.Model): basic_deposit_amount = models.IntegerField(default=0, null=True) basic_interest = models.IntegerField(default=0, null=True) basic_investment_return = models.IntegerField(default=0, null=True) basic_withdraw_amount = models.IntegerField(default=0, null=True, blank=True) basic_balance = models.IntegerField(default=0, null=True, blank=True) investment_id = models.CharField(max_length=10, null=True, blank=True) is_active = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now=True, null=True) Forms from django import forms from .models import Investment class BasicInvestmentForm(forms.ModelForm): class Meta: model = Investment fields = ['basic_deposit_amount'] class BasicWithdrawalForm(forms.ModelForm): class Meta: model = Investment fields = ['basic_withdraw_amount'] Views from django.shortcuts import get_object_or_404, redirect, render from django.db.models import Sum, F from django.contrib import messages from .forms import BasicInvestmentForm, BasicWithdrawalForm, from .models import Investment, def create_investment_view(request): if request.method == 'POST': basic_investment_form = BasicInvestmentForm(request.POST) if basic_investment_form.is_valid(): investment = basic_investment_form.save(commit=False) investment.basic_investment_return += investment.basic_deposit_amount print(investment.basic_investment_return) investment.is_active = True investment.save() messages.success(request, 'your basic investment of {} is successfull '.format(investment.basic_deposit_amount)) else: messages.success(request, 'your investment is not successfull! Try again.') else: basic_investment_form = BasicInvestmentForm() context = {'basic_investment_form': basic_investment_form} return render(request, 'create-basic-investment.html', context) def create_withdrawal_view(request): if request.method == 'POST': basic_withdraw_form = BasicWithdrawalForm(request.POST) if basic_withdraw_form.is_valid(): investment = basic_withdraw_form.save(commit=False) investment.basic_investment_return -= investment.basic_withdraw_amount print(investment.basic_investment_return) investment.save() messages.success(request, 'your withdrawal of {} is successfull '.format(investment.basic_withdraw_amount)) else: messages.success(request, 'your … -
Generate same Django Token Docker
I wanted to know if there was any way to always generate the same token for a user. I currently use the following command in building a docker image but it always generates a different token which makes the services are connected through the token, stop working. python3 manage.py drf_create_token root Is there any way to always generate the same token or some other method to achieve something similar? Thank you very much and sorry for the ignorance xd -
Django channels - not connection to ws
I'm making an example from the documentation Django channels and it works great! I see in the logs HTTP GET /chat/lobby/ 200 [0.00, 127.0.0.1:43164] WebSocket HANDSHAKING /ws/chat/lobby/ [127.0.0.1:43168] WebSocket CONNECT /ws/chat/lobby/ [127.0.0.1:43168] however I can't connect with the client andrey@andrey-desktop:~$ wscat -c "ws://127.0.0.1:8000/ws/chat/lobby/" error: Unexpected server response: 403 or postman postman disconnect I see in the logs on unsuccessful attempts WebSocket HANDSHAKING /ws/chat/lobby/ [127.0.0.1:43232] WebSocket REJECT /ws/chat/lobby/ [127.0.0.1:43232] WebSocket DISCONNECT /ws/chat/lobby/ [127.0.0.1:43232] How do I make connectivity from other clients, not just from the javascript/html page? -
Django query from paypalipn table
I have connected my django-paypal and I have managed to make payments but it seems I can make queries from paypal_ipn table or I'm making mistakes somewhere. The below are the currect snippets of what I have done. from paypal.standard.ipn import models as paypal_models from .serializers import PaymentSerializer @api_view(['GET']) def getPaymentStatus(request): postedRef = PaymentSerializer(data=request.data) print(postedRef) paypalTxn = paypal_models.PayPalIPN #On here I'm trying to query serializer = PaymentSerializer(paypalTxn) return Response(serializer.data) The below is something that I intend to get. from paypal.standard.ipn import models as paypal_models from .serializers import PaymentSerializer @api_view(['GET']) def getPaymentStatus(request): postedRef = PaymentSerializer(data=request.data) print(postedRef) paypalTxn = paypal_models.PayPalIPN.objects.filter(invoice=postedRef).first() #Something like this serializer = PaymentSerializer(paypalTxn) return Response(serializer.data) -
Unable to change position of previous and next button and background color of carousel slide
Can't change positions of the prev and next buttons and not only that but also the background color of carousel slidebar of also unable to changed. i tried from inspecting it but can't save changes in inspect and not by entering code of those buttons. {% extends 'shop/basic.html' %} {% block css %} .carousel-indicators [data-bs-target] { background-color: #0d6efd; } .col-md-3 { display: inline-block; margin-left: -4px; } .carousel-indicators .active { background-color: blue; } .col-md-3 img{ width: 170px; height: 200px; } body .carousel-indicator li{ background-color: blue; } body .carousel-indicators{ bottom: 0; } body .carousel-control-prev-icon, body .carousel-control-next-icon{ background-color: blue; } .carousel-control-prev, .carousel-control-next{ bottom: auto; top: auto; padding-top: 222px; } body .no-padding{ padding-left: 0; padding-right: 0; } {% endblock %} From here I given id and names to the particular code above mentioned {% block body %} {%load static%} <div class="container"> {% for product,range,nSlide in allprods %} <h5 class="my-4"> {{product.0.category}} </h5> <div id="row"> <div id="demo{{forloop.counter}}" class="carousel slide my-3" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#demo{{forloop.counter}}" data-bs-slide-to="0" class="active"></button> {% for i in range%} <button type="button" data-bs-target="#demo{{forloop.parentloop.counter}}" data-bs-slide-to="{{i}}"></button> {% endfor %} </div> <div class="container carousel-inner no-padding"> <div class="carousel-item active"> {% for i in product %} <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card align-items-center" style="width: 18rem;"> <img src='/media/{{i.image}}' class="card-img-top" … -
Username and password are always incorrect in my django AuthenticationForm
I'm trying to login user by his username and password, but when i'm trying to check form.is_valid(), it returns False. Errorlist contain error: "Please enter a correct username and password. Note that both fields may be case-sensitive.". When i don't specify my own post it's doesn't work either. I was looking for typo, but didn't found any. In internet nothing helped me at all. I tried switch form and it's fields, but error was the same. views.py from django.views.generic import * from django.views.generic import * from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import authenticate, login, logout ... class RegisterView(CreateView): form_class = UserRegisterForm success_url = reverse_lazy('main:homepage') template_name = "accounts/register.html" def post(self, request): form = self.get_form() if form.is_valid(): user = form.save() login(request, user) return redirect("main:homepage") else: print(form.errors) return redirect("accounts:register") class LoginView(FormView): form_class = AuthenticationForm template_name = "accounts/login.html" def post(self, request): form = self.get_form() if form.is_valid(): form.clean() user = authenticate( request, username=form.cleaned_data["username"], password=form.cleaned_data["password"], ) login(request, user) return redirect("main:homepage") else: print(form.errors) print(form.cleaned_data) return redirect("accounts:login") forms.py from django import forms from django.contrib.auth import get_user_model, authenticate, login from django.contrib.auth.forms import UserCreationForm, AuthenticationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = get_user_model() fields = ['username', 'email', 'first_name'] def save(self): self.clean() user = self.Meta.model( username = self.cleaned_data['username'], email … -
Exception Type: MultiValueDictKeyError at /predict/ Exception Value: 'a'
Exception Type: MultiValueDictKeyError at /predict/ Exception Value: 'a' Code val1 = float(request.GET['a'])