Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how a user can add a new attribute to a model from template
I have the following model : models.py : class Product(models.Model): name = models.CharField(blank=False, max_length=255) description = models.TextField() class Ingredients(models.Model): ingredients = models.ForeignKey(Product, related_name='ingredients', on_delete=models.CASCADE, null=True) salt = models.IntegerField(default=0) pepper = models.IntegerField(default=0) views.py : def productdetails(request, product_pk): product = get_object_or_404(Product, pk=product_pk) ingredients = get_object_or_404(Ingredients, ingredients_id=product_pk) salt = ingredients.salt pepper = ingredients.pepper if request.method == 'POST': form = IngredientsForm(request.POST) newvalue = form.save(commit=False) newvalue.user = request.user newvalue.save() return render(request, 'xxx.html', {'product': product, 'form': IngredientsForm, 'salt': salt, 'pepper': pepper}) return render(request, 'xxx.html', {'product': product, 'iform': IngredientsForm, 'salt': salt, 'pepper': pepper}) def updateproduct(request, product_pk): ingredients = get_object_or_404(Ingredients, ingredients_id=product_pk) form = IngredientsForm(request.POST or None, instance = ingredients) salt = ingredients.salt pepper = ingredients.pepper if form.is_valid(): form.save() products = Product.objects.filter() return render(request, 'xxx.html', {'products': products}) return render(request, 'xxx.html', {'form': form, 'salt': salt, 'pepper': pepper, 'product_pk': product_pk}) def createingredients(request, product_pk): if request.method == 'POST': ingredients = get_object_or_404(Ingredients, ingredients_id=product_pk) form = IngredientsForm(request.POST or None, instance=ingredients salt = ingredients.salt pepper = ingredients.pepper # here should be the code return render(request, 'xxx.html', {'ingredients': ingredients, 'product_pk': product_pk}) In template: <div class="container"> <strong>Ingredients:</strong> <b>Salt: </b>{{ salt }} g <br> <b>Pepper: </b>{{ pepper }} g <br> <br> Update ingredients: {% if error %} <div class="alert alert-danger" role="alert"> {{ error }} </div> {% endif %} … -
Django form conditional required, Error message placement
What i want is for end validation error to be displayed next to the company_name field name. Is this even possible? in my form.py def clean(self): cleaned_data = super().clean() use_company = cleaned_data.get("use_company") company_name = cleaned_data.get("company_name") use_acn = cleaned_data.get("use_acn") if not use_company and not use_acn: raise forms.ValidationError('Kindly select either a company name or ACN Option') if use_company and company_name is '': raise forms.ValidationError('Pls select company Name') What are my options? -
How can i slice an array in django template?
So I am trying to achieve how to show 5 name into the chart instead off all name: here is my views.py: def index(req): labels = [ {"name": 'data'}, {"name": 'hello'}, {"name": 'wassup'}, {"name": "waddddup"}, {"name": "heyyyyy"}, {"name": "dsfdsfd"}, {"name": "qqqq"}, {"name": "23f3f"}, {"name": "23f"}, {"name": "zzzz"}, ] values = [] def label_chart(labels): label_test = [] for i in labels: label_test.append(i['name']) dataJSON = dumps(label_test) return dataJSON data = { 'data': label_chart(labels), } return render(req, 'index.html', data) and here is my template javascript index.html: <script type="text/javascript"> var data_labels = JSON.parse(`{{ data | safe }}`); console.log(data_labels); var endpoint = '/api/chart/data/' $.ajax({ method: "GET", url: endpoint, success: function (data) { labels = data.labels defaultData = data.default setChart() }, error: function (error_data) { console.log("error") console.log(error_data) } }) function setChart() { let y = [10, 3, 5, 9, 1]; var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: 'bar', data: { labels: data_labels, datasets: [{ label: '# of Votes', data: y, backgroundColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', … -
custom management command throws no module found error in virtual env
I am using a virtual environment in django to install all the pip packages. It runs fine when i write command: source env/bin/activate python manage.py runserver but when i run custom management command: source env/bin/activate python manage.py broadcast It throws no module found pika. I deactivated the virtual env and again activated it but still no luck. I tried pip install pika but it says requirement already satisfied. Is there a way to use virtual env in command line? What can cause this issue? -
footer going in front of other thing
im new to python/Django and i've put a calendar on my app i have no error but i don't know why my footer goes before my calendar when i press f12 on my app i can see : <section class="content container-fluid"> <div class="clearfix"> <a class="btn btn-info left" href="/calendrier/calendar/?month=2020-6"> Previous Month </a> <a class="btn btn-info right" href="/calendrier/calendar/?month=2020-8"> Next Month </a> <a class="btn btn-info right" href="/calendrier/event/new/"> New Imputation </a> </div> <footer class="main-footer"> <div class="pull-right hidden-xs"> Version X.x </div> <strong>Copyright © 2019 <a href="#">CONDUENT</a>.</strong> All rights reserved. </footer><table border="1" cellpadding="1" cellspacing="1" class="calendar"> It look like that in my code : {% extends 'base.html' %} {% block title %} Calendar {% endblock %} {% block content %} <div class="clearfix"> <a class="btn btn-info left" href="{% url 'cal:calendar' %}?{{ prev_month }}"> Previous Month </a> <a class="btn btn-info right" href="{% url 'cal:calendar' %}?{{ next_month }}"> Next Month </a> <a class="btn btn-info right" href="{% url 'cal:event_new' %}"> New Imputation </a> </div> {{ calendar }} {% endblock %} And if i put my {{ calendar }} inside the div my button overwritte the footer -
p tags are not removed in for loop with BeautifulSoup
I'm trying to remove some marks from text, like <p>\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n</p> and <p>\r\n</p> here is code where I am using here BeautifulSoup. article = Article.objects.all() for obj in article: soup_en = BeautifulSoup(obj.text_en, features="html5lib") obj.text_en = '\n'.join(map(str, OrderedSet(soup_en.find_all('p')))).replace(r'\r\n', '').replace('#####444#####', '').replace('#####555#####', '').replace('<p></p>', '').replace(r'<p>&nbsp;</p>', '') obj.save() Text with marks to remove: <p>\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n</p> <p>\r\n</p> <p>Name of person </p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>\r\n</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>\r\n</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing … -
Django+React: What is the bet way to properly implement authentication and security on API requests from React to Django backend
I am working on a Django+React project. My React app is my only UI renderer (which means no template or any markup is being served by Django), while my Django app is only used for serving APIs for me to access my database resources. On a particular React page, I have login and test buttons that send requests to a DRF API in my Django backend. Login API View class AuthLogin(generics.GenericAPIView): serializer_class = LoginSerializer authentication_classes = [SessionAuthentication] permission_classes = () def get(self, request): user = request.user if not user and not user.is_authenticated or user.is_anonymous: return Response( { "status": True, "message": "Login page accessed" }, status=status.HTTP_200_OK ) else: return Response( { "status": False, "message": "You are currently logged in" }, status=status.HTTP_400_BAD_REQUEST ) def post(self, request, *args, **kwargs): res = [] res_stat = status.HTTP_401_UNAUTHORIZED serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=False) validated_data = serializer.validated_data if validated_data: user = dj_auth(username=request.data.get('username'), password=request.data.get('password')) if user and user.is_authenticated and not user.is_anonymous: auth_login(request, user) res_stat = status.HTTP_200_OK res = { "status": True, "message": "Login successful!", "login": { "date_time": timezone.now(), "user": { 'id': user.id, 'first_name': user.first_name, 'last_name': user.last_name, 'email': user.email, } } } else: res_stat = status.HTTP_401_UNAUTHORIZED res = { "status": False, "message": "Invalid username and/or password" } else: res_stat = … -
excluding based on related field's count
I have classic title and entry models where title is foreignkey in entry model. I use users model's default first_name field to suspend users, so if a user is suspended then the first_name field is set to blocked. I also have a model to let user block eachother: class Block(models.Model): blocker= models.ForeignKey("auth.user",on_delete= models.CASCADE,related_name="blocker") blocked= models.ForeignKey("auth.user",on_delete= models.CASCADE,related_name="blocked") What I want to do is to display titles while excluding titles if there are no entries left beloging to the title after exlusion of blocked and suspended users. In other words filtering titles if related entry count is > 0 after exclusions. I've been using the code below to solve this: title= Popular.objects.all().order_by("-rating") titles= [] followed_count= None paginator = Paginator(title, 1) page = request.GET.get('page', 1) try: entries2 = paginator.page(page) except PageNotAnInteger: entries2 = paginator.page(1) except EmptyPage: entries2 = paginator.page(paginator.num_pages) page_list = entries2.paginator.page_range for title in entries2: if request.user.is_authenticated: followed_count= Entry.objects.filter(user__followed__follower=request.user,title=title.title,created_date__gte=date_from).exclude(user__last_name="blocked").count() blocked_count= Entry.objects.filter(user__blocked__blocker=request.user,title=title.title,created_date__gte=date_from).exclude(user__last_name="blocked").count() else: blocked_count= 0 suspend_count= Entry.objects.filter(user__last_name="blocked",title=title.title,created_date__gte=date_from,).count() amount= Entry.objects.filter(title=title.title,created_date__gte=date_from).count() amount -= blocked_count + suspend_count if amount == 0: continue titles.append({"title":title.title,"url":title.title.title_url,"rating":title.rating,"title_id":title.title_id,"amount":amount,"followed_count":followed_count} But if there are titles with no entries it causes the paginator to create empty pages, I also do not want to put the pagination code to the end as I don't want … -
Django 3.1 asgi server timeout connecting to itself inside async view
Got an issue trying to connect from an async view in Django 3.1 to a sync view served by the same asgi server. Doing this in normal wsgi development server works, but not in an asgi server. Which seems kind of weird. Probably I misunderstood on how asgi works :). Here's a link on how to reproduce this: All steps to reproduce this. Here are just the views causing the problem. Maybe someone is able to tell immediately what I'm doing wrong by just looking at those: import httpx from django.http import JsonResponse def sync_api_view(request): payload = {"foo": "bar"} return JsonResponse(payload) def sync_aggregation_view(request): responses = [] r = httpx.get("http://127.0.0.1:8000/sync_api_view/") responses.append(r.json()) result = {"responses": responses} return JsonResponse(result) The "sync_aggregation_view" is the one that works in wsgi but not via asgi. -
Django dumpdata error on postgres db downloaded from AWS RDS
I've downloaded a database from AWS RDS instance and loaded it locally into Postgres and connected my Django application to it. It works. I am then trying to use ./manage.py dumpdata and I'm getting the following error: CommandError: Unable to serialize database: cursor "_django_curs_140343345395520_1" does not exist I've tried just dumpdata for single applications and tables and get the same error. Does anyone know what I need to do? -
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on '127.0.0.1:3306' (111 Connection refused)
I used mysql connector in my django web app. I've dockerized the app and mysql is throwing this error. I've tried restarting mysql server, i've also used 127.0.0.1 instead of localhost, it still throws the same error. I'm trying to run "docker-compose up" here and it's bringing this error mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on '127.0.0.1:3306' (111 Connection refused) "docker-compose build" runs fine but "docker-compose up" and python manage.py runserver" throws the mysql error Here is my utils.py file import mysql.connector mydb = mysql.connector.connect( host="127.0.0.1", user="root", passwd="aspilos", database="aspilos_log" ) mycursor = mydb.cursor() mycursor.execute("SELECT PHONE_NUMBER FROM category2") results = mycursor.fetchall() for i in zip(*results): number = list(i) number1 = '+2348076548894' print (number) Here is my docker-compose.yml file version: '3.4' services: db: image: mysql ports: - '3306:3306' environment: MYSQL_DATABASE: 'app' MYSQL_USER: 'root' MYSQL_PASSWORD: 'aspilos' MYSQL_ROOT_PASSWORD: 'aspilos' web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/aspilos ports: - "8000:8000" depends_on: - db Here is my settings.py file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'app', 'USER': 'root', 'PASSWORD': 'aspilos', 'HOST': 'db', 'PORT': '3306', }, } Please if you can help me look at it with Visual Studio Code Live Share i'll be very grateful. I've been on this … -
Shorten condition variable in Django template using with
Hey I am trying to set a variable in a Django template on a condition and also within a for loop (which is why I can't do it directly in the views). The condition I have is this: {% if message.sender == request.user %} {% contact=message.receiver %} {% else %} {% contact=message.sender %} {% endif %} I thought about putting with in each condition but I would have to have a copy of the same HTML code in each if/else part because you need to have an {% endwith %}, like so: {% if message.sender == request.user %} {% with contact=message.receiver %} <p>some html code</p> {% endwith %} {% else %} {% contact=message.sender %} <p>some html code</p> {% endwith %} {% endif %} So I would like to shorten it like that to be able to use with but it doesn't seem to work: {% with contact=(message.sender, message.receiver)[message.sender == request.user] %} Any idea how I could achieve this? -
Using QuerySet.union() in ModelAdmin.formfield_for_manytomany() breaks selection widget
Not sure what I am doing wrong here: I tried to use QuerySet.union() to combine two querysets (for the same model) inside ModelAdmin.formfield_for_manytomany(). However, when the form is saved, the entire queryset is selected, regardless of the actual selection made. Pleas consider the minimal example below, based on the standard Django Article/Publication example. Here's what happens when I add a new Article in the admin, without selecting any publications: Before "Save" (nothing selected) After "Save" (everything is selected) These images were created using the following minimal example: from django.db import models from django.contrib import admin class Publication(models.Model): pass class Article(models.Model): publications = models.ManyToManyField(to=Publication, blank=True) class ArticleAdmin(admin.ModelAdmin): def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == 'publications': # the following query makes no sense, but it shows an attempt to # combine two separate QuerySets using QuerySet.union() kwargs['queryset'] = Publication.objects.filter(id__lt=3).union( Publication.objects.filter(id__gt=2)) return super().formfield_for_manytomany(db_field, request, **kwargs) admin.site.register(Publication) admin.site.register(Article, ArticleAdmin) The initial queryset for the publications field is filtered using formfield_for_manytomany, as described in the docs. The actual query in this example makes no sense, but the point is that QuerySet.union() messes things up (it works normally if you remove the union()). Am I using QuerySet.union() the wrong way,or is this expected behavior, given … -
Image carousel, converting p5.js to Django?
I'm a beginner with Django and would appreciate getting some directions / tips of tutorials for the following scenario: User sees image 1 on home page. When they click a button, it changes to image 2, then after next click to image 3 etc. These images can come from JSON (preferably) or image folder in my database. I have been looking into some AJAX tutorials (like https://www.pluralsight.com/guides/work-with-ajax-django) and I start to understand the basic structure of Django, however so far I find it a bit difficult to understand how to update the image like this. Just in case, I'll illustrate how I got it working in P5.js with array and index: var index = 0; var imageData; var imgList = []; var indexMax; function preload() { loadJSON("img.json", resultLoaded); console.log("JSON is loaded") } function resultLoaded(data) { imageData = data; console.log(imageData) console.log(imageData.length) indexMax = imageData.length; for (i = 0; i < indexMax; i++) { url = imageData[i]["source"]; imgList.push(loadImage(url)); } } function setup() { createCanvas (w, h); setupButtons(); } function setupButtons() { buttonA = select("#goodButton"); buttonA.mousePressed(function() { index = index + 1; if (index == indexMax) { index = index - indexMax; } }); (etc.) Warm thanks for any help! -
create a coupon in stripe programmatically with Django
I have a random code generator model which is working fine and generating unique codes in Django. Now I want to create a stripe coupon using that generated code. What can I implement in my Html template and views.py ? -
Django 3.0.8 ' bootstrap' is not a registered tag library. Must be one of:
I want a menu thats custom depending which group you are member of. Im using Django 3.0.8. When i am trying to make my Templatetag it fails and it says:¨ TemplateSyntaxError at /accounts/login/ 'bootstrap' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls bootstrap_tags cache crispy_forms_field crispy_forms_filters crispy_forms_tags crispy_forms_utils i18n l10n log static tz Error during template rendering In template /home/saurabh/Documents/python projects/django-job-portal-master/job_portal/templates/accounts/login.html, error at line 3 'bootstrap' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls bootstrap_tags cache crispy_forms_field crispy_forms_filters crispy_forms_tags crispy_forms_utils i18n l10n log static tz 1 {% extends 'base.html' %} 2 {% load static %} 3 {% load bootstrap %} 4 5 6 {% block content %} 7 <section class="home-section section-hero inner-page overlay bg-image" 8 style="background-image: url('images/hero_1.jpg');" id="home-section"> 9 <div class="container"> 10 <div class="row align-items-center justify-content-center"> 11 <div class="col-md-12"> 12 <div class="mb-5 text-center"> and tha error comes in login.html file which say, {% load bootstrap %} -
Django modal form requiring a value
I'm facing an issue that I have a small modal form pop up when I click on a button and taking a product ID value from a text field and when the user click on submit it should be redirect to the product view. the issue in the action section it's requiring a primary key even before the main page lunched and it's showing the below error NoReverseMatch at /productsall Reverse for 'ProductDetail2' with arguments '('',)' not found. 1 pattern(s) tried: ['ProductDetail2/(?P<pk>[^/]+)$'] below is the modal form: <div class="modal-body"> <form method="POST" action="{% url 'ProductDetail2' ProdID %}ProdID %}"> {% csrf_token %} <div class="form-group"> <label style="float: right;" for="ProdID"> : رقم المنتج</label> <input style="float: right;" type="text" class="form-control" id="ProdID" aria-describedby="emailHelp" > <br><br><br> <small id="emailHelp" style="float: right;" class="form-text text-muted">إبحث برقم المنتج ثم إضغط على الذهاب للمنتج</small> </div> <button type="submit" class="btn btn-primary">الذهاب للمنتج</button> </form> </div> and this is the url path('ProductDetail2/<pk>',views.ProductDetail2,name="ProductDetail2"), if I pass a fixed value like below <form method="POST" action="{% url 'ProductDetail2' 90 %}ProdID %}"> the main page will lunched without no error and if I click on the submit button even with no input it will direct me to the ProductDetail2 view for product 90 with no error I need to replace the … -
Multiple Inlines in Model Admin in Django
I have some models as follows: models.py from django.db import models SET_CHOICES = [ ('A', 'Set A'), ('B', 'Set B'), ('C', 'Set C'), ('D', 'Set D') ] class Exam(models.Model): exam_name = models.CharField(max_length=255) sub_code = models.CharField(max_length=10) sub_name = models.TextField() max_marks = models.PositiveIntegerField() def __str__(self): return f'{self.sub_code}: {self.sub_name}' class ExamSet(models.Model): which_exam = models.ForeignKey(Exam,on_delete=models.CASCADE) set_name = models.CharField( max_length=1, choices=SET_CHOICES, default='A', ) def __str__(self): return f'{self.which_exam.sub_code}: {self.which_exam.sub_name} (Set {self.set_name})' class Question(models.Model): for_which_exam_set = models.ForeignKey(ExamSet, on_delete=models.CASCADE) question_order = models.PositiveIntegerField(blank=True) question_text = models.TextField() max_marks = models.PositiveIntegerField() def __str__(self): return f'{self.for_which_exam_set}: {self.question_text}' class Choices(models.Model): choice_text = models.TextField() is_correct = models.BooleanField() for_which_question = models.ForeignKey(Question, on_delete=models.CASCADE) admin.py from django.contrib import admin from django.forms import TextInput, Textarea from django.db import models from .models import Exam, ExamSet, Question, Choices # Register your models here. class QuestionInline(admin.TabularInline): model = Question extra = 0 ordering = ("question_order",) formfield_overrides = { models.TextField: {'widget': Textarea(attrs={'rows':3, 'cols':50})}, } class ChoicesInline(admin.TabularInline): model = Choices extra = 0 formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size':'20'})}, models.TextField: {'widget': Textarea(attrs={'rows':2, 'cols':30})}, } class QuestionAdmin(admin.ModelAdmin): list_display = ('question_text', 'max_marks', ) inlines = [ ChoicesInline ] formfield_overrides = { models.TextField: {'widget': Textarea(attrs={'rows':3})}, } class ExamSetAdmin(admin.ModelAdmin): inlines = [ QuestionInline ] admin.site.register(ExamSet, ExamSetAdmin) admin.site.register(Question, QuestionAdmin ) admin.site.register(Exam) And this gives the model inline something … -
Requesting multiple pages on the same route | Python, Flask
I want to request 2 pages (page and page2) to paginate 2 boxes on my website. However, I'm getting an error like below: Here are my entire codes: page = request.args.get('page', 1, type=int) comment_blogs1 = BlogInfo.query.filter(BlogInfo.blog_post_id.ilike(blog_validated_id)).order_by(BlogInfo.date.desc()) comment_blogs = comment_blogs1.paginate(page=page, per_page=2) comment_blogs_num = comment_blogs1.count() page2 = request.args.get('page2', 1, type=int) ideas1 = BlogIdea.query.filter(BlogIdea.blog_post_id.ilike(blog_validated_id)).order_by( BlogIdea.date.desc()) ideas = ideas1.paginate(page2=page2, per_page2=2) ideas_num = ideas1.count() I don't know why I'm wrong as I already named 2 pages with 2 different names. I'm struggling with this problem and I would greatly appreciate it if you could help me fix it. Thank you! -
How to point to last value in django
well, I tried to point to last value using last but it seems it shows to the last character in the data. So what I am trying to do is in data-words='["Front-End Developer", "Java Developer", "Python Developer"]' I have kept these value in database and I want to bring using for template but I don't want a comma after the last value but using for templete a comma comes and it does not work. Any suggestion on how I can point to the last data. -
Loading dynamic initial data in runtime in Django app
The issue: I have some models structure in my Django app: Company Category (category has fk relation to companies) Payment (it doesn't matter in this context, just for the big picture, every payment has a category and a company) Users can create companies. After that action, I want to load initial data for the most common categories of payments (there are about 30-40 categories, so it's not a good idea to hardcode it). What I've tried to do: I thought about Django's fixtures, but we can't modify them in runtime (to set fk relation to the exact company). So, how to load prepared fixtures with dynamic data and do it in runtime? Or maybe there is another way and another tool to implement this feature? -
why does my django application retain variables after program have been executed
def clean_html_1(soup, items=[],stripped_items=[]): text_list = [] for div in soup.find_all("td", attrs={"height":"24", "style":" padding-left:15px", "width":"200"}): text_list.append(div.stripped_strings) for i in range(len(text_list)): for gen in text_list[i]: items.append(gen) for x in items: if x != None: stripped_items.append(x.replace("\\", "")) if len(stripped_items) > 0: stripped_items.remove("Reference Code") print(stripped_items) return stripped_items def process_data(html): soup = BeautifulSoup(html, 'html5lib') items = clean_html_1(soup) it = iter(items) trans_details = dict(zip(it, it)) return trans_details When I run this code, the print stripped items give values like this ['Account Number', '232****313', 'Effective Date', 'Wednesday, June 17, 2020', 'Currency Naira', 'NGN', 'Description', 'MC DB NG Sd PayP Card Issuance Transfer | 48 | 17/06/2020', 'Reference Code', 'Branch', 'Head Office', 'Transaction Type', 'DEBIT', 'Date of Transaction', '17/06/2020 12:22:57 PM', 'Amount', '10,000.00', 'Current Balance', '4,000.00', 'Available Balance', '4,000.00'] But when I run it again in a few seconds, with an updated value, I get this ['Account Number', '232****313', 'Effective Date', 'Wednesday, June 17, 2020', 'Currency Naira', 'NGN', 'Description', 'MC DB NG Sd PayP Card Issuance Transfer | 48 | 17/06/2020', 'Reference Code', 'Branch', 'Head Office', 'Transaction Type', 'DEBIT', 'Date of Transaction', '17/06/2020 12:22:57 PM', 'Amount', '10,000.00', 'Current Balance', '4,000.00', 'Available Balance', '4,000.00', 'Account Number', '232****313', 'Effective Date', 'Wednesday, June 17, 2020', 'Currency Naira', 'NGN', 'Description', 'MC DB … -
Django: Passing multiple keys into AJAX including a JavaScript seralised form and parsing them in python
What I need I'm trying to find a way to send a multi layered dictionary via AJAX to my server, including a JavaScript seralised form with the use of serialize(). The issue When I use data: frm.serialize();. It's a single layered json and it is easily parsed when returned to server with result: <QueryDict: {'csrfmiddlewaretoken': ['6aTZ7xey90sczae15069ZlbIiE7gVWW69RyeJBptUxadbgnBo8t8R0Nskg8S8Jzb', '6aTZ7xey90sczae15069ZlbIiE7gVWW69RyeJBptUxadbgnBo8t8R0Nskg8S8Jzb'], 'days': ['Mon', 'Wed'], 'no_weeks': ['1']}> Then when using a nested dictionary with data: {'form':frm.serialize(),'additional_data':12,'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()}``` I get: <QueryDict: {'form': ['csrfmiddlewaretoken=IF2D4vTBjaQSsrE4oY3Lb36jekPB5nZbLmHSGz4w4HyT4xNEH6qK3II3gWQdiaCg&days=Mon&days=Thu&no_weeks=2&csrfmiddlewaretoken=IF2D4vTBjaQSsrE4oY3Lb36jekPB5nZbLmHSGz4w4HyT4xNEH6qK3II3gWQdiaCg'], 'additional_data': ['12'], 'csrfmiddlewaretoken': ['IF2D4vTBjaQSsrE4oY3Lb36jekPB5nZbLmHSGz4w4HyT4xNEH6qK3II3gWQdiaCg']}> What i've tried I have attempted with use of this answer to use urllib to parse the form section of the data into a separate variable. Like so: x = parse_qs(urllib.parse.urlparse(request.POST['form']).query) This returns an empty dicitonary. Code HTML <form method="post" id="replicate_form"> [..more code] </form> Javscript function send_replication_data() { var frm = $('#replicate_form') var form_server_response = submit_formdata(frm) } // parent function to handle replcation form saving $('#create_replicate_booking_button').on('click', function() { send_replication_data() }); // submit booking data ajax function submit_formdata(frm) { var tmp = $.ajax({ type: frm.attr('method'), async:false, url: window.location.href, data: {'form':frm.serialize(), 'additional_data':12, 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()} }); return tmp.responseJSON; } Possibly I could somehow make use of whatever Django is doing in it's middleware to a parse the form data in … -
Comparing ForeignKey Values In A Form Values Outside The Form
I'm displaying a table. Among the static information on the table I want to insert the checkbox 'read' which is attached to a single User/Book pair. I cannot figure out how to compare the current book in my outter loop with the book in my inner form loop in order to output the checkbox matching the book. I have tried many ways of accessing form.book.id, id being the book's id in the DB, not an attribute of the Book model. I think I may have to add an id field to my UserBookData model. class UserBookData(models.Model): user = models.ForeignKey(Users, related_name='user_book_data', on_delete=models.CASCADE) book = models.ForeignKey(Book, on_delete=models.CASCADE) read = models.BooleanField() {% for book in user.books.all %} <tr> <td>{{ book.name }}</td> <td>{{ book.author}}</td> {% for item in form %} # this -> {% if item.book.id == book.id %} <td>{{ item.read }}</td> {% endif %} {% endfor %} Thank you. -
stripe coupon code functionality in django
This is my dj-stripe view function for making a subscription, now I want to add a coupon functionality to it where a customer can enter a coupon code and get 15% off the subscription. How can I implement it in this function? def create_sub(request): if request.method == 'POST': # Reads application/json and returns a response data = json.loads(request.body) payment_method = data['payment_method'] stripe.api_key = djstripe.settings.STRIPE_SECRET_KEY payment_method_obj = stripe.PaymentMethod.retrieve(payment_method) djstripe.models.PaymentMethod.sync_from_stripe_data(payment_method_obj) try: # This creates a new Customer and attaches the PaymentMethod in one API call. customer = stripe.Customer.create( payment_method=payment_method, email=request.user.email, invoice_settings={ 'default_payment_method': payment_method } ) djstripe_customer = djstripe.models.Customer.sync_from_stripe_data(customer) request.user.customer = djstripe_customer # At this point, associate the ID of the Customer object with your # own internal representation of a customer, if you have one. # print(customer) # Subscribe the user to the subscription created subscription = stripe.Subscription.create( customer=customer.id, items=[ { "price": data["price_id"], }, ], expand=["latest_invoice.payment_intent"] ) djstripe_subscription = djstripe.models.Subscription.sync_from_stripe_data(subscription) request.user.subscription = djstripe_subscription request.user.save() return JsonResponse(subscription) except Exception as e: return JsonResponse({'error': (e.args[0])}, status =403) else: return HTTPresponse('requet method not allowed')