Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to return Boolean from jQuery plugin to html?
I am currently working on a password strength meter that provides real-time update to the user via onkeyfocus event. I have decided to use https://github.com/elationbase/jquery.passwordRequirements for this purpose. Currently I am trying to return a Boolean from the jQuery plugin to my html so that I could check if the user input password has met the requirement completely. If it does not, to prevent them from further continuing in whatever they are doing. Below is what I have came up with so far. My question is how can I pass the var is_passed back to the html? jQuery Plugin (function($){ $.fn.extend({ passwordRequirements: function(options) { // options for plugin var defaults {...}; options = $.extend(defaults, options); var is_passed = false; // the variable that I wish to return return this.each(function() { ... //skipping all the checks $(this).on("keyup focus", function(){ var thisVal = $(this).val(); if (thisVal !== '') { checkCompleted(); if (is_passed === true) { console.log('is_passed', is_passed); return is_passed; } } )}; HTML <script> $(document).ready(function () { $('.pr-password').passwordRequirements({}); var is_passed = $('.pr-password').passwordRequirements({}); //not working as it returns an Obj }); </script> -
edit post always going to the same pk in url django
im making a social media app in django im setting up the edit post option at the home page but im getting a problem that in the for loop each post's edit option points to a same posts pk for example if the edit option of post 2 or post 3 is clicked, it still goes to the edit page of post 1. views.py class EditPostView(UpdateView): model = Post form_class = EditPostForm template_name = "edit_post.html" home page {% for post in object_list %} <div class="flex flex-wrap -m-4"> <div class="p-4 md:w-2/5"> <div class="h-full border-2 border-gray-200 border-opacity-60 shadow-lg rounded-md overflow-hidden"> <img class="w-full object-cover object-center " src="{{post.image.url}}" alt="blog"> <div class="p-6"> <h2 class="tracking-widest text-xs title-font font-medium text-gray-400 mb-1">{{post.hashtag}} </h2> <h1 class="title-font text-lg font-medium text-gray-900 mb-3">@{{post.user.username}} </h1> <p class="leading-relaxed mb-3"><span class="font-medium font-bold mr-2">{{post.user.username}}</span> {{post.caption}} </p> <div class="flex items-center flex-wrap "> <div class="inline-flex items-center md:mb-2 lg:mb-0"> <span class="mr-3 inline-flex items-center lg:ml-auto md:ml-0 ml-auto leading-none text-sm pr-3 py-1"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-suit-heart-fill w-4 h-4 mr-1" viewBox="0 0 16 16"> <path d="M4 1c2.21 0 4 1.755 4 3.92C8 2.755 9.79 1 12 1s4 1.755 4 3.92c0 3.263-3.234 4.414-7.608 9.608a.513.513 0 0 1-.784 0C3.234 9.334 0 8.183 0 4.92 0 2.755 1.79 1 4 1z" /> … -
Image not getting updated/replaced in CRUD
I am doing CRUD operation which also has image, I am unable to replace the image in the update operation with another image, the previous image remains, please help below is my update function def update(request,id): if request.method == 'GET': print('GET',id) editclothes = Products.objects.filter(id=id).first() s= POLLSerializer(editclothes) category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict, many=True) sub_category_dict = SUBCategories.objects.filter(isactive=True) sub_category = SUBCategoriesSerializer(sub_category_dict,many=True) color_dict = Colors.objects.filter(isactive=True) color = ColorsSerializer(color_dict,many=True) size_dict = Size.objects.filter(isactive=True) size = SizeSerializer(size_dict,many=True) hm = {"context": category.data,"sub_context":sub_category.data,"color_context":color.data,"size_context":size.data,"Products":s.data} return render(request, "polls/product_edit.html", hm) else: print('POST',id) editclothes = {} d = Products.objects.filter(id=id).first() if d: editclothes['categories']=request.POST.get('categories') # print('categories is equal to:',editclothes['categories']) editclothes['sub_categories']=request.POST.get('sub_categories') editclothes['color']=request.POST.get('color') editclothes['size']=request.POST.get('size') editclothes['title']=request.POST.get('title') editclothes['price']=request.POST.get('price') editclothes['sku_number']=request.POST.get('sku_number') editclothes['gender']=request.POST.get('gender') editclothes['product_details']=request.POST.get('product_details') editclothes['quantity']=request.POST.get('quantity') if len(request.FILES)!=0: if len(d.image)>0: os.remove(d.image.path) editclothes['image']=request.FILES['image'] form = POLLSerializer(d,data=editclothes) if form.is_valid(): form.save() print("data of form",form.data) messages.success(request,'Record Updated Successfully...!:)') return redirect('polls:show') else: print(form.errors) print("not valid") return redirect('polls:show') below is my product_edit html <form method="POST" > {% csrf_token %} <table> <thead> <tr> <td>Categories</td> <td> <select name="categories" id=""> {% for c in context %} {% if c.id == Products.categories %} <option value="{{c.id}}" selected></option> {% endif %} <option value="{{c.id}}">{{c.category_name}}</option> {% endfor %} </select> </td> </tr> <tr> <td>Sub-Categories</td> <td> <select name="sub_categories" id=""> {% for c in sub_context %} {% if c.id == Products.sub_categories %} <option value="{{c.id}}" selected></option> {% endif %} <option … -
imshow() got an unexpected keyword argument 'hover_data'
def staff_activity_view(request, pk): staff = get_object_or_404(User, pk=pk) staff_activity = StaffActivity.objects.filter(user_id=staff.id) now = timezone.now() start = now - timezone.timedelta(days=364) daterange = date_range(start, now) counts = [[] for i in range(7)] dates = [[] for i in range(7)] day_names = list(calendar.day_name) first_day = daterange[0].weekday() days = day_names[first_day:] + day_names[:first_day] for dt in daterange: count = staff_activity.filter(timestamp__date=dt).count() day_number = dt.weekday() counts[day_number].append(count) dates[day_number].append(dt) fig = px.imshow( counts, color_continuous_scale='Blues', x=dates[0], y=days, # hover_data=['count', 'date', 'day'], height=300, width=900, title='Staff Activity', ) fig.update_layout( plot_bgcolor='white', paper_bgcolor='white', # xaxis_title='Date', yaxis_title='Activity', ) fig.update_traces( xgap=5, ygap=5, ) chart = fig.to_html() return render(request, 'gym_admin/chart.html', {'chart': chart}) What I wanted to change is the label color on hover, if I add hover_data directly, getting the above error. Tried the following solution but still the labels are same hover_text = [f'{day} {date.strftime("%d %b %Y")} {color}' for day, date in zip(days, dates[0]) for color in counts[0]] fig.update_traces(text=hover_text) Labels currently I am getting are x, y and color, looking for a solution, thank you -
Linkify Foreign Keys with Django Tables2 and Slugs
I am trying to build summary tables with clickable links that drill down to lower levels. The hierarchy in descending order is Division -> Region -> Branch -> Profit Center where each profit center can have multiple "receivables." I want the division summary view to show all of the regions (e.g. California, Central Texas, Ohio, etc) and a sum of the 'total_amount' for the regions. I want to be to click a region and it drills down to the branches where I can see a summary for each branch. So on and so forth I've spent far longer than I would like to admit on this and the lines commented out on tables.py is just a fraction of what I have tried. What am I missing? class Division(models.Model): name = models.CharField(max_length=128, unique=True) slug = models.SlugField(unique=True, null=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('division-detail', args=[str(self.slug)]) class Region(models.Model): name = models.CharField(max_length=128, unique=True) division = models.ForeignKey('Division', to_field='name', on_delete=models.CASCADE) slug = models.SlugField(unique=True, null=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('region-summary', args=[str(self.slug)]) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) super().save(*args, **kwargs) class Branch(models.Model): name = models.CharField(max_length=128) number = models.CharField(max_length=4, unique=True) region = models.ForeignKey('Region', to_field='name', on_delete=models.CASCADE) slug = models.SlugField(unique=True, null=True) def … -
Payfort Error code 00013 invalid currency
I was trying to make a request to Payfort API using python: url = "https://sbcheckout.payfort.com/FortAPI/paymentPage" sign = "766l8ccloPvjBEb1dzhPj6?]access_code=0zXXVcMMK04wNqwk9EgBamount=10000command=AUTHORIZATIONcurrency=AEDcustomer_email=test@payfort.comlanguage=enmerchant_identifier=2dccbd67merchant_reference=XYZ9239-yu89813434432order_description=iPhone 6-S766l8ccloPvjBEb1dzhPj6?]" requestParams = { 'command' : 'AUTHORIZATION', 'access_code' : '*****************', 'merchant_identifier' : '********', 'merchant_reference' : 'XYZ9239-yu8981343443254', 'amount' : '10000', 'currency' : 'USD', 'language' : 'en', 'customer_email' : 'test@payfort.com', 'signature' : 'a9cca1a93b2c9326748c8b884229e2b8da345a2dd3fea34ba3491a7f2902d402', 'order_description' : 'iPhone 6-S', } res = requests.post(url, requestParams) print(res.text) and got this response {"response_code":"00013","response_message":"Invalid Currency","fort_id":null,"token":"52190Zl41PbSHvmr9OqmVKx6G817501458703215891441727366723522234"}; I need help to know what causes Invalid currency error? -
how to dynamically show form input fields base on user selection from dropdown options
I have this form that is used to enter student grades per subject now on this form I have 3 dropdown boxes that are dependent on each other, what I want to accomplish is that after the user selects the classroom that the students are in, I want the input fields for each subject to appear on the same form that is only in that class that the user selected so that the user can enter the grades of the students per subject but I am having a hard time figuring out how to implement such behavior. in short,i want to show input fields for subjects base on the classroom the user selected form.py <div class="container-fluid"> <form id="result-form" method="post"> {% csrf_token %} <!-- Modal --> <div class="modal-header"> <h5 class="modal-title" id="staticBackdropLabel"> {% block modal-title%} Add Result {% endblock%}</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="row"> <div class="col-md-12" id="msg8" style="font-size: 2rem; color:rgb(255, 144, 47)"></div> <div class="col-md-12 form-group p-2"> <label class="form-label">Class Name</label> {% render_field form.room class+="form-control" %} </div> <div class="col-md-12 form-group p-2"> <label class="form-label">Exam Name</label> {% render_field form.exam class+="form-control" %} </div> <div class="col-md-12 form-group p-2"> <label class="form-label">Student</label> {% render_field form.student class+="form-control select2" %} </div> <div class="hidden" id="subject-fields"></div> <div class="form-group mb-3 … -
Code run in setUpTestData for django testing is not captured in test time
When I run tests using setUpTestData() the time spent in setUpTestData() is not captured. I can see this when running it in pycharm (it shows only the test run time) as well as when the tests run in CircleCi. Is there something special that needs to be done so that setUpTestData() time will be captured (at least on the TestSuite xml) -
Django Rest Framework filter specific columns in csv file base on values
I have a csv file, and I want to filter base on the input value. Age Name Gender Grade 10 Mark male 90 6 James male 85 10 Carl male 93 8 Lucky male 89 10 Ice female 90 Here's my code: @api_view(['GET']) def filter(request): field_value = ['James','Ice'] with open("/path_to_file/grade.csv", 'r') as csvfile: file = csv.reader(csvfile) for row in file : if row[1] == field_value: out = json.dumps(row, ensure_ascii=False) obj = json.loads(out) Name = obj.get('Name') Gender = obj.get('Gender') grade = obj.get('Grade') And the return output should be like this: But I got and error AttributeError: 'list' object has no attribute 'get' Name Gender Grade James male 85 Ice female 90 -
Django + gunicorn timming out on AWS Auto Scaling
I have added my gunicorn + django config to systemd, and when I access "http://EC2_Public_IP:8000" the browser shows the expected result, which is an OpenApi screen. Here is the django.service file: [Unit] Description=Unit for starting a basic Django app [Service] User=ubuntu Restart=on-failure WorkingDirectory=/home/ubuntu/projectName ExecStart=/home/ubuntu/env/bin/gunicorn projectName.wsgi -b 0.0.0.0:8000 [Install] WantedBy=multi-user.target Here is the systemctl status django log: ● django.service - Unit for starting a basic Django app Loaded: loaded (/etc/systemd/system/django.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2022-07-14 00:07:00 UTC; 27min ago Main PID: 865 (gunicorn) Tasks: 2 (limit: 1134) CGroup: /system.slice/django.service ├─865 /home/ubuntu/env/bin/python /home/ubuntu/env/bin/gunicorn lastmile.wsgi -b 0.0.0.0:8000 └─968 /home/ubuntu/env/bin/python /home/ubuntu/env/bin/gunicorn lastmile.wsgi -b 0.0.0.0:8000 Jul 14 00:07:00 ip-xxxxxx systemd[1]: Started Unit for starting a basic Django app. Jul 14 00:07:02 ip-xxxxxx gunicorn[865]: [2022-07-14 00:07:02 +0000] [865] [INFO] Starting gunicorn 20.1.0 Jul 14 00:07:02 ip-xxxxxx gunicorn[865]: [2022-07-14 00:07:02 +0000] [865] [INFO] Listening at: http://0.0.0.0:8000 (865) Jul 14 00:07:02 ip-xxxxxx gunicorn[865]: [2022-07-14 00:07:02 +0000] [865] [INFO] Using worker: sync Jul 14 00:07:02 ip-xxxxxx gunicorn[865]: [2022-07-14 00:07:02 +0000] [968] [INFO] Booting worker with pid: 968 I tested restarting the EC2 instance e trying to connect to "http://EC2_Public_IP:8000", and it works fine too I also added the EC2 that I used to create … -
Data Scraping using proxy
How can I scrape the data using node js (puppeteer package ) using proxy .I need some useful resources related to it and which is more suitable python or js for scraping data using proxy -
Django Forms - Multi-Step Save Progress Along the Way
Just looking for a bit of a push in the right direction. I'm creating a multi-step user sign up to receive a personalized assessment. But I'm having trouble trying to wrap my head around the multi-step progress within Django and a SQL point of view. These are my steps, each to be a separate form: Sign Up (Make an Account) Complete Profile Information Create an application Complete required questions within application - This may need to be broken down even further. I've figured out redirections from each form, but my biggest concern is saving which step they're up to. E.g. What if they close the browser at end of step 2, how do I have a way to prompt them to come and complete step 3 onwards. To make it clear, I'm not looking for saving the state within the browser. Needs to be saved within the database to support access from other devices, for example. To add onto it, what if I was to allow them to make multiple applications (steps 3 and 4), but only allowing one to be open at a time. E.g. One gets rejected but we allow them to reapply. Just looking for some tips/suggestions … -
Expected behavior of "in" filter in Django-Filter with Graphene
Suppose I have models in Django like so model Foo: bar = ManyToMany(Bar) model Bar: baz = String and some object foo of type Foo, like so: foo.bar = [Bar(baz='fizz'), Bar(baz='buzz')] (so basically, some Foo object with more than 1 distinct related Bar) and then if I create a schema with the following filter field foo_bar__baz: ['in'] and I do a query with fooBarBazIn: ['fizz', 'buzz'], the same foo object is returned twice (whereas if I did only fooBarBazIn: ['fizz'], the object foo would only be returned once). This behavior extends to n related fields and m arguments in the filter; if an object matches k<m of these arguments, it will be returned k times in the resulting query (up to a maximum of n times) - whereas I would expect the same object to only be returned once. Is this behavior intentional? -
How to save the context of an api and use it to create an order history
I am using the transbank api to simulate the purchase of a product through an app of a bank, and I need to save the data generated at the end of the purchase to show them in a purchase history of the user, and I do not know how to do that, thanks in advance. Here is the code of: successful payment @csrf_exempt def pago_exitoso(request, id): if request.method == "GET": token = request.GET.get("token_ws") print("commit for token_ws: {}".format(token)) commercecode = "597055555532" apikey = "579B532A7440BB0C9079DED94D31EA1615BACEB56610332264630D42D0A36B1C" tx = Transaction(options=WebpayOptions(commerce_code=commercecode, api_key=apikey, integration_type="TEST")) response = tx.commit(token=token) print("response: {}".format(response)) user = User.objects.get(username=response['session_id']) perfil = PerfilUsuario.objects.get(user=user) form = PerfilUsuarioForm() producto = Producto.objects.get(id=id) context = { "buy_order": response['buy_order'], "session_id": response['session_id'], "amount": response['amount'], "response": response, "token_ws": token, "first_name": user.first_name, "last_name": user.last_name, "email": user.email, "rut": perfil.rut, "direccion": perfil.direccion, "response_code": response['response_code'], "producto": producto } return render(request, "core/pago_exitoso.html", context) else: return redirect(index) ---- And here is the code : Start payment @csrf_exempt def iniciar_pago(request, id): print("Webpay Plus Transaction.create") buy_order = str(random.randrange(1000000, 99999999)) session_id = request.user.username amount = Producto.objects.get(id=id).precio return_url = 'http://127.0.0.1:8000/pago_exitoso/'+ id # response = Transaction.create(buy_order, session_id, amount, return_url) commercecode = "597055555532" apikey = "579B532A7440BB0C9079DED94D31EA1615BACEB56610332264630D42D0A36B1C" tx = Transaction(options=WebpayOptions(commerce_code=commercecode, api_key=apikey, integration_type="TEST")) response = tx.create(buy_order, session_id, amount, return_url ) print(response['token']) perfil = PerfilUsuario.objects.get(user=request.user) form … -
Python-Pandas How create new column, using a subquery in the same table and get all rows related in one row
SAP pep pep_union 4530020120 1001-17AD400-1.05.03 1001-17AD400-1.05.03/1001-17AD400-2.04 4530020120 1001-17AD400-2.04 1001-17AD400-1.05.03/1001-17AD400-2.04 4530020130 1001-17AD400-5.05 1001-17AD400-5.05 4530020110 1001-17AD400-5 1001-17AD400-5/1001-17AD400-5.05/345 4530020110 1001-17AD400-5.05 1001-17AD400-5/1001-17AD400-5.05/345 4530020110 345 1001-17AD400-5/1001-17AD400-5.05/345 4530020145 not match how can get this result in the same table create new column with all rows related with column "sap" separated by "/" in SQL is something like this SELECT sap, pep, pep_union=isnull(STUFF ( ( SELECT DISTINCT '/' + CAST([pep] AS VARCHAR(MAX) ) FROM [sap_reales] t2 WHERE t2.[sap] = t1.[sap] FOR XML PATH('') ),1,1,'' ),'not match') FROM sap_reales t1 -
django Error Cannot use None as a query value
I'm following a basic search tutorial in https://learndjango.com/tutorials/django-search-tutorial but without the admin. it's throwing an error Cannot use None as a query value but when I go to python shell it's fetching me the studid and studlastname I want >>>from clearance.models import Student >>>query=Student.objects.using('srgb').get(studid__icontains='2012-5037') >>><QuerySet [<Student: Student object (2012-5037)>]> >>>query.studid '2012-2555' >>>query.studlastname 'Michael' views.py class SearchResultsView(ListView): model = Student template_name = 'clearance/search.html' def get_queryset(self): query = self.request.GET.get("q") object_list = Student.objects.using('srgb').get( Q(studid__icontains=query) | Q(studlastname__icontains=query) ) return object_list search.html <form action="{% url 'search_results' %}" method="get"> <input name="q" type="text" placeholder="Search..."> </form> <h1>Search Results</h1> <ul> {% for result in object_list %} <li> {{ result.studid }} </li> {% endfor %} </ul> -
"Server Error 500" Debug = False - Django
When I want to change Debug to False, I am facing this error : Server Error 505 Who knows why? By the way I deployed it in Heroku. File tree: ─mainfolder ├─.idea ├─all ├─my-project ├─__pycache__ ├─__init.py__ ├─asgi.py ├─settings.py (Above) ├─urls.py ├─wsgi.py ├─env ├─static ├─templates ├─user ├─.gitignore ├─Procfile ├─manage.py ├─requirements.txt Settings.py : import os import django_heroku # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = (os.environ.get('DEBUG_VALUE')=='True') ALLOWED_HOSTS = ['mydomain.com','www.mydomain.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "user", "all", ] 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', ] ROOT_URLCONF = 'my-project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ["templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'my-project.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': … -
Cant filter my employers in django project
So, i have a django website, where i have companys with "pages".~ I need to add some employers to that page, but before i add them, i need to check if there is a page created, and then if there is some employers already in that company and i want my result to be "dynamic", so here is how i tried to achieve this: Thats my employer module: class Employer(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) name = models.CharField(max_length=30) funcion = models.CharField(max_length=20, blank=True, null=True) image = models.ImageField(default="default.png") facebook = models.CharField(max_length=100, null=True, blank=True) instagram = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.name My company model wich is the "father" class Company(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.CharField(max_length=30, blank=True, null=True, unique=True) image = models.ImageField(default="default.png") created = models.DateTimeField(auto_now_add=True) about = models.TextField(max_length=800, blank=True, null=True) phone = models.IntegerField(blank=True, null=True) address = models.CharField(max_length=100) email = models.EmailField(blank=True, null=True) slug = models.SlugField(null=False) logo = models.ImageField(default="default.png") welcome = models.CharField(blank=True, null=True, default="Welcome", max_length=200) def __str__(self): return self.company and here is my view, where im getting errors because i dont know how to achieve what i want @login_required def listing_employer(request): try: company = Company.objects.get(user=request.user) except company.DoesNotExist: company = None employers = Employer.objects.filter(company=company) context = { "employers": employers, "company": company, } return render … -
Django Query using Foreign Key
I'm starting to work with queries in django and I'm trying to replicate the results of a join in sql. I have a two models that represent a parent (WaiverAdult) and a child (WaiverMinor). I would like to return the parent and child in the query set, so I can group them in a formatted template, like so: John Dad Tommy Son Amber Daughter Jen Jones Stevie Jones Mike Jones MODELS: class WaiverAdult(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50, blank=True) class WaiverMinor(models.Model): first_name = models.CharField(max_length=50, blank=True) last_name = models.CharField(max_length=50, blank=True) parent = models.ForeignKey(WaiverAdult, on_delete=models.CASCADE) VIEW: class WaiverListView(ListView): template_name = 'waiver/waiver_list.html' model = WaiverAdult context_object_name = "waiver_list" queryset = WaiverAdult.objects.order_by('created') What is the proper way to write this query? Thank you in advance. I truly appreciate the guidance. -
How to return a value from data base to a function in Django Python?
I'm working in a Python project using Django framework e I'm having some troubles such as: first we have a page to receive a integer value and we submit this value, after we'll have a new page that contains N integer field, where N is the input value from the first page. Below I show models.py: class Numero(models.Model): n=models.IntegerField() def back(self): return self.n class Peso(models.Model): peso=models.IntegerField() def __str__(self): return self.peso class Preco(models.Model): preco=models.IntegerField() def __str__(self): return self.preco views.py é: def index(request): template=loader.get_template('app/index.html') n=0 if request.method=='POST': n = Objetos(request.POST) context={'n': n} return render(request, 'app/index.html', context) def valores(request): template = loader.get_template('app/valores.html') peso=0 preco=0 peso_unitario=[] preco_unitario=[] **N=int(n_objetos)** for i in range(N): if request.method=='POST': peso=Peso_Unitario(request.POST) preco = Preco_Unitario(request.POST) if i == 0: peso_unitario = peso preco_unitario = preco else: peso_unitario.append(peso) preco_unitario.append(preco) context={'peso_unitario': peso_unitario, 'preco_unitario': preco_unitario} return render(request, 'app/valores.html', context) In N=int(n_objetos) **N=int(n_objetos)** is the drouble because I wanna return the value received before. index.html: <form action="/app/valores/" method="POST"> {% csrf_token %} <label for="n_objetos">n_objetos:</label> <input id="n_objetos" type="number" value=""/><br> <label for="peso_maximo">peso_maximo</label> <input id="peso_maximo" type="number" value=""/><br> <input type="submit"> </form> <a href="/app/valores/"></a> valores.html: <form action="% url 'app:Resultados' %" method="POST"> {% csrf_token %} <label for="peso_u">peso_u</label>; <input id="peso_u" type="number" value=""/><br>; <label for="preco_u">preco_u</label>; <input id="preco_u" type="number" value=""/><br>; <input type="submit">; </form> <a href="% … -
when executing docker-compose, Service 'web' failed to build
I get this message in the terminal when I run docker-compose, everything looks good as far as my novice eyes can tell. $ docker-compose up Building web [+] Building 9.3s (8/9) => [internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 32B 0.0s => [internal] load .dockerignore 0.0s => => transferring context: 2B 0.0s => [internal] load metadata for docker.io/library/python:3.8 0.7s => [1/5] FROM docker.io/library/python:3.8@sha256:883e00aeb53d4cecb6842f2e10078a6bc8faf5dbb3d8b2a77cb1a232d81bf7ca 0.0s => [internal] load build context 0.0s => => transferring context: 4.06kB 0.0s => CACHED [2/5] WORKDIR /gekkopedia 0.0s => CACHED [3/5] COPY Pipfile Pipfile.lock /gekkopedia/ 0.0s => ERROR [4/5] RUN pip install pipenv && pip install --system 8.5s ------ > [4/5] RUN pip install pipenv && pip install --system: #8 1.827 Collecting pipenv #8 2.014 Downloading pipenv-2022.7.4-py2.py3-none-any.whl (3.7 MB) #8 3.354 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3.7/3.7 MB 2.8 MB/s eta 0:00:00 #8 3.380 Requirement already satisfied: setuptools>=36.2.1 in /usr/local/lib/python3.8/site-packages (from pipenv) (57.5.0) #8 3.426 Collecting certifi #8 3.446 Downloading certifi-2022.6.15-py3-none-any.whl (160 kB) #8 3.488 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 160.2/160.2 KB 3.8 MB/s eta 0:00:00 #8 3.643 Collecting virtualenv #8 3.667 Downloading virtualenv-20.15.1-py2.py3-none-any.whl (10.1 MB) #8 5.486 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 10.1/10.1 MB 5.6 MB/s eta 0:00:00 #8 5.497 Requirement already satisfied: pip>=22.0.4 in /usr/local/lib/python3.8/site-packages (from pipenv) (22.0.4) #8 5.538 Collecting virtualenv-clone>=0.2.5 … -
Mobile double tap issue
I was developing a website using django. Everything is responsive the way I wanted it to be, but when I change to mobile mode, the dropdown menus needed double tap to send me to the link I wanted. single tap is acting as a hover evenif I don't have hover effect. Here is my code. html code: <ul class="custom-menu"> <li><a href="{% url 'account' %}">{% "Account" %}</a></li> <li><a href="{% url 'orders' %}"></i> {% "Orders " %}</a></li> <li><a href="{% url 'logout' %}"> {% "Logout" %}</a></li> </ul> css code: .custom-menu { position: absolute; padding: 15px; background: #FFF; -webkit-box-shadow: 0px 6px 12px rgba(0, 0, 0, 0.175); box-shadow: 0px 6px 12px rgba(0, 0, 0, 0.175); z-index: 100; top: 100%; min-width: 200px; opacity: 0; visibility: hidden; -webkit-transition: 0.3s all; transition: 0.3s all; } .dropdown.open>.custom-menu { opacity: 1; visibility: visible; } It works on desktop but it needs double tap on mobile. I have tried using @media (pointer: fine) {}, but it makes the dropdown always visible. Thankyou in advance for your help! -
How to repair ipnyb files?
I accidentally delete jupyter file in VScode and I recover it using a disk drill but now I can not open it. even the code is changed into characters. Please help me out. picture of a file after recovery -
Is it possible to access an SQL database migrated using Django with a JavaScript ORM instead of raw SQL for a microservice architecture?
Suppose that I have an app where the models have been created using Django ORM and Django acts like an API for authentication and gives control to the relation model User using its ORM. At the same time, we want to use Express JS to continuously update a field in one the User model for some feature that requires performance. Is it possible to use a JavaScript ORM with Express JS to update such field? If yes, then how? -
Why does custom delete function didn't work?
I am working on DRF (Django) API I have a simple ModelViewSet. Delete request is working good for this: class BuildingObjectViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] serializer_class = BuildingObjectSerializer queryset = BuildingObject.objects.all() I want to customize delete function. But this delete code works too long time > 1 minute What is the reason of too long time of request? class BuildingObjectViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] serializer_class = BuildingObjectSerializer queryset = BuildingObject.objects.all() def destroy(self, request, *args, **kwargs): instance = self.get_object() deleted_id = instance.pk self.perform_destroy(instance) response = { "message": "BuildingObject has been deleted.", "building_object_id": deleted_id } return Response(response, status=status.HTTP_204_NO_CONTENT) models.py class BuildingObject(models.Model): name = models.CharField(max_length=32) address = models.CharField(max_length=200) urls.py path( "building_objects/<int:pk>/", BuildingObjectViewSet.as_view({ "delete": "destroy", "get": "retrieve", "patch": "partial_update", }), name="building_objects_detail" ),