Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to refresh the admin/app view after some time in django
My app has two users, frontend and backend. The frontend user will insert the data and the backend user will check the record of the app in the admin panel. I want to refresh the app view of the admin panel every 10 or so seconds. On the frontend, I can use this script to refresh <script type="text/javascript"> setTimeout(function(){ location = '' },60000) </script> But how do I refresh the backend? I have searched and there are lots of stuff using ajax jquery, and others but I am sorry I am not familiar with any of them. Just want a simple solution. Is it even possible? -
CORS NOT WHITELISTING IP
Python Version 3.8.12 Django Version 3.2.0 Package Version 3.7.0 Description React server is trying to access the resources but it is showing the error as mentioned. Access to XMLHttpRequest at 'https:///api/token/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. -
django deployment using digital ocean Droplets
Can some one help with idea on deploying 2 django apps on one instance of a server using digital ocean droplets or any just idea needed link to issue on github can be found here -
Unable to deploy the ASGI application with channels
Initially, I was using WSGI + gunicorn + nginx (as a load balancer) to deploy my application in a dockerized environment with python 3.9. Now I want to implement channels and socket io in the application. In the development server (using runserver) the ASGI server is running fine. I can connect to both WebSockets and my HTTP endpoints but when I deploy it on the production server with docker + gunicorn + uvicon and nginx to proxy_pass connections to the http://web-app:5000 upstream, it is giving internal server error with the following error logs [2021-12-09 18:53:35 +0000] [105] [ERROR] Exception in ASGI application Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/uvicorn/protocols/http/h11_impl.py", line 373, in run_asgi result = await app(self.scope, self.receive, self.send) File "/usr/local/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__ return await self.app(scope, receive, send) File "/usr/local/lib/python3.9/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/usr/local/lib/python3.9/site-packages/asgiref/compatibility.py", line 34, in new_application instance = application(scope) TypeError: 'tuple' object is not callable And the following is my ASGI server configuration in the myweb.asgi.py file import os from django.core.asgi import get_asgi_application from django import setup os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myweb.settings") setup() http = get_asgi_application(), import routing from channels.routing import ProtocolTypeRouter, URLRouter application = ProtocolTypeRouter({ "http": http, "websocket": URLRouter(routing.websocket_urlpatterns) }) Django … -
Django Rest Framework: validate HiddenField CurrentUserDefault property
I am using DRF to create an API in a single page application. I have a customer user class to which I have only added a is_manager flag and a managerEntity model where users that have the is_manager flag as True can create managerEntities becoming owners of them. The problem is that I can't seem to figure out how to validate the data from the serializer before create method to check whether the is_manager is set or not. If set, the managerEntity should be created, if not, raise an exception. class DeepmetricsUser(AbstractUser): is_manager = models.BooleanField(default=False) class managerEntity(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) team = models.ManyToManyField(get_user_model(), blank=True) views.py class managersEntityViewSet(viewsets.ModelViewSet): queryset = managerEntity.objects.all() serializer_class = managerEntityModelSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): return self.queryset.filter(Q(owner = self.request.user) | Q(team=self.request.user.id)) def create(self, request, *args, **kwargs): serializer = managerEntitySerializer(data=request.data, context={"request": self.request}) serializer.is_valid(raise_exception=True) res = serializer.save() data = managerEntityModelSerializer(res).data return Response(data, status=status.HTTP_201_CREATED) serializer.py class managerEntitySerializer(serializers.Serializer): name = serializers.CharField(max_length=255) owner = serializers.HiddenField(default=serializers.CurrentUserDefault()) def create(self, data): res = managerEntity.objects.create(**data) return res -
How to fetch those products that are belongs to the Offer class and offer is belongs to Product_tab from template in django?
This is my views.py def offers(request): pro_tab = Product_tab.objects.all() for i in pro_tab: for j in i.offer.all(): for k in j.product: print(k.name) context = { 'pro_tab':pro_tab, } return render(request, 'pages/offers.html', context) This is my models.py class Offer(models.Model): offer_name = models.CharField(max_length=100) is_active = models.BooleanField(default=True) def __str__(self): return self.offer_name class Product_tab(models.Model): prod_tab = models.CharField(max_length=100) offer = models.ManyToManyField(Offer) def __str__(self): return self.prod_tab class Product(models.Model): name = models.CharField(max_length=150) is_stock = models.BooleanField(default=True) offer = models.ForeignKey(Offer, on_delete=models.CASCADE) product_for = models.ForeignKey(Product_for, on_delete=models.CASCADE) product_tab = models.ForeignKey(Product_tab, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name This is my html page <section class="offer-section"> <div class="row mx-5 mt-5"> <div class="gallery-filter mb-5"> <ul class="list-unstyled"> <li class="active" data-filter="*">All</li> {% for i in pro_tab %} <li data-filter=".{{ i|lower }}">{{ i|capfirst }}</li> {% endfor %} </ul> </div> <div class="gallery mt-4 mb-5 text-white"> {% for i in pro_tab %} {% for j in i.offer.all %} <div class="col-lg-12 col-md-12 isotope-item {{ i|lower }}"> <div class="active-offer-title py-3 mb-3"> <h3 class="pl-3">{{ j.offer_name }} offer</h3> </div> <div class="row"> {% for k in i.offer.product %} <div class="col-md-3 col-6 mb-3"> <a href="food-details.html" target="_blank" class="text-decoration-none"> <div class="card"> <div class="card-img"> <img src="{% static 'img/offer/o-1.jpeg' %}" class="img-fluid" alt=""> </div> <div class="card-content"> <div class="card-title"> <h5 class="text-center mt-2 mb-0">{{ k.name }}</h5> In my HTML page, all Product_tab are … -
Django Conditional Login Redirect on userType check
I would like to redirect a user to their profile page when they login. I have two user types, typeA and typeB. I have model flags is_typeA and is_typeB to determine the user type. Each type has its own profile template mysite/accounts/typeA/ and mysite/accounts/typeB/<username. I am attempting to call a new view on login, called login_success, this is the code: def login_success(request): """ Redirects users based on their user_type """ if request.user.is_typeA: return redirect("typeA") elif request.user.is_typeB: return redirect("typeB") else: return redirect("home") My urls.py is then: urlpatterns = [ path('login/', LoginView.as_view(), name='login'), path('typeA/<username>/', typeA, name='typeA'), path('typeB/<username>/', typeB, name='typeB'), path('login_success/', login_success, name='login_success')] My settings: LOGIN_REDIRECT_URL = 'login_success' Error I'm getting Exception Type: NoReverseMatch at /accounts/login_success/ Exception Value: Reverse for 'userTypeB' with no arguments not found. 1 pattern(s) tried: ['accounts/userTypeB/(P<username>[^/]+)/$'] -
How to create order form in django with foreign key
Hello I have created an order form where it should add an id to /place-a-order/ like an e-commerce product. Product for example, if I order something it should save the product I ordered I want it to be like this food-deals/id/place-a-order/ in other words when I fill the order So it should tell me which product I ordered in the database/Django-admin Order Form I have no idea how to get the product in database that ordered First I'm showing all products from database to html template def deals(request): my_deals = Deals.objects.all() context = { "Deals": my_deals, } return render(request, 'deals.html', context) and there is my html template {% for fooddeal in Deals %} <div class="col-lg-4 col-md-5"> <a href="{{ fooddeal.pk }}" class="menu-item-card"> <div class="image"> <div> <div></div> <img sizes="100vw" src='{{ MEDIA_URL }}{{fooddeal.deal_img.url }}'> </div> </div> <div class="info"> <h3 class="title">{{ fooddeal }}</h3> <p class="desc ">{{ fooddeal.details }}</p> <h6 class="delivery-time">Ready to dispatch in <span class="text-color-primary">120 mins</span></h6><button type="button" class="deals-btn cta-btn-primary"></button> </div> </a> </div> {% endfor %} then I'm getting customer info def order_now(request): if request.method == 'POST': form = Order_Now(data=request.POST) if form.is_valid(): form.save() return redirect("thank-you/") else: form = Order_Now() return render(request, 'order.html', {"form": form}) Urls.py urlpatterns = [ path('food-deals/', deals, name="food-deals"), path('food-deals/<pk>/', deals_detail, name="deals-details"), path('place-an-order/', … -
Django does not redirect to correct path on password reset
in django password reset, while the path name is password-reset/done/, django redirects me to password_reset/done/ page. No redirects work except password-reset/ also password-reset-confirm not working to. Return /user/reset/done/. user/password-reset/ is working : When POST the form return default django page and the link like this : Return link should be 'password-reset/done/' but return link is : 'password_reset/done/' My user app urls.py from django.contrib import admin from django.urls import path from . import views from django.conf.urls.static import static from django.conf import settings from django.contrib.auth import views as auth_views app_name = "user" urlpatterns = [ path('register/',views.register,name="register"), path('login/',views.loginUser,name="login"), path('logout/',views.logoutUser,name="logout"), path('profile/',views.profileUser,name="profile"), path('password-reset/',auth_views.PasswordResetView.as_view(template_name="password_reset.html"), name="password_reset"), path('password-reset/done/',auth_views.PasswordResetDoneView.as_view(template_name="password_reset_done.html") , name="password_reset_done"), path('password-reset-confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name="password_reset_confirm.html"), name="password_reset_confirm"), path('password-reset-complete/',auth_views.PasswordResetCompleteView.as_view(template_name="password_reset_complete.html"), name="password_reset_complete"), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My Root project urls.py from django.contrib import admin from django.urls import path from django.urls.conf import include from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views from article import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.index, name="index"), path('about/',views.about, name="about"), path('articles/',include("article.urls")), path('user/',include("user.urls")), path('user/', include('django.contrib.auth.urls')), path('contact/',views.contact, name="contact"), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
what is difference between a tag and form action?
I wrote code like that. I want if form is posted, next url got to url home:home. But It doesn't work. It go to default url('account/profile) <form class="form1" method="post" action = "{% url 'login' %}?next={% url 'home:home' %}"> {% csrf_token %} <input type="hidden" name="next" value="{{ next }}" /> Then, I change my code like below. It works well <a href="{% url 'login' %}?next={% url 'ads:all' %}">Login</a> why form doesn't work? below code works well. <p class="sign" align="center">Log In</p> <form class="form1" method="post" action = "{% url 'login' %}"> {% csrf_token %} <input type="hidden" name="next" value="{% url 'home:home' %}" /> -
Django Rest Framework - Nested Serializer Help - Cannot assign OrderedDict
I'm working on creating a nested writeable serializer for my project and I'm running into a road block. I'm following the code snippet here DRF Writeable Nested Serializers but I'm running into this error when I try to send my payload to the API endpoint via postman: Cannot assign "OrderedDict([('first_name', 'Mike'), ('last_name', 'Doe'), ('phone_number', '123-456-7890'), ('company_name', 'Trucking Company')])": "Load.primary_driver" must be a "Driver" instance. Basically, in this specific scenario I need to be able to create a "Load" object (or in other words, shipment object) as well as create a "Driver" object that is associated with the "Load" one POST request. Driver is a FK in the Load model. Models.py (load model is at the end) class Broker(models.Model): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) e_mail = models.EmailField(max_length=50) company_name = models.CharField(max_length=50) phone_number = models.CharField(max_length=50) class Meta: db_table = "Broker" class Employee(models.Model): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) e_mail = models.EmailField(max_length=50) phone_number = models.CharField(max_length=50) class Meta: db_table = "Employee" class Delivery_Location(models.Model): id = models.AutoField(primary_key=True) street_address = models.CharField(max_length=50) city = models.CharField(max_length=30) state = models.CharField(max_length=20) zip_code = models.IntegerField() class Meta: db_table = "Delivery Location" class Pickup_Location(models.Model): id = models.AutoField(primary_key=True) street_address = models.CharField(max_length=50) city = models.CharField(max_length=30) state = models.CharField(max_length=20) … -
How to extract URL text in Django class-based views?
I'm creating a blog to hopefully add to my portfolio and blog about my projects. It was going well until I stumbled across needing to use class-based views and extract URL information to create category pages. Here is my class: class CategoryPage(ListView): model = Post template_name = 'categories.html' ordering = ['-post_date'] def get_context_data(self, *args, **kwargs): cats = self.kwargs['category'] category_posts = Post.objects.filter(category=cats) context = super(CategoryPage, self).get_context_data(*args, **kwargs) context["cat"] = cats context["posts"] = category_posts return context and my urls.py: from django.urls import path, include from .views import HomeView, PostDetailView, CreatePost, UpdatePost, DeletePost, CategoryPage urlpatterns = [ path('', HomeView.as_view(), name="home"), path('post_details/<int:pk>', PostDetailView.as_view(), name='post_details'), path('post_create/', CreatePost.as_view(), name='create'), path('post_edit/<int:pk>', UpdatePost.as_view(), name='edit'), path('post_delete/<int:pk>', DeletePost.as_view(), name='delete'), path('category/category=<str:cats>/', CategoryPage, name='category') ] I've been hacking away at it for a few hours now trying this and that from different posts on here and I can't seem to find anything similar to what I'm facing. Currently I can't stop it from bringing up an error page saying init() takes 1 positional argument but 2 were given. Any help is appreciated thank you! -
Django is not loading media files on shared hosting cPanel
I am having issues loading media files uploaded by the user and displaying them via a template.html file when DEBUG = FALSE. The static files are displayed but I keep getting webaddress/media/images/image1.png 404 Not Found whenever I load the page. I followed some guides and added urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to my urls.py but I am still getting the 404 error. I've chatted with the cPanel hosting provider and they said I do not have access to modify the cPanel Apache httpd.conf file so I am looking to have Django manage the serving of the media files since it handles the uploading of images to the media/images directory. Location where images directory is: /home/<cPanelUserName>/repositories/djangoApp/media/images settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') template/index.html <body style="background: url('{{ background_pic.url }}'); background-size: cover; background-position: center; background-attachment: fixed;"> <div id="profile"> <img id="userPhoto" src="{{ profile_pic.url }}" alt="{{ profile_pic_title }}"> </div> </body> models.py class profilePic(models.Model): title = models.CharField(max_length=50) image = models.ImageField(upload_to='images/') class backgroundPic(models.Model): title = models.CharField(max_length=50) image = models.ImageField(upload_to='images/') views.py def index(request): imageModel = profilePic.objects.get(pk=1) backgroundModel = backgroundPic.objects.get(pk=1) return render( request, "template/index.html", { "profile_pic_title":imageModel.title, "profile_pic":imageModel.image, "background_pic_title":backgroundModel.title, "background_pic":backgroundModel.image, } ) urls.py from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import … -
django cannot convert queryset to list to js array
Using Django I have a view which pulls a queryset and attempting to convert to a list as context to the template which then feeds through to javascript array however it's as if the queryset is not converting to a real list as javascript validation is not accepting the list and thus validation not working. I have also created a normal list rather than from a queryset and works as I expect for my JS validation but everything I have tried in converting the queryset to a list the javascript just will not accept it to the array. I have also tried to convert the list as json as well from what I read online and still not working. I have tried my own for loop on the queryset to append to a new list but also done nothing. Please see the following code: View (manual python list which works tried and tested) mylist= ['sid', 'john'] context = {"mylist": mylist} View (first attempt at converting queryset to list) test = User.objects.values_list('username', flat=True) mylist = list(test) context = {"mylist": mylist} View (second attempt at converting queryset to list to json) test = User.objects.values_list('username', flat=True) mylist= json.dumps(list(test)) context = {"mylist": mylist} Template(with … -
how to load django settings for celery app
This is my tree (hidding all the unnecesary stuff): src/ ├─ api/ │ ├─ app1/ │ │ ├─ tasks.py │ │ ├─ models.py │ ├─ celeryworker/ │ │ ├─ celery.py │ ├─ settings.py │ ├─ urls.py ├─ manage.py ├─ setup.py And then this is my celery.py from __future__ import absolute_import from celery import Celery import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') app = Celery('portal') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() when I am trying to run this app: cd src/api celery -A celeryworker worker --loglevel=INFO I am getting: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. moreover, printing print(app.conf) doesn't seem to be setting any of my CELERY_ settings that I have specified in src/api/settings.py How can I make my celery worker read the Django settings properly? -
How to display multiple Plotly graphs in a HTML webpage? (using plot_div)
I would like to display multiple plotly graphs in a HTML webpage. I tried many codes, but the simplest one I found was this: In my views function, I have: for graphs in res: plot_div = plot(res[graphs], output_type='div') return render(request, '__', context={'plot_div': plot_div, "result": res}) In my HTML, I have: <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>test</title> </head> <body> {% autoescape off %} {{ plot_div }} {% endautoescape %} </body> </html> However, only the last graph is displayed. That's because the variable plot_div is constantly being updated under the for loop. Thus, I tried to create a dictionary like so: plot_div = dict() for index, graphs in enumerate(res, 1): plot_div.update({index: plot(res[graphs], output_type='div')}) return render(request, 'account/user/IndFin/indfin_resultado.html', context={'plot_div': plot_div, "result": res}) Thus, I needed to change the HTML to: {% for graphs in plot_div %} {{plot_div.graphs}} {% endfor %} But, as a result I get, in my webpage, the matrix result and the last graph again. No graphS at all, just the last one. Has anyone faced such problem before? Thanks -
Django/Postgre Docker deployment - Localhost:8000 404 error
I am trying to spin up a Django web application and Postgre database using docker-compose. I am following the steps at https://docs.docker.com/samples/django/ pretty spot on, but I am still getting a 404 error on localhost:8000 after spinning up my docker containers. Any help would be appreciated as to why this is not working. docker-compose.yml: version: "3.9" services: db: image: postgres environment: - POSTGRES_HOST_AUTH_METHOD=trust volumes: - ./data/db:/var/lib/postgresql/data web: build: . command: bash -c "python3.8 manage.py makemigrations && python3.8 manage.py migrate && python3.8 manage.py runserver 0.0.0.0:8000" volumes: - .:/dittoservice-docker ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db Dockerfile: FROM python:3.8 ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 WORKDIR /dittoservice-docker RUN apt-get update RUN pip3 install django RUN pip3 install django-cors-headers RUN pip3 install djangorestframework RUN pip install "ditto.py[all]" RUN pip3 install psycopg2 RUN pip3 install pytz COPY . /dittoservice-docker settings.json DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('POSTGRES_NAME'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': 'db', 'PORT': 5432, } Docker-compose up output: -
New to heroku and publishing websites wanting to know the best plan/dyno-type to choose for large 203mb django website
I have a Django website that I want to publish, the size of the file being pushed to Heroku is 203 Mb (memory quota vastly exceeded when using the free version). I will also require the Heroku app to temporarily store CSV files that can range from 80kb to 10Mb as well as user login information. If anyone could recommend a plan/dyno-type to use that at least meets the storage requirements that'll be greatly appreciated. thank you! -
When i click on the same radio check twice, it changes the output to the opposite, but doesnt change the check
I've got 2 radio checks in a questionaire. If i choose Yes, it will show me certain inputs, and when check set to No it shows me different inputs. The thing is, when i click on Yes twice, check remains on the Yes, but shows me the inputs for 'no'. Do you have any idea why is it like that? This one should show me 'yes' inputs This should show me 'no' inputs Django html: <div class="form-check mt-5"> <h6 class="c-grey-900">Czy masz swoje zwierzę?</h6> <label class="form-check-label mt-2" id="choose-if-animal"> <input class="form-check-input" type="radio" name="has_animal" id="has_animal1" value="yes" > Tak, jestem właścicielem/właścicielką zwierzaka<br> </label> </div> <div class="form-check"> <label class="form-check-label"> <input class="form-check-input" type="radio" name="has_animal" id="has_animal2" value="no"> Nie, nie mam swojego zwierzęcia </label> </div> In views.py its simple: if has_animal == 'yes': has_how_many_animals = all_post_data['has_how_many_animals'] elif has_animal == 'no': animal_type_like = all_post_data.getlist('animal_type_like[]') -
Reverse for "page" with no arguments not found. 1 pattern(s) tried
I started testing and studying Django recently and I'm building some projects to learn and test it. I tried looking for answers in the documentation but was unable to find any, if you can send me the documentation reference to solve this with your solution/tip, I'd appreciate it. I'm trying to pass an argument through the URL in Django, the url changes and the int appears on the browser when redirecting (i.e. http://127.0.0.1:8000/edit-contact/1 - 1 being put dinamically from the "redirecting") but, apparently, the view function can't recognize it. button I'm using to redirect and send the argument <a href="{% url 'edit-contact' contato.id%}" class="btn btn-primary"> Edit contact </a> urls.py file: urlpatterns = [ path('', views.index, name='index'), path('busca/', views.search, name='busca'), path('<int:contato_id>', views.details, name='detalhes'), path('edit-contact/<int:contato_id>', views.edit_contact, name='edit-contact'), ] view function I'm using to capture the request @login_required(redirect_field_name='login') def edit_contact(request, contato_id): if request.method != 'POST': form = ContatoForm() return render(request, 'contatos/detalhes.html', {'form': form, 'contato_id': contato_id}) Traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/edit-contact/1 Django Version: 3.2.9 Python Version: 3.10.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'contatos.apps.ContatosConfig', 'accounts.apps.AccountsConfig'] 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 D:\Gabriel\Codando\studying\django_learning\DjangoProj_agenda\templates\base.html, error at line 0 Reverse for 'edit-contact' with no arguments … -
Django models with reverse field
I have a problem that I seem cant find a solution to it see I have 2 models with a ForeignKey as below : class Transaction(models.Model): chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11, choices=income_period_choices) property_market_rent = models.DecimalField( help_text="Weekly", max_digits=7) class FamilyGroup(models.Model): Transaction= models.ForeignKey(Transaction, on_delete=models.CASCADE, related_name="family_groups") last_rent = models.DecimalField(max_digits=7, decimal_places=2) income_period = models.CharField(max_length=11, choices=income_period_choices) any_income_support_payment = models.BooleanField(null=True, blank=True) @property def rent_charged(self): rent_charged = self.transaction.property_market_rent - self.last_rent now this function is good for only one instance of FamilyGroup, what im trying to do is to Subtract this rent_charged from self.transaction.property_market_rent in the next instance of FamilyGroup, so the next instance of FamilyGroup can have something like : @property def rent_charged(self): rent_charged = self.transaction.property_market_rent - rent_charged #( of the first instance) - self.last_rent Any thoughts would be so appreciated! -
Django composition clean forms don't work correctly
class RegisterForm(forms.ModelForm): ... class Meta: model = CreateUser ... def clean(self, password1, password2, error_key="password"): symbols = ['$', '@', '#', '%', '!'] password1 = self.cleaned_data.get('password') password2 = self.cleaned_data.get('password2') errors = dict() if password1 and password2: if password1 != password2: errors[error_key] = "Passwords do not match" raise forms.ValidationError(errors) if not any(symbol in symbols for symbol in password1): s = ", " errors[error_key] = f"Passwords don\'t have symbols like {s.join(symbols)}" raise forms.ValidationError(errors) if not any(char.isdigit() for char in password1): errors[error_key] = "Password should have at least one numeral" raise forms.ValidationError(errors) if not any(char.isupper() for char in password1): errors[error_key] = "Password should have at least one uppercase letter" raise forms.ValidationError(errors) if not any(char.islower() for char in password1): errors[error_key] = "Password should have at least one lowercase letter" raise forms.ValidationError(errors) return self.cleaned_data class SetPasswordsForm(forms.Form): ... def __init__(self, user, *args, **kwargs): self.user = user self.register = RegisterForm super().__init__(*args, **kwargs) def clean(self): password1 = self.cleaned_data.get('new_password') password2 = self.cleaned_data.get('confirm_new_password') self.register.clean(self, password1, password2, error_key="new_password") return self.cleaned_data I want composition class and function and override this in django, I created my own User, and now i created my own validation but i dont want duplicate code-lines. Why this second function clean don't work correctly? ;/ -
How to encrypt a file with openpgp PGPy - Django python
I am trying to use PGPy for encrypt a zip file. I had a public and private key, but it seems going to dead-end as PGPy decline my keys due to missing required flags.. I already try to bypass require flag as guided from the documentation and still error happen. Also, I sent an issue to its github https://github.com/SecurityInnovation/PGPy/issues/382 Could someone assist me the simple way to perform this? Or maybe there is another way to achieve this? Any positive feedback will be appreciated. Thanks. -
Django select_related the join table only for a many-to-many relation
I have a Django application with a model A with a ManyToManyField bees to model B. For one view, when I select a bunch of A's I also need the ids of their B's. The default where Django queries the related B's for each A individually is too slow, so I use select_related. If I do A.objects.select_related('bees') Django selects the full B models: SELECT ("app_a_bees"."from_a_id") AS "_prefetch_related_val_from_a_id", "app_b"."id", "app_b"."field1", "app_b"."field2", ... FROM "app_b" INNER JOIN "app_a_bees" ON ("app_b"."id" = "app_a_bees"."to_b_id") WHERE "app_a_bees"."from_a_id" IN (... list of A ids ...) But I only need their id values, so I only need to select the app_a_bees join table to get them, not the B model table. I tried A.objects.select_related('bees__id') (I also tries 'bees_id') but Django doesn't like that, individual fields cannot be prefetched in this way. I have also tried A.objects.select_related(Prefetch("bees", queryset=B.objects.all().only("id")), but that still joins to the B table to select the id field, which Django already has from the join table. Is there any way to prefetch just the join table for my A objects? -
i have two groups, 'client' and 'worker'.. when i register a client everything is fine but for a worker he gets assigned to both groups
i have two groups, 'client' and 'worker'.. when i register a client everything is fine but for a worker he gets assigned to both groups. i need everyone to be assigned to their specific group Signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.contrib.auth.models import Group from .models import Worker,Client def client_profile(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='client') instance.groups.add(group) Client.objects.create( user=instance, name=instance.username, ) print('Profile created!') post_save.connect(client_profile, sender=User) def worker_profile(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='worker') instance.groups.add(group) Worker.objects.create( user=instance, name=instance.username, ) print('profile created!') i have two groups, 'client' and 'worker'.. when i register a client everything is fine but for a worker he gets assigned to both groups. i need everyone to be assigned to their specific group views.py @unauthenticated_user def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + username) return redirect('login') context = {'form': form} return render(request, 'users/register.html', context) def workerRegister(request): if request.user.is_authenticated: return redirect('plumber_home') else: form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success( request, 'Account was created for ' + username) return redirect('worker_login') context …