Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Why does database login every query?
In my settings.py, I have a database configured. I have a page that issues a sql query against the database defined in settings.py every 10 seconds. I have been using it for 1 year now and never had any issues with it. My database admin ran a login audit on our database. As it turns out, each individual single sql query has a unique login to the database. His audit took 5 minutes to run just today and it is because of my django application logging in. I was pretty surprised to find out that every query that is issues has a unique login attempt to the database. Is there anyway to create a "session" for the backend database in settings.py. I really feel that the application should have a single login and use that session to issue commands. Did I miss a setting to do this? Sql login audit: -
Amazon RDS: OperationalError: (2003, "Can't connect to MySQL server on rds.amazonaws.com (110)"
I have set up a MySQL database and I'm trying to connect it with my application. But I'm getting the above error. My database settings in settings.py are as follows: DATABASES = { 'default': { 'ENGINE': config('db_engine'), 'NAME': config('db_name'), 'USER': config('db_user'), 'PASSWORD': config('db_password'), 'HOST': config('db_host'), 'PORT': config('db_port') } } and my database environment variables are these: db_engine=django.db.backends.mysql db_name=stagingdatabase db_user=staginguser db_password=stagingpassword db_host=somestagingname.somestagingid.us-east-2.rds.amazonaws.com db_port=3306 I know the port is correct, which is the solution for most cases of these types of errors. All other variables are correct as well. I can't ping somestagingname.somestagingid.us-east-2.rds.amazonaws.com even though it's status is available, so there must be an issue in this: -
calculate difference between consecutive numbers in rows af the same model
I am trying to calculate the difference between consecutive numeric values in the odometer_reading field of my model. My Models.py has fields like below: class Refuel(models.Model): vehicle = models.ForeignKey(Vehicle, blank=True, null=True, on_delete=models.SET_NULL) gaz_station = models.ForeignKey( GazStation, related_name=_("Station"), blank=True, null=True, on_delete=models.SET_NULL ) odometer_reading = models.PositiveIntegerField(_("Compteur KM"), blank=True, null=True) snitch = models.PositiveIntegerField(_("Mouchard KM"), blank=True, null=True) fuel_quantity = models.DecimalField(_("Quantitée en Litres"), max_digits=5, decimal_places=1) fuel_unit_price = models.DecimalField(_("Prix en DH"), max_digits=6, decimal_places=2) note = models.CharField(_("Remarque"), max_length=255, blank=True, null=True) created_at = models.DateTimeField(_("Created at"), auto_now_add=True, editable=False) updated_at = models.DateTimeField(_("Updated at"), auto_now=True) is_active = models.BooleanField(default=True) @property def total_price(self): total_price = self.fuel_quantity * self.fuel_unit_price return total_price class Meta: ordering = ["gaz_station", "-created_at"] def __str__(self): return self.vehicle.serie I want to use a CBV to get the distance between every two refuel for the same vehicle so I can calculate fuel consumption per km. is there a way to do it? -
calling from browser to phone - django
I am working on an app using Django, I want my users to call clients using the app just by clicking on the call button and then the clients receive the call on their phone, I want you to suggest to me the first steps I have to follow. thank you, I will really appreciate your help and guide. -
How to save celery task to a temporary db which will then be updated to the master db
What is a good way to compare new data with old data which is updated everyday with Django ORM? Basically I have a scraper which fetches hackathons everyday (basically just a celery task) and I want the newest to be unioned it with my master database which has the latest fetched hackathons from yesterday. I don't want to destroy my master database and then just upload everything that I just fetched since that seems wasteful. -
I am getting a pre-receive hook declined when trying to push to heroku
I am trying to push my python/django project to heroku for deplyment but I keep getting ! [remote rejected] master -> master (pre-receive hook declined) . not sure why is this happening ? I have tried deleting and starting over but nothing happened, any ideas please ?! -
import error in parallel folders python django cant be fixed with PYTHONPATH
django structure this is my django structure I am trying to import "home_view" function from Pages APP to main urls in "Kianwoodco" project these statements seem to be not working from ..Pages.views import home_view from src.Pages.views import home view also importing views is giving out the same error as result errors : no module name 'src' attempted relative import beyond top-level package any help would be appreciated I have tried sys.path.append("#path to Pages") and adding init.py to src -
How to use jQuery to find balance from Debit and Credit in Django row table
Please help, i have my Django app where i have row table where fetch numbers from database and it work correctly, i have one problem i want to calculate balance by taking balance plus debit side and minus credit side by using jquery but refer what i get in a link plus what i expect. Note: I failed to use django itself because balance doesn`t saved to database What i get: [https://paste.pics/DW7TA] Expected: [https://paste.pics/DW7WP] javascript < script > $(document).ready(function() { $('tr').each(function() { var balance = []; $(this).find('#col1').each(function() { var bal = $(this).text(); if (bal.length !== 0) { var bala = $("#balance").text(); balance = bal + bala } }); $(this).find('#col2').each(function() { var bal = $(this).text(); if (bal.length !== 0) { var bala = $("#balance").text(); balance = bala - bal } }); $(this).find("#balance").html(balance); }); }); < /script> html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <th>DR</th> <th>CR</th> <th>BALANCE</th> </tr> {% for statement in customer_stat %} <tr style="margin-top: 20px; font-size: 25px; margin-left: 90px;"> <td class="col" id="col1">{{statement.total_amount}}</td> <td class="col" id="col2">{{statement.to_amount}}</td> <td id="balance"></td> </tr> {% endfor %} </table> -
django project : static directory not available in docker
i'm working on a personal project, basic webapp, which is working fine locally. /home/mxp/DOCKER/django_cv/django/venv/bin/gunicorn my_cv.wsgi --bind 0.0.0.0:8000 -e "DEBUG=1" -e "SECRET_KEY=****" -e "DJANGO_ALLOWED_HOSTS=localhost 127.0.01" [2021-09-16 20:50:13 +0200] [560882] [INFO] Starting gunicorn 20.1.0 [2021-09-16 20:50:13 +0200] [560882] [INFO] Listening at: http://0.0.0.0:8000 (560882) [2021-09-16 20:50:13 +0200] [560882] [INFO] Using worker: sync [2021-09-16 20:50:13 +0200] [560884] [INFO] Booting worker with pid: 560884 now i run the same image with my Dockerfile as follow FROM python:3.8 RUN apt-get update RUN mkdir /usr/src/app RUN useradd -U django RUN mkdir /home/django && chown django:django /home/django USER django ENV MICRO_SERVICE=/usr/src/app/django COPY . $MICRO_SERVICE WORKDIR $MICRO_SERVICE ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV PATH=$PATH:/home/django/.local/bin RUN pip install --upgrade pip RUN pip install -r requirements.txt WORKDIR /usr/src/app/django/my_cv% And i have this not found message : sudo docker run -p 80:8000 7484050feceb gunicorn my_cv.wsgi --bind 0.0.0.0:8000 -e "DEBUG=1" -e "SECRET_KEY=****" -e "DJANGO_ALLOWED_HOSTS=localhost 127.0.01" [2021-09-16 19:10:04 +0000] [1] [INFO] Starting gunicorn 20.1.0 [2021-09-16 19:10:04 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1) [2021-09-16 19:10:04 +0000] [1] [INFO] Using worker: sync [2021-09-16 19:10:04 +0000] [8] [INFO] Booting worker with pid: 8 Not Found: /static/cv/custom.css Not Found: /static/cv/me.jpg I know that this is not the best way, and that i should use an nginx … -
vuejs + django passwordreset email and redirect to vue front end
I am trying to implement a password reset by sending the email to users using Django in the backend and vue in the frontend (both work on different IP addresses). I tried by using the package django-rest-passwordreset and the steps provided by (Django REST-Auth Password Reset and https://newbedev.com/django-rest-auth-password-reset) its not clear what is vuedj.constant and how they are importing site_url, site_full_name, site_shortcut_name from vuedj.constants. I even tried by custom based ResetPasswordEmailRequestSerializer and SetNewPasswordSerializer I am able to get email by using these, but not able to redirect to frontend or get uidb64 and token for the specific user in the frontend. serializers.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from rest_framework.exceptions import AuthenticationFailed from django.utils.encoding import force_str from django.utils.http import urlsafe_base64_decode class ResetPasswordEmailRequestSerializer(serializers.Serializer): email = serializers.EmailField(min_length=2) redirect_url = serializers.CharField(max_length=500, required=False) class Meta: fields = ['email'] class SetNewPasswordSerializer(serializers.Serializer): password = serializers.CharField( min_length=6, max_length=68, write_only=True) token = serializers.CharField( min_length=1, write_only=True) uidb64 = serializers.CharField( min_length=1, write_only=True) class Meta: fields = ['password', 'token', 'uidb64'] def validate(self, attrs): try: password = attrs.get('password') token = attrs.get('token') uidb64 = attrs.get('uidb64') id = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(id=id) if not PasswordResetTokenGenerator().check_token(user, token): raise AuthenticationFailed('The reset link is invalid', 401) user.set_password(password) user.save() return (user) except Exception as e: raise AuthenticationFailed('The reset link is … -
Is it possible to use gunicorn for my Django app inside a WSL Ubuntu system?
I am working on a Windows 10 machine using Ubuntu inside WSL. I did this because I cannot get gunicorn to work as I've researched it is not available in Windows. I can successfully run my app using my docker-compose file within my WSL Ubuntu perfectly fine. I then run the gunicorn myapp.wsgi command and the server spins up with the terminal giving me the following output: [2021-09-16 19:11:53 +0000] [25] [INFO] Starting gunicorn 20.1.0 [2021-09-16 19:11:53 +0000] [25] [INFO] Listening at: http://127.0.0.1:8000 (25) [2021-09-16 19:11:53 +0000] [25] [INFO] Using worker: sync [2021-09-16 19:11:53 +0000] [26] [INFO] Booting worker with pid: 26 However, I cannot connect to my site at localhost:8000. I also did a curl request against the localhost:8000 from inside my docker container and got a 302 error. I've researched using gunicorn, mod_wsgi and uwsgi, all given as options in the Django documentation. However, I want to use gunicorn or uwsgi to have access to either nginx or Apache (plus the documentation on mod_wsgi has a dead link for the windows install file). Does anyone have suggestions on how I can get this to work? -
Django NoReverseMatch at logout function error
I am encountering such an error in the logout part of my Django project. I tried many ways with examples I searched on the internet, but the error does not go away. layout.html {% 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"> <title>Layout</title> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <!-- <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script> --> <link href="https://use.fontawesome.com/releases/v5.0.6/css/all.css" rel="stylesheet"> </head> <body> {% block content %} {% endblock %} <script src="{% static 'js/popper.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/jquery-3.6.0.min.js' %}"></script> dash.html {% extends 'layout.html'%} {% load static %} {% block content %} <div class="sidebar-container"> <div class="sidebar-logo"> Ox.v1 </div> <ul class="sidebar-navigation"> <li> <a href="#"> <i class="fa fa-home" aria-hidden="true"></i>Anasayfa </a> </li> <li> <a href="#"> <i class="fas fa-chart-line"></i> Dashboard </a> </li> <li> <a href="#"> <i class="fas fa-phone-volume"></i> Infotmation </a> </li> <li> <a href="#"> <i class="fas fa-adjust"></i> Users </a> </li> <li> <a href="{% url 'logout_view' %}"> <i class="fas fa-outdent"></i> Exit </a> </li> </ul> </div> {% endblock %} views.py from django.shortcuts import render from django.db import connections from django.shortcuts import redirect, render from django.http import HttpResponse,HttpResponseRedirect from django.contrib.auth.decorators import user_passes_test from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User … -
Is there a downside of redirecting to another view rather than returning it directly?
I've built a hardcoded target_url to use it as redirect argument to trigger another view. I could also return this view directly, but I want the user to have the specific url in the browser address field. Is there any downside to call the other view directly other than having a different url than desired? I don't think that Version 1 is common practice: # Version 1 def view_one(request): [..] target_url_view_two = '/poller/' + str(random_poller_id) + '/' return redirect(target_url_view_two, request, random_poller_id) # Version 2 def view_one(request): [..] return view_two(request, random_poller_id) -
most of my calculations in the views.py, how to clean or do correctly?
i have some calculations that help me find total amounts for teachers earnings. made from the ammount of lessons they have, their rate, their costs, etc. where is this meant to go as im sure its not in the correct place and could be a lot more efficient? i thought about making some of the work in the models.py as an @property but not sure how to or even if it is that nessecary. any help is appreciated, thank you. def accounts(request): lessons=Lessons.objects.all() basic_band= lessons.filter(price_band="BASIC") top_band=lessons.filter(price_band="TOP") native_band=lessons.filter(price_band="NATIVE") basic_count=basic_band.count() top_count=top_band.count() native_count=native_band.count() native_house_rate =0.25 top_house_rate =0.30 basic_rate=300 top_rate=400 native_rate=700 ##earnings basic_earning= basic_count * basic_rate top_earning= top_count * top_rate native_earning= native_count * native_rate ##fees native_house_fee=native_earning * native_house_rate top_house_fee=top_earning * top_house_rate ##totals total_top = top_earning - top_house_fee total_native = native_earning - native_house_fee total_earning= total_top + total_native total_gross_earning=top_earning + native_earning monthly_top= total_top * 4 monthly_native= total_native * 4 monthly_total= monthly_top + monthly_native context{"total_gross":total_gross_earning,"native_number":native_earning, "top_number":top_earning,"basic_number":basic_earning, "basic":basic_count, "top":top_count,"native":native_count, "native_fee":native_house_fee, "top_fee":top_house_fee, "top_rate":top_rate, "native_rate":native_rate, "basic_rate":basic_rate,"total":total_earning, "native_house_rate":native_house_rate,"top_house_rate":top_house_rate, "total_top":total_top, "total_native":total_native, "monthly_top":monthly_top, "monthly_native":monthly_native,"monthly_total":monthly_total} return render(request, "accounts.html", context) -
Is it possible to do a doctest on a Django model method (validate_unique)
I have a Django model where I've overridden validate_unique(). I want to add a doctest to test against the exception I throw if the object being saved isn't sufficiently unique (and not itself). That works fine (e.g., in the Admin creating a degenerate object throws and error as does changing an existing record such that it isn't unique; changing a record's other fields that aren't involved in the uniqueness saves properly). I've read the docs on doctests, but I can't find an example to use in the case where the method is within a Django model class, to wit: class MyModel(models.Model): def validate_unique(self, *args, **kwargs): """ >>> validate_unique(???) Traceback (most recent call last): ... ValidationError: Parameter with this as_of_date + slug + facility combination already exists. """ (working code here) Any pointers to relevant documentation (since I failed to find anything) or a code snippet would be greatly appreciated. -
Django model manytomany field count occurrence
models.py class Region(models.Model): name = models.CharField(blank=False, unique=True) count = models.IntegerField(blank=True, null=True) # This should be the occurrence count in ETF class ETF(models.Model): ticker = models.CharField() region = models.ManyToManyField(Region, blank=True) Example: If there is 100 ETF objects in ETF model have U.S.A. as region, then count field in U.S.A. object in Region model should be 100. How do I automatically update the count field in Region Model everytime there are changes in the database? Sorry if there is duplicate question, I just can't find the keywords to search for the solution. -
TypeError: Object of type QuerySet is not JSON serializable
I get this error when I try to delete an object from the database: Object of type QuerySet is not JSON serializable My views.py @action(['PUT'], detail=False, url_path='remove_meal/(?P<meal_slug>\w+)') def remove_meal(self, *args, **kwargs): restaurant = Restaurant.objects.get(owner=self.request.user.restaurateur) meal = get_object_or_404(Meal, slug=kwargs['meal_slug']) restaurant.meals.remove(meal) meal.delete() restaurant.save() return response.Response(status=status.HTTP_204_NO_CONTENT) My models.py class Meal(models.Model): """Meal""" title = models.CharField(max_length=255) description = models.TextField(default='The description will be later') price = models.DecimalField(max_digits=9, decimal_places=2) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null=True) slug = models.SlugField() class Restaurant(models.Model): """Restaurant""" name = models.CharField(max_length=255) slug = models.SlugField() address = models.CharField(max_length=1024) owner = models.ForeignKey('Restaurateur', on_delete=models.CASCADE, null=True) @property def meals(self): return json.dumps(Meal.objects.filter(restaurant=self).values()) How can i solve this problem? I think i need to add field meals in my restaurant model, but how can i do it? -
The view searchapp.views.searchresult didn't return an HttpResponse object. It returned None instead
shopapp models.py from django.db import models # Create your models here. from django.urls import reverse class catagory(models.Model): name=models.CharField(max_length=250,unique=True) slug=models.SlugField(max_length=250,unique=True) description=models.TextField(blank=True) image=models.ImageField(upload_to='catagory',blank=True) class Meta: ordering=('name',) verbose_name='catagory' verbose_name_plural='catagories' def __str__(self): return '{}'.format(self.name) def get_url(self): return reverse('shop:product_by_catagory',args=[self.slug,]) class product(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) image = models.ImageField(upload_to='product', blank=True) price=models.DecimalField(max_digits=10,decimal_places=2) stock=models.IntegerField() available=models.BooleanField() created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) catagory=models.ForeignKey(catagory,on_delete=models.CASCADE) class Meta: ordering = ('name',) verbose_name = 'product' verbose_name_plural = 'products' def __str__(self): return '{}'.format(self.name) search app views.py from django.shortcuts import render from shop.models import product from django.db.models import Q # Create your views here. def searchresult(request): products=None query=None if 'q' in request.GET: query=request.GET.get('q') products=product.objects.all().filter(Q(name__contains=query) | Q(description__contains=query)) return render(request,'search.html',{'query':query,'products':products}) searchapp urls.py from django.urls import path from . import views app_name='searchapp' urlpatterns=[ path('',views.searchresult,name='searchresult',) ] catagory.html {% extends 'base.html' %} {% load static %} {% block metadiscription %} {% if catagory %} {{catagory.description|truncatewords:155 }} {% else %} welcome {% endif %} {% endblock %} {% block title %} {% if catagory %} {{catagory.name}}--ABC store {% else %} see our new collection {% endif %} {% endblock %} {% block content %} {% if catagory %} <div> <div class="row my_row_class"> <div class="mx_auto"> <a href="{% url 'shop:allproductcat' %}">OUR PRODUCT COLLECTION</a> </div> </div> </div> {% endif %} <div> … -
Django Sending Email Alerts on only new alerts
I am trying to send email alerts for all new alerts that have just been created. I have tried last_alert = Alert.objects.filter(kiosk=kiosk).last() But that only gets the last alert and it triggers the same one all the time. It is possible to have 3 alerts be triggered at once. I am trying to implement a flag to know whether or not an alert has been sent. I'm probably using latest wrong here. last_alert = Alert.objects.filter(kiosk=kiosk).latest('pk') if last_alert.created_on: alert_status = HTTP_208_ALREADY_REPORTED send_alert_email = False else: alert_status = HTTP_201_CREATED send_alert_email = True last_alert.created_on = datetime.now(last_alert.kiosk.location.timezone) Alert.create(kiosk=kiosk, created_on=datetime.now(last_alert.kiosk.location.timezone)) last_alert.save() # Get Timezone aware date and time current_dt = datetime.now().astimezone(kiosk.location.timezone) current_time = current_dt.strftime('%I:%M %p') current_date = current_dt.strftime('%m/%d/%Y') email_props2 = { 'method': 'EMAIL', 'email': 'john@example.com', 'data': { 'facility': last_alert.kiosk.location.name, 'description': last_alert.description, 'pk': last_alert.pk, 'time': current_time, 'date': current_date, 'kioskName': kiosk.name, 'alert_type_display': last_alert.alert_type_display } } if send_alert_email: _send_email( [email_props2['email']], {'data': email_props2['data']}, ALERT_TEMPLATE_ID ) Maybe I am approaching this problem wrong with the flag. Any help is very much appreciated. thanks in advance -
JobPost' object has no attribute 'job_type'
I have simple view to create custom jobs and post them on a job_portal, but I am getting the below-mentioned error, I am working with many-to-many fields and have gone through the docs, set method is not working it seems, I have posted the trace as well, but its pointing to the strange error, foreign that it is mentioning is already set to null, thanks in advance def create_job(request): company_ = Company.objects.values_list('name', flat=True) if request.method == 'POST': # getting company by name for reference job_title = request.POST['job_title'] company_name = request.POST['company_name'] company = get_object_or_404(Company, name__iexact=company_name) address = request.POST.get('street_addr') city = request.POST['city'] state = request.POST['state'] country = request.POST['country'] zip_ = request.POST.get('zip_code') skill_names = request.POST.getlist('skill_name') start_salary = request.POST.get('salary_start') end_salary = request.POST.get('salary_end') # create job skills if not already present inside DB print(skill_names) skill_list = [] for skill in skill_names: skill_nam, created = Skillset.objects.get_or_create(skill_name__iexact=skill,defaults={ 'skill_name' : skill }) skill_list.append(skill_nam) job_loc = JobLocation(address=address, city=city, state=state, country=country, zip_code=zip_) job_loc.save() job_descrip = request.POST['job_descrip'] job_skill_ = request.POST.getlist('job_skill_level') job_pst = JobPost(title=job_title, cmpny_name=company, job_description=job_descrip, salary_start=start_salary,salary_end=end_salary) job_pst.job_posters.set(request.user) <--- i am getting error here job_pst.save() #skill_list has skill names job_skill_set = [] for job_skill_name, job_level in zip(skill_list, job_skill_): skil_set = Skillset.objects.filter(skill_name=job_skill_name) job_skillset = Job_Skillset(job_post=job_pst, skill_level=job_level) job_skillset.skill.set(skil_set) job_skill_set.append(job_skillset) Job_Skillset.objects.bulk_create(job_skill_set) messages.add_message(request,messages.SUCCESS,'Job post successfully submitted!') … -
how to detect unhandled Exception without try statement
when integrate sentry with django, sentry detect unhandle Exceptions and capture them Sentry's Django integration enables automatic reporting of errors and exceptions. Sentry's Django integration reports all exceptions leading to an Internal Server Error and creates a separate scope for each request. The integration supports Django Web Framework from Version 1.6 and above. Django applications using Channels 2.0 will be correctly instrumented using Python 3.7. Older versions of Python require installation of aiocontextvars. but my question: how can i detect unhandle Exceptions and send it to sentry in pure python script? -
How to run a function with parameters periodicaly?
I have a form(DashboardData model) on my system that each user fills out. In this form, we are asking for a username, password, and a range to update for another system. Options in this range are once a week, once a month, and once a year. Depending on which interval the user selects, I will run a function at those intervals. In this function, I will get the username and password from the form filled by the user as parameters. For example in form username, password, once a week is selected then I have to run myFunction(username, password) once a week. I try to use apscheduler for this. But in apps.py I can not reach request.user, so, I cannot get the data. I have to take request.user for running my function. forms.py class SetupForm(forms.ModelForm): # Time PERIOD = ( ('168', 'Once a week'), ('720', 'Once a month'), ('8766 ', 'Once a year'), ) n_username = forms.CharField() n_password = forms.CharField(widget=forms.PasswordInput) period = forms.CharField(max_length=200, widget=forms.Select(choices=PERIOD))) class Meta: model = DashboardData fields = ('n_username', 'n_password','period') models.py class DashboardData(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True) # request.user n_username = models.CharField(max_length=250) n_password = models.CharField(max_length=250) period = models.CharField(max_length=250) functions.py class myFunction(): def __init__(self, n_user, n_password): self.time = … -
How to show a error on client side after validation on server side in django
I am fairly new to django. I want to check user entered value for the price value input in my web page, against all values in my existing database while doing server side validation. I am using django forms. my database have fields called "name" and "price". I want add user input to data base if user entered price value is larger than the all existing price values in my database. otherwise i want to show an error on the client side like "enter a larger value". This is what I have came up with so far. This is my form in views.py class myform (forms.Form): name = forms.CharField(max_length = 200) price= forms.IntegerField( validators = [MinValueValidator(0,0)], widget=forms.NumberInput(attrs={'min' : 0})) I am trying to validate it in here def add_item (request): if request.method == "POST": max_price = items.objects.order_by("-price").first().price if request.POST["price"] < max_price: return render(request,"myapp/items.html") else: items.objects.create(name = request.POST["name"] , price = request.POST["price"]) return render(request,"myapp/index.html") I tried to use validators to show message on the client side but it was not succefull. because I couldn't figured out how to use database entries in validation methods to raise validation errors. -
How to transform JavaScript filter function to Django Python?
I have the following filter function on JavaScript and I need to do the same on Django. This is my JavaScript function: absentAttendees() { return this.meeting.attendees.filter((element) => this.timeAttendees(element.user.id) <= 0 || (element.absent && this.timeAttendees(element.user.id) <= 0)); } timeAttendees(user) { let timeUser = 0 this.meeting.meeting_times.forEach((time) => { if (time.user.id === user) { timeUser = timeUser + time.time } }) return timeUser } Here is what I have so far on Django, but it tells me that the object I'm passing doesn't have the attribute 'user' meeting.attendees.all().filter(timeAttendees > 0) def timeAttendees(item): timeUser = 0 for time in time_list: if(time.user.id == item.user.id): timeUser = timeUser + time.time return timeUser -
Getting KeyError from views in get_context_data() while accessing urlpatterns
So I upgraded from django 2.2 to 3.2. Did NOT face this issue when using django 2.2, but after the upgrade to django 3.2 I'm getting KeyError from the get_context_data() function while accessing the urlpatterns. All the urlpatterns are defined using re_path() in urls.py. The URL parameters are being accessed using get_context_data(self, **kwargs) from the view mixin class using self.kwargs. As per Django 3 change logs (https://docs.djangoproject.com/en/3.2/releases/3.0/#miscellaneous): RegexPattern, used by re_path(), no longer returns keyword arguments with None values to be passed to the view for the optional named groups that are missing. While investigating this issue I rolled back to django 2.2 to check on the context data from the view and could see that the required Key in the self.kwargs dict was set to None which is as expected. Is there any way to return keyword arguments with None values to the views in django 3.2? Really appreciate some help in getting around this! I'm unable to post the entire code, sorry. Do ask me for more info if required! Thanks.