Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filtering with wildcards in Django Rest Framework
I'm looking for a way to be able to filter my dataset in DRF using a wildcard. For example; I want to return any hostname in the below model that starts with 'gb'. I also have some requirements to search in the middle and the end of the hostname depending on usecase. I'd expect to be able to hi the following endpoint: /devices/?host_name=gb* and it return everything that has a host_name starting with gb. Model: class Device(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) host_name = models.CharField(max_length=64) mgmt_ip_address = models.GenericIPAddressField() domain_name = models.CharField(max_length=64) class Meta: ordering = ['host_name'] def __str__(self): return self.host_name Serializer: class DeviceSerializer(serializers.HyperlinkedModelSerializer): id = serializers.ReadOnlyField() class Meta: model = Device fields = '__all__' View: class DeviceViewSet(viewsets.ModelViewSet): permission_classes = (DjangoModelPermissions,) queryset = Device.objects.all() serializer_class = DeviceSerializer filter_backends = [DjangoFilterBackend, filters.rest_framework.DjangoFilterBackend, drf_filters.SearchFilter] filter_fields = ['id', 'host_name', 'mgmt_ip_address', ] I have tried creating custom filters but not sure that is the right approach since I haven't been able to get it working. -
Using Django, should I implement two different url mapping logics in my REST API and web application, and how?
I have a Book model an instance of which several instances of a Chapter model can be linked through Foreign Key: class Book(models.Model): pass class Chapter(models.Model): book = models.ForeignKey(to=Book, ...) class Meta: order_with_respect_to = "book" I decided to use Django both for the RESTful API, using Django Rest Framework, and for the web application, using Django Template. I want them separate as the way should be open for another potential application to consume the API. For several reasons including administration purposes, the API calls for a url mapping logic of this kind: mylibrary.org/api/books/ mylibrary.org/api/books/<book_id>/ mylibrary.org/api/chapters/ mylibrary.org/api/chapters/<chapter_id>/ For my web application, however, I would like the user to access the books and their contents through this url mapping logic: mylibrary.org/books/ mylibrary.org/books/<book_id>-esthetic-slug/ mylibrary.org/books/<book_id>-esthetic-slug/chapter_<chapter_order>/ The idea is the router to fetch the book from the <book_id>, whatever the slug might be, and the chapter according to its order and not its ID. Now I need some advice if this is desirable at all or if I am bound to encounter obstacles. For example, how and where should the web app's <book_id>/<chapter_order> be "translated" into the API's <chapter_id>? Or if I want the web app's list of books to offer automatically generated slugged links … -
Using value from URL in Form Wizard for Django
I'm trying to use this Form Wizard to design a multipage form in Django. I need to catch a value from the URL, which is a client's ID, and pass it to one of the Forms instance, as the form will be built dynamically with specific values for that client. I have tried redefining the method get_form_kwargs based on this thread, but this isn't working for me. I have the following code in my views.py: class NewScanWizard(CookieWizardView): def done(self, form_list, **kwargs): #some code def get_form_kwargs(self, step): kwargs = super(NewScanWizard, self).get_form_kwargs(step) if step == '1': #I just need client_id for step 1 kwargs['client_id'] = self.kwargs['client_id'] return kwargs Then, this is the code in forms.py: from django import forms from clients.models import KnownHosts from bson import ObjectId class SetNameForm(forms.Form): #Form for step 0 name = forms.CharField() class SetScopeForm(forms.Form): #Form for step 1, this is where I need to get client_id def __init__(self, *args, **kwargs): super(SetScopeForm, self).__init__(*args, **kwargs) client_id = kwargs['client_id'] clientHosts = KnownHosts.objects.filter(_id=ObjectId(client_id)) if clientHosts: for h in clientHosts.hosts: #some code to build the form When running this code, step 0 works perfectly. However, when submitting part 0 and getting part 1, I get the following error: _init_() got an unexpected keyword … -
How to receive the emails from the user, using office365 mail credentials, In `Django`?
As office 365 requires to use only the HOST_USER mail as the sender, tha mail which was used to buy the office365 credentials. So how can we receive the mail from the user. -
how to jquery ajax json response for loop / django
django model class UserAlbum(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='albums') album_photos = models.ManyToManyField(Photo, through='AlbumPhoto') album_name = models.CharField(max_length=50, blank=False) is_private = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-date_created'] def __str__(self): return f"{self.user}'s album [{self.album_name}]" def get_absolute_url(self): return reverse('album:album', args=[self.user, str(self.id)]) django view @login_required def get_album_list(request): if request.method == 'GET': user = request.user albums = user.albums.all() return JsonResponse(serializers.serialize('json', albums), safe = False) script $("#album_list_modal_button").click(function () { $.ajax({ type: "GET", url: "{% url 'album:get_album_list' %}", dataType: "json", success: function (response) { if (response) { //test $("#modal_body_album_list").html(response) //loop test 1 $.each(response, function(i, item) { $("#modal_body_album_list").append(item.fields.album_name); }); //loop test 2 for (var i = 0; i < response.length; i++) { $('#modal_body_album_list').append('<li>'+response[i].fields.album_name+'</li>'); } } else { $("#modal_body_album_list").html('None'); } }, error: function (request, status, error) { window.location.replace("../user/login") }, }); }) what i need to do is print each albums name using iteration only test part works and printed like this. [{"model": "album.useralbum", "pk": 6, "fields": {"user": 6, "album_name": "test album name1", "is_private": true, "date_created": "2021-03-26T19:20:23.571"}}, {"model": "album.useralbum", "pk": 4, "fields": {"user": 6, "album_name": "test album name2", "is_private": false, "date_created": "2021-03-18T20:30:09.575"}}] i've searched and find two way of loop. But these are not working. please help!! -
Python DJANGO input fields
I want to make simple "calculator" on django app. I want to make 2 fields. Visitor put 2 numbers into fields and multiplication this numbers. I want to make input1 = 2, input2 = 3 and output will be 6. only this inputs make customer on website. Thanks for help and hve a great day -
How to handle excel file sent in POST request in Django?
I sent an excel file in a post request to my back-end and I tried handling the file using the following: def __handle_file(file): destination = open('./data.xslx', 'wb') for chunk in file.chunks(): destination.write(chunk) destination.close() However, the output from that is not an excel file. It is a collection of XML files. My end goal is to obtain a data frame from the file data that was sent so that I can extract the data. What is a clean way of handling this type of file? -
Why do I get "HTTP Error 404: Not Found" when installing pyaudio with pipwin in Python Django project in Windows 10?
I'm trying to install pyaudio with pipwin in a Python Django project in Windows 10. I first run CMD as admin in Windows 10. Then I run the command: pipwin install pyaudio and I get the following error: raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 404: Not Found the full output from the command: Package `pyaudio` found in cache Downloading package . . . https://download.lfd.uci.edu/pythonlibs/z4tqcw5k/PyAudio-0.2.11-cp38-cp38-win_amd64.whl PyAudio-0.2.11-cp38-cp38-win_amd64.whl Traceback (most recent call last): File "C:\Users\Knowe\AppData\Local\Programs\Python\Python38\Scripts\pipwin-script.py", line 11, in <module> load_entry_point('pipwin==0.5.1', 'console_scripts', 'pipwin')() File "c:\users\knowe\appdata\local\programs\python\python38\lib\site-packages\pipwin\command.py", line 103, in main cache.install(package) File "c:\users\knowe\appdata\local\programs\python\python38\lib\site-packages\pipwin\pipwin.py", line 300, in install wheel_file = self.download(requirement) File "c:\users\knowe\appdata\local\programs\python\python38\lib\site-packages\pipwin\pipwin.py", line 294, in download return self._download(requirement, dest) File "c:\users\knowe\appdata\local\programs\python\python38\lib\site-packages\pipwin\pipwin.py", line 290, in _download obj.start() File "c:\users\knowe\appdata\local\programs\python\python38\lib\site-packages\pySmartDL\pySmartDL.py", line 267, in start urlObj = urllib.request.urlopen(req, timeout=self.timeout, context=self.context) File "c:\users\knowe\appdata\local\programs\python\python38\lib\urllib\request.py", line 222, in urlopen return opener.open(url, data, timeout) File "c:\users\knowe\appdata\local\programs\python\python38\lib\urllib\request.py", line 531, in open response = meth(req, response) File "c:\users\knowe\appdata\local\programs\python\python38\lib\urllib\request.py", line 640, in http_response response = self.parent.error( File "c:\users\knowe\appdata\local\programs\python\python38\lib\urllib\request.py", line 569, in error return self._call_chain(*args) File "c:\users\knowe\appdata\local\programs\python\python38\lib\urllib\request.py", line 502, in _call_chain result = func(*args) File "c:\users\knowe\appdata\local\programs\python\python38\lib\urllib\request.py", line 649, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 404: Not Found Why can I not install pyaudio? Thanks! -
Error while installing mysqlclient in django project on cPanel
I've been trying to solve this problem for a couple of days. I am trying to put my Django project in a venv on cPanel and install mysqlclient. So after setting up my Python (version = 3.7.8) on Cpanel, I installed Django version 3.1.7 and mysqlclient from the terminal using pip install django and pip install mysqlclient. However when I try to install mysqlclient, this error pops out. Using cached mysqlclient-2.0.3.tar.gz (88 kB) Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/canggihmallmy/virtualenv/django_test/3.7/bin/python3.7_bin -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-ct08p_k4/mysqlclient_5cd61bc8b4de40efb5731cfe082b4d65/setup.py'"'"'; __file__='"'"'/tmp/pip-install-ct08p_k4/mysqlclient_5cd61bc8b4de40efb5731cfe082b4d65/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))'bdist_wheel -d /tmp/pip-wheel-scx4wswm cwd: /tmp/pip-install-ct08p_k4/mysqlclient_5cd61bc8b4de40efb5731cfe082b4d65/ Complete output (43 lines): mysql_config --version ['10.0.38'] mysql_config --libs ['-L/usr/lib64', '-lmysqlclient', '-lpthread', '-lz', '-lm', '-ldl', '-lssl', '-lcrypto'] mysql_config --cflags ['-I/usr/include/mysql', '-I/usr/include/mysql/..'] ext_options: library_dirs: ['/usr/lib64'] libraries: ['mysqlclient', 'pthread', 'm', 'dl'] extra_compile_args: ['-std=c99'] extra_link_args: [] include_dirs: ['/usr/include/mysql', '/usr/include/mysql/..'] extra_objects: [] define_macros: [('version_info', "(2,0,3,'final',0)"), ('__version__', '2.0.3')] /opt/alt/python37/lib64/python3.7/distutils/dist.py:274: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.7 creating build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/release.py -> … -
Circular import Django and im lost ... :(
I got my services.py where i am trying to make api connections based on some tables in models(fex user): import requests import json from django.contrib.auth.models import User from .models import UserProfile,House have a function here that call 2 database queries to get more info to connect towards the API and my models.py contains: from django.db import models from django.contrib.auth.models import User from django.contrib.auth.signals import user_logged_in from .services import * connectApi() -> function in services.py -
How do I sort a Queryset according to a list?
For example, I do this: m.objects.filter (id__in = [3,1,8]) And it is necessary that the elements in the queryset go in order, that is, first id = 3, then id = 1, then id = 8, etc. But in the end, you need a queryset, not a list! -
Set up Flutter Client for Django/GraphQL
I've been trying to get this to work, it looks like it should be fairly simple but I just can't find a recent reference, the README file at pub.dev isn't all that clear and the only other examples are all from before flutter 2.0, so I don't know if that's what it is. import 'package:flutter/material.dart'; import 'package:graphql_flutter/graphql_flutter.dart'; String search = """ query { units { title } } """; void main() async { WidgetsFlutterBinding.ensureInitialized(); final HttpLink httpLink = HttpLink( 'http://localhost:8000/graphql/', ); ValueNotifier<GraphQLClient> client = ValueNotifier( GraphQLClient( link: httpLink, // The default store is the InMemoryStore, which does NOT persist to disk cache: GraphQLCache(store: InMemoryStore()), ), ); runApp(GraphQLProvider( child: MaterialApp( title: "APIClient", home: MyApp(), ), client: client, )); } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { @override Widget build(BuildContext context) { return Query( options: QueryOptions(document: gql(search)), builder: (QueryResult result, {fetchMore, refetch}) { if (result.data == null) { return Text("No data found"); } return ListView.builder( itemBuilder: (BuildContext context, int index) { return Text(result.data!['title'][index]); }, itemCount: result.data!.length, ); }); } } I already got a django/graphql server running on localhost:8000/graphql. Any help would really help. thx, oscrr -
Users reset password
I get a 404 not found error when users trie to reset their password. It worked fine until I had to reinstall my server due to OVH datacenter fire ... I also uprade Django version to the last one. You can try here : https://www.lamontagnesolitaire.fr/start/forget/ My views def view_forget(request): media = settings.MEDIA if request.method == 'POST': form = ForgetForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] try: user = User.objects.get(email=email) except: messages.add_message(request, messages.INFO, 'Vérifiez votre messagerie, un e-mail vous a été envoyé !') messages.add_message(request, messages.INFO, 'Vous pouvez fermer cette page.') return redirect(view_forget) token = default_token_generator.make_token(user) uidb64 = urlsafe_base64_encode(force_bytes(user.pk)) from django.core.mail import send_mail corps = 'Bonjour, la modification de votre mot de passe est à effectuer en suivant ce lien : https://www.lamontagnesolitaire.fr/start/forget/reset/%s/%s' %(uidb64, token) subject = "Changement de mot de passe" message = corps sender = "Equipe@LaMontagneSolitaire.fr" recipients = [email, ] send_mail(subject, message, sender, recipients) messages.add_message(request, messages.INFO, 'Vérifiez votre messagerie, un mail vous a été envoyé !') messages.add_message(request, messages.INFO, 'Vous pouvez fermer cette page.') else: form = ForgetForm() return render(request, 'forget.html', locals()) def view_forget_reset(request, uidb64, token): media = settings.MEDIA if uidb64 is not None and token is not None: from django.utils.http import urlsafe_base64_decode uid = urlsafe_base64_decode(uidb64) try: from django.contrib.auth import get_user_model from django.contrib.auth.tokens … -
const product = products.find(p => Number(p._id) === Number(match.params.id)) geting type error
import React from 'react' import { Link } from 'react-router-dom' import { Row, Col, Image, ListGroup, Button, Card } from 'react-router-bootstrap' import Rating from '../components/Rating' import products from '../products' function ProductScreen({ match }) { const product = products.find(p => Number(p._id) === Number(match.params.id)) return ( {product.name} ) } export default ProductScreen -
DetailView with UUID getting NoReverseMatch
It was working with a normal pk but when I changed to UUID it stopped working. Model: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) order_number = models.CharField(primary_key=True, default=uuid.uuid4().hex[:5].upper(), max_length=50, editable=False) product_cost = models.IntegerField(default=0) order_cost = models.IntegerField(default=0) order_status = models.CharField(max_length=100, default='Pending') completion_date = models.DateField() def __str__(self): return self.order_number url: path('panel/orders/<uuid:pk>', views.OrderDetail.as_view(), name='order-detail') template: <a href="{% url 'order-detail' o.pk %}" aria-current="page" class="dropdown-link w-inline-block w--current"> Error: Reverse for 'order-detail' with arguments '('65830',)' not found. 1 pattern(s) tried: ['panel/orders/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$'] -
using following approach: for key in ("a1", "a2", "a3" .....) How can I change values of list members? [closed]
I have something like this: for key in ("a1", "a2", .....) if key == "": (the member which is empty) = getattr(object, key) Is there a way to do so? -
How to handle large numbers in python, django models for mysql?
How to handle large numbers in python and django models for mysql datatype? I want to store large decimal numbers e.g mass of the Sun in kg (1.98847±0.00007)×10^30 kg and other large numbers of physics and astronomy. What max_digits and decimal_places will I need? For simple longitude, latitude I use 11,6: models.DecimalField(max_digits=11, decimal_places=6, null=False) >>> s = 1.9884723476542349808764 >>> s 1.988472347654235 >>> -
Exception caused due to DateTimeField in Django unit test cases with SQLite
We are by default running unit tests & production against postgres. Normally it takes almost 10 mins to run 58 test cases. To achieve faster test performance for dev environment, I am experimenting with running tests against SQLite3 locally by providing different test specific configuration. But I ran into issues while creating object with DateTimeField as follows. Default auto_now and auto_now_add DateTimeField seems to be working fine. import dateutil.parser st1 = dateutil.parser.parse('2021-02-28T11:00:00Z') et1 = dateutil.parser.parse('2021-02-28T12:00:00Z') self.event2, created = Event.objects.get_or_create(name='test_event_2', owner=owner_id, start_time=st1, end_time=et1) Exception: Traceback (most recent call last): File "/home/vikram/.virtualenvs/my_venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/vikram/.virtualenvs/my_venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: unrecognized token: ":" -
User permissions in django using decorators
I am following a tutorial from youtube he used some codes that I did not understand please explain it if anyone can. def allowed_user(allowed_roles=[]): def decorators(view_func): def wrapper(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not athorize to veiw this page') return wrapper return decorators -
TypeError at /approve/1
def approve_qoute(request, application_id): approve = get_object_or_404(Application, pk=application_id, created_by=request.user) if request.method == 'POST': form = EditStatusForm(request.POST, instance=approve) if form.is_valid(): approve = form.save(commit=False) approve.status = request.POST.get('status') approve.save() return redirect('dashboard') else: form = EditStatusForm(instance=approve) return render(request, 'job/approve_qoute.html',{'form':form, 'approve':approve}) -
KeyError: 'id' in django rest framework when trying to use update_or_create() method
I am trying to update the OrderItem model using update_or_create() method. OrderItem model is related to the Order model with many to one relationship ie with a Foreignkey. I am trying to query the orderitem object using id and update the related fields using default as you can see, but got this error. My models: class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) total_price = models.CharField(max_length=50,blank=True,null=True) #billing_details = models.OneToOneField('BillingDetails',on_delete=models.CASCADE,null=True,blank=True,related_name="order") def __str__(self): return self.user.email class Meta: verbose_name_plural = "Orders" ordering = ('-id',) class OrderItem(models.Model): #user = models.ForeignKey(User,on_delete=models.CASCADE, blank=True) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants,on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) order_item_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') My view: class UpdateOrderView(UpdateAPIView): permission_classes = [AllowAny] queryset = Order.objects.all() serializer_class = OrderUpdateSerializer My serializers: class OrderUpdateSerializer(serializers.ModelSerializer): order_items = OrderItemUpdateSerializer(many=True) billing_details = BillingDetailsSerializer() class Meta: model = Order fields = ['id','ordered','order_status','order_items','billing_details'] def update(self, instance, validated_data): instance.order_status = validated_data.get('order_status') instance.ordered = validated_data.get('ordered') #billing_details_logic billing_details_data = validated_data.pop('billing_details',None) if billing_details_data is not None: instance.billing_details.address = billing_details_data['address'] instance.billing_details.save() #order_items_logic instance.save() order_items_data = validated_data.pop('order_items') # print(order_items_data) #instance.order_items.clear() for order_items_data in order_items_data: oi, created = OrderItem.objects.update_or_create( id= order_items_data['id'], defaults={ 'quantity' : order_items_data['quantity'], 'order_item_status': … -
How add variable to django request from my front-end?
I am developing web app, with djangorestframework on the back and Vue.js on the front. Interface was translated to a few language. On the site footer user can see icons of language represented country flag. After hit the need icon, app translate all text to required language. All actions for translate do in front and my backend know nothing about what is language was chosen. Now I want to tell my back-end about chosen language, how can I do it? I think to add a variable language to my django request object, but I can find nothing about it. Any ideas? -
django error check in function reaching Ajax call
The scenario is adding an item to a cart and also choosing a fabric with it. Two errors I want to show with an alert pop up: a) when either when no color is selected / e.g. general error b) Only 1 item with the same fabric allowed per cart Putting out the (a) general error message works. But I'm unsure how to trigger the error alert of my ajax from the if statement in my view from django. My Ajax form: var productForm = $(".form-product-ajax") productForm.submit(function(event){ event.preventDefault(); var thisForm = $(this) var actionEndpoint = thisForm.attr("data-endpoint"); var httpMethod = thisForm.attr("method"); var formData = thisForm.serialize(); $.ajax({ url: actionEndpoint, method: httpMethod, data: formData, success: function(data){ var submitSpan = thisForm.find(".submit-span") if (data.added){ $.alert({ title: "Success", content: "Product added", theme: "modern", }) submitSpan.html("<button type='submit' class='btn btn-success'>Add to cart</button>") } }, error: function(errorData){ $.alert({ title: "Oops!", content: data.message, theme: "modern" }) } }) }) Django carts.view simplified def cart_update(request): added = False error_messages = "Please check your selections." if str(product_obj.type).lower() == "fabric": cart_obj, new_obj = Cart.objects.new_or_get(request) fabric_obj = str(Fabric.objects.filter(name__contains=fabric_select).first()) for item in cart_obj.choices.all(): if fabric_obj == item.fabric_note: error_messages = "You've reached the maximum order amount for this fabric." # how to trigger ajax error: function() … -
How to frequently update some perticular field in database?
This is my model to store bus details. Here I have kept a field named bookedSeat to store which seat is booked ( input a-z or A-Z ).Every-time user book a seat a single character (inputted from user) should be added to bookedSeat field in database. class busDetails(models.Model): busID = models.AutoField(primary_key=True) arrival = models.CharField(max_length=50) destination = models.CharField(max_length=50) rent = models.IntegerField() distance = models.IntegerField() bookedSeat = models.CharField(max_length=100) def __str__(self): return self.arrival+' --> '+self.destination I am getting stuck at how to frequently update(add into existing) that particular database field(bookedSeat)? ( without adding any new row ) How to solve this problem? Thank You :) -
How do I attach a PaymentMethod to a stripe Customer in DjStripe?
I have the following Django class: class PurchaseSubscriptionView(APIView): def post(self, request, user_id): price_name = request.data.get("price_name") payment_method = request.data.get("payment_method") user = User.objects.get(id=user_id) customer, created = djstripe.models.Customer.get_or_create(subscriber=user) payment_method_json = json.dumps(payment_method) customer.add_payment_method(payment_method_json) price = djstripe.models.Price.objects.get(nickname=price_name) customer.subscribe(price=price) Everything works until customer.add_payment_method(payment_method_json) At which point I get: stripe.error.InvalidRequestError: Request req_8KcCUrPg7z8Aok: No such PaymentMethod: '{\"id\": \"pm_1IaFMyJs57u3g5HDGoe83cGx\", \"object\": \"payment_method\", \"billing_details\": {\"address\": {\"city\": null, \"country\": null, \"line1\": null, \"line2\": null, \"postal_code\": null, \"state\": null}, \"email\": null, \"name\": null, \"phone\": null}, \"card\": {\"brand\": \"visa\", \"checks\": {\"address_line1_check\": null, \"address_postal_code_check\": null, \"cvc_check\": null}, \"country\": \"US\", \"exp_month\": 2, \"exp_year\": 2022, \"funding\": \"credit\", \"generated_from\": null, \"last4\": \"4242\", \"networks\": {\"available\": [\"visa\"], \"preferred\": null}, \"three_d_secure_usage\": {\"supported\": true}, \"wallet\": null}, \"created\": 1617002320, \"customer\": null, \"livemode\": false, \"type\": \"card\"}' What exactly is going on? I passed the PaymentMethod from my client after generating it - this should work, correct? Am I missing any steps?