Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
save function in form and if status change a date should be created and then check or compare the status if true save the status to database
models.py class Item(models.Model): status_choices = [('Requested', 'Requested'), ('Processing', 'Processing'), ('Completed', 'Completed')] status = models.CharField(choices=status_choices, max_length=50, null=True, blank=True, ) completed_date = models.DateTimeField(blank=True, null=True) requested_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) froms.py class ItemForm(forms.ModelForm): class Meta: model = Item fields = ['status', created_at, requested at] def __init__(self, *args, **kwargs): super(ItemForm, self).__init__(*args, **kwargs) self.fields['status'].initial = 'Requested' def save(): pass i want to override my form and at the time of instance if i change the form value to completed. i want the date in my model filled with today's date in the field 'completed_at' and save it to database also can anyone help me? -
Strange non-breaking space when copying text from website in Chrome
I am developing a website in Django. It is a movie database. For creating a movie reference, I am using a join function like this: ''.join(i for i in movies) As a result, I get the following references for movies: Titanic. Directed by <i>James Cameron</i>. 1997. Everything is perfect on the backend side. On the frontend side, everything is visually OK, but when I copy the string with the movie reference and paste it into Microsoft Word, a non-breaking space appears before the italicized item instead of the regular space (I've tried italicizing other items as well, and it appeared everywhere before them): Titanic. Directed by°James Cameron. 1997. I do not add any non-breaking spaces, and I've tested out the backend side, no nbsp's appear there. Moreover, when I inspect the page in Chrome... it shows no non-breaking spaces: Titanic. Directed by <i>James Cameron</i>. 1997. How come that it appears on copying? And how can I avoid this behavior? P.S. I've tried this out on the book referencing site https://www.citethisforme.com/, and it's all the same. When adding a journal, this non-expected nbsp appears right before the italicized journal title element. -
Django create data with OnetoOneField
Hello thanks for your time: i'm trying to add some data to my model table trough management/commands/create_data.py: 1º Question in other project of mine i can call python manage.py create_data create_data.py although in this one is not working. How do i call the right command? 2º Question besides that i guess i'm gonna recieve an error at user field on People model because should be an id. How do i get the id? pets/models.py: User = get_user_model() class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='person') birthday = models.DateField() cpf = models.CharField(max_length=11, validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return '%s' % (self.user) pets/management/commands/create_data.py: User = get_user_model() class GenerateUser(): username = None password = None def __init__(self, username, password): with open('User.txt') as file: for rows in file: self.username = slugify(rows) self.password = '12345' class GeneratePeople(): user = None documento = None birthday = None def __init__(self, documento, birthday): with open('People.txt') as file: for rows in file: t1 = rows.split(', ') self.user = slugify(t1[0]) self.documento = t1[1] self.birthday = t1[2] class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( 'file_name', type=str, help='ok') def handle(self, *args, **kwargs): username = GenerateUser.username password = GenerateUser.password user = GeneratePeople.user documento = GeneratePeople.documento birthday = GeneratePeople.birthday one = User( username=username, password=password ) one.save() peop = … -
Django m2m_changed signal for GenericRelation, is it possible?
Can it be used for a generic relation? I don't see it mentioned in the docs. A naive try of getting the through table: In [4]: Asset.related_images.through --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-4-d541db71a7a5> in <module>() ----> 1 Asset.related_images.through AttributeError: 'ReverseGenericManyToOneDescriptor' object has no attribute 'through' -
django check query return value or not
I need to get the destinationId value as query result from database, it works fine when there is matching value in database.If no match is there it results in error "matching query does not exist.".How can i solve this issue, also i need to run another query based ob=n the result,how can i check value exist or not? Am new to django and python, please help def get_route_list(request): if request.method == "POST": #Get the posted form areaDigit = request.POST['areaDigit'] productId = request.POST['productId'] destination_id=Routing_Dest_Area.objects.get(areaDigit=areaDigit).destinationId else: data = '' print(data) return render(request, 'routing/test.html',{'data':destination_id}) -
Implement serach in a corpus of document with Haystack an Whoosh
Hy, I am looking to add a search in some text (convert from pdf) to my app. I choice to use Whoosh. For the moment I have created an index of the documents with a Schema, create_in and add_document from Whoosh The index seems correct, I can read it with open_dir and reader from Whooosh. The link with my Django models is the name of the file in the Schema which contains an id, I am not sure it is the good way to link index with models ... Now I try to add a frontend form to allow user to search the index with a simple form CharFiled Google like and retrieve the original pdf document and I don't find the way to do this, the docs I found explain mainly how to search in models fields and not in an indexed corpus. Thanks for your time. -
Heroku cannot read '/etc/secret_key.txt', No such file or directory:
I successfully deployed a django app to heroku with my settings.py as such: SECRET_KEY = 'the_real_long_secret_key_itself', which of course is not recommended, but that was find for me just in this scenario as it is just a test and can be changed. Now back to my local environment, I decided to hide the key without changing it yet and according to django documents like this: # on settings.py with open('/etc/secret_key.txt') as s: SECRET_KEY = s.read().strip() And it works when I run server locally. But now when I try to commit & push like this: (herokuvirtualenv)tester1@test:~/$ git add -A (herokuvirtualenv)tester1@test:~/$ git commit -m "some editing" (herokuvirtualenv)tester1@test:~/$ git push heroku master It runs but ends up with this error message: remote: with open('/etc/secret_key.txt') as s: remote: FileNotFoundError: [Errno 2] No such file or directory: '/etc/secret_key.txt I have used search engines and there seems to be many ways to do this and it point that this should work, but there seems to be something I am omitting here. Could someone please help out? -
Django change choice before validation
I am trying to update a choice field before it is validated in Django. The reason for this is the choice field in question value is the Id of a model that i want to update. def fuelLogSystemOne(request): entries = FuelLogSystemOneMod.objects.all().order_by('date') products = productsMod.objects.all() if request.method == 'POST': form = forms.AddFuelLogOneForm(request.POST, request.FILES) productid = form['product'].value() product = productsMod.objects.get(id=productid) product_id = request.POST.get('product') form.fields['product'].choices = [(product.product_type, product.product_type)] if form.is_valid(): bucketsRemoved = form['buckets_added'].value() product.stock -= bucketsRemoved product.save(['stock']) instance = form.save(commit=False) instance.staff = request.user instance.save() return redirect('home') else: form = forms.AddFuelLogOneForm() return render(request,'systems/fuellogsystemone.html',{'form':form,'entry':entries,'products':products}) The below part is where i am trying to change the form data before it gets validated so it doesn't say 'Select a valid choice. 1 is not one of the available choices' product_id = request.POST.get('product') form.fields['product'].choices = [(product.product_type, product.product_type)] But when I first submit the form it is still saying 'Select a valid choice.' At what point does Django validate the form because I am changing the form before the is_valid() method and it still hits this error? -
Django REST Framework - cookies not being set via Response.set_cookie() call...?
I have the following standard Response setup in my DRF application: response = Response(data=response, status=status.HTTP_200_OK) I'm then attempting to add a split JWT header.payload and signature to the response headers with a response.set_cookie() call, as follows: max_age = 365 * 24 * 60 * 60 expires = datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age) response.set_cookie( key='JWT_ACCESS_HEADER_PAYLOAD', value=header_payload, httponly=False, expires=expires.strftime("%a, %d-%b-%Y %H:%M:%S UTC"), max_age=max_age ) response.set_cookie( key='JWT_ACCESS_SIGNATURE', value=signature, httponly=True, expires=expires.strftime("%a, %d-%b-%Y %H:%M:%S UTC"), max_age=max_age ) return response I can't see anything wrong with what I have done thus far: Yet, for some reason, the only cookies set on the client side are as follows: What have I done wrong here?? The actual output in the headers seem to be a valid SetCookie value: JWT_ACCESS_HEADER_PAYLOAD=aSasas; expires=Sat, 03-Apr-2021 10:24:31 GMT; Max-Age=31536000; Path=/ JWT_ACCESS_SIGNATURE=asaSasaS; expires=Sat, 03-Apr-2021 10:24:31 GMT; HttpOnly; Max-Age=31536000; Path=/ -
Manage models inheritance in Django admin
I'm developing with my team a Django webapp which provides authentication and users profile creation. Basically, we are dealing with a model Profile which extends django.auth.contrib.models.User implementing One-to-One link method, as shown below model.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateField(default=datetime.date.today) # other custom fields def __str__(self): return self.user.username Since we have registered the model in admin.py, it appears in Django admin panel, as it should be. Then, we have introduced another model PersonalTrainer which is an intherited class of Profile one. admin.py from django.contrib import admin from usermanager.models import Profile, PersonalTrainer admin.site.register(Profile) admin.site.register(PersonalTrainer) Is there any programmatically method to organize PersonalTrainer instances in a such a way they appear both in Profile section and PersonalTrainer section? In other words, we'd like to have a PersonalTrainer instance which appears in auth User model, Profile model and PersonalTrainer model. -
Django messages not working in admin model_save()
I have the following save_model in MyModelAdmin, the print statement gives output in console, but on django admin, i can see default messages, but not my error message for some reason. class MyModelAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): try: transfer_money() super(MyModelAdmin, self).save_model(request, obj, form, change) except Exception as e: print(e) messages.add_message(request, messages.INFO, str(e)) -
How can I convert my class-based view to function-based views? - Django
I am trying to change all my class-based views to function-based views and I am having difficulty converting the following class: class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, UpdateView): model = Post fields = ['image', 'title', 'category', status', 'description'] template_name = 'blog/post-form.html' success_message = 'Your post has been updated.' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False def get_context_data(self, **kwargs): context = super(PostUpdateView, self).get_context_data(**kwargs) context['title'] = 'Update post' context['submit'] = 'Update' return context def get_success_url(self): author = self.object.author return reverse_lazy( 'profile', kwargs={'author': author.username}) The function and form should do exactly what this class-based view does, so if anyone can help me out, please let me know. -
Object level authorization in a Django Rest Framework viewset
I'm creating an API with Django Rest Framework (DRF) and wondering where I should handle object level authorization. So far I've created an Organization model and a custom user model with email being the unique identifier instead of username. Organizations and users are currently connected through a many-to-many field. What I'd like to do is make sure that when a user hits my API they're only able to do the standard CRUD actions on the models that are linked to the users respective organization. As an example here's my current UserViewSet where I've overriden then get_queryset method to filter the User queryset to only return other users who are apart of the same organizations as the user calling the API: class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer def get_queryset(self): User = get_user_model() user = self.request.user organizations = user.organization.all() return User.objects.filter(organization__in=organizations) What's considered best practice to extend these limitations to other viewset actions? For example, if I want to make sure that the user can only create and add other users into the organizations they're linked to, should I override the create method in the viewset and perform a validation there that the organization which was passed in the request data is the … -
Why does django gives me 405 error on the first instance
I'm writing this code class ParentCancelView(ProfileTypeRequiredMixin, UpdateView): profile_type = 'parent' model = Books template_name = 'library/student_parent_list_view.html' def post(self, *args, **kwargs): recipient = self.request.user.parent.recipient.first() queryset = self.get_queryset() pk = self.kwargs.get('pk') if pk: queryset.filter( pk=pk, recipient=recipient ).update(reserve_status='cancelled') return super(ParentCancelView, self).post(*args, **kwargs) urls.py url( r'^reserve/parent/(?P<pk>\d+)/$', views.ParentCancelView.as_view(), name='reserve_parent_cancel' ), html <form method="POST" action="{% url 'library:reserve_cancel' pk=book.pk %}"> {% csrf_token %} <button class="btn btn-xs btn-primary" type="submit" {% if book.reserve_status != 'for_approval' %}disabled{% endif %}>Cancel Reservation {{ book.pk }}</button> </form> when Im trying to cancel it works fine on second, third but not on first instance it has no error but it gave me 405, does any one what went wrong here? thanks -
Add extra non-model attribute to serializer
I have following scenario: I have a device model with a "deleted" field. When it's true, the device is deleted. I need a endpoint to change the value of that field. I want to do this in a request by giving the device_id and a deleted_flag. I was able to just change the deleted attribute without passing the deleted_flag attribute. But I'm stuck if I want to give the deleted_flag attribute to the serializer because it's a non model field.. This is my code: test: def test_undelete_device(self): self.client.force_login(self.admin_user) url = reverse( "admin-device-change-status", kwargs={"device_pk": self.device.id}, ) response = self.client.patch(url, data={"deleted_flag": False}) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data["deleted"], False) serializer: class AdminDeviceChangeStatusSerializer(serializers.ModelSerializer): deleted = serializers.BooleanField() deleted_flag = serializers.SerializerMethodField() class Meta: model = Device fields = ["deleted", "deleted_flag"] def validate_deleted(self, deleted): return deleted def validate_deleted_flag(self, deleted_flag): return deleted_flag def get_deleted_flag(self, deleted_flag): return deleted_flag view: def patch(self, request, device_pk): """ Change deleted status device """ device = get_object_or_404(Device, pk=device_pk) serializer_class = AdminDeviceChangeStatusSerializer serializer = serializer_class(device, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() if serializer.validated_data.get("deleted_flag") == False: device.deleted = True else: device.deleted = False device.save() return Response(serializer.data, status=status.HTTP_200_OK) stacktrace: TypeError: Object of type 'Device' is not JSON serializable -
My code is working on codepen but not on my editor
My code is working on codepen but not on my editor (PyCharm). This is part of django project. By not working I mean I get a blank page, with no output (no text). I have tried to read a few answers addressing a similar issue but none of these solutions seem to be working for me/or I am not applying them correctly. Specifically adding the full URL path for getting ScrollWatch through CDN. Here is a sample of my code html { % load script % } <html lang="en"> <head> <meta charset="UTF-8"> <title>The Gradient Boost</title> <link rel="stylesheet" href="{% static 'second/css/app/book.css' %}"> <script src="https://cdn.jsdelivr.net/npm/scrollwatch@2.0.1/dist/ScrollWatch-2.0.1.min.js"></script> </head> <body> <h2><div data-scroll-watch>First Text</div></h2> <h2><div data-scroll-watch>Second Text</div></h2> <h3><div data-scroll-watch>Third Text</div></h3> <script src="{% static 'second/js/app/book.js' %}"></script> </body> </html> css location -> static\second\css\app\book.css .watch-container { font-size: 2em; width: 75%; height: 150px; padding: 20px; margin: 50px auto; background-color: #0681CD; color: #fff; overflow: auto; text-align: center; } div { text-align: center; font-size: 1em; margin: 200px 0; opacity: 0; transition: opacity 1s; font-weight: normal } div.scroll-watch-in-view { opacity: 1; } and javascript location -> static\second\js\app\book.js (function() { var addElements = function() { var txt = document.createTextNode('Testing'); var el; el = document.createElement('div'); el.appendChild(txt); document.body.appendChild(el); // If we want newly injected elements to … -
argument of type 'QuerySet' is not iterable Django error
In my webapp, I have a friends feature, but one of the if statements produces an error Here is my UserProfileInfo model class UserProfileInfo(models.Model): connection = models.ManyToManyField(User,blank=True,related_name='follow_profile') And now here is my view: def friend_actions(request,username=None): current_user = request.user.userprofileinfo user = request.user # username = get("username") username = User.objects.get(username=username) other_user = get_object_or_404(UserProfileInfo,user__username=username) # other_user = UserProfileInfo.objects.get(username=username) url = other_user.get_absolute_url() if other_user in current_user.connection.all(): current_user.connection.remove(other_user) else: current_user.connection.add(other_user) return HttpResponseRedirect(url) However, this produces the following error: argument of type 'QuerySet' is not iterable Full traceback Traceback: File "C:\Users\User\.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\User\.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\User\.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\interests-site\interests-drf\mainapp\views.py" in friend_actions 453. if other_user in current_user.connection.all(): Exception Type: TypeError at /mainapp/profile/donnellan0007/connect/ Exception Value: argument of type 'QuerySet' is not iterable I am wondering how I can stop this error from occurring. I have been stumped by it all day -
Django hosting trouble with django.wsgi
I registered everything as it is written in the instructions for django hosting provider (jino), but errors popped up, which I can't even come close to understanding. [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] mod_wsgi (pid=61341): Failed to exec Python script file '/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi'. [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] mod_wsgi (pid=61341): Exception occurred processing WSGI script '/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi'. [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] Traceback (most recent call last): [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] File "/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi", line 4, in <module> [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] exec(open(activate_this).read(), dict(__file__=activate_this)) [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] FileNotFoundError: [Errno 2] \xd0\x9d\xd0\xb5\xd1\x82 \xd1\x82\xd0\xb0\xd0\xba\xd0\xbe\xd0\xb3\xd0\xbe \xd1\x84\xd0\xb0\xd0\xb9\xd0\xbb\xd0\xb0 \xd0\xb8\xd0\xbb\xd0\xb8 \xd0\xba\xd0\xb0\xd1\x82\xd0\xb0\xd0\xbb\xd0\xbe\xd0\xb3\xd0\xb0: '/home/users/m/marselabdullin/projects/caparol_center_spb_decision/env/bin/activate_this.py' [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] mod_wsgi (pid=37979): Failed to exec Python script file '/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi'. [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] mod_wsgi (pid=37979): Exception occurred processing WSGI script '/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi'. [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] Traceback (most recent call last): [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] File "/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi", line 4, in <module> [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] exec(open(activate_this).read(), dict(__file__=activate_this)) [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] FileNotFoundError: [Errno 2] \xd0\x9d\xd0\xb5\xd1\x82 \xd1\x82\xd0\xb0\xd0\xba\xd0\xbe\xd0\xb3\xd0\xbe \xd1\x84\xd0\xb0\xd0\xb9\xd0\xbb\xd0\xb0 \xd0\xb8\xd0\xbb\xd0\xb8 \xd0\xba\xd0\xb0\xd1\x82\xd0\xb0\xd0\xbb\xd0\xbe\xd0\xb3\xd0\xb0: … -
Problems with django error handling with ajax
I want to create ajax error handling function for that. Problems can be in the JsonResponse part.Also how to implement that in the template? I tried to create ajax function before but it did't work.I want to create something like on signup page by default views.py def auth_join(request, room, slug): if request.method == 'POST': user = request.user.username form_auth = AuthRoomForm(request.POST) if form_auth.is_valid(): room_pass = form_auth.cleaned_data.get('room_pass') password2 = form_auth.cleaned_data.get('password2') if room_pass != password2: messages.error(request, 'Doesn\'t match') return JsonResponse('error') else: user = CustomUser.objects.get(username=user) room = get_object_or_404(Room, slug=slug) if user.has_perm('pass_perm', room): return HttpResponseRedirect(Room.get_absolute_url(room)) else: messages.error(request,'You don\'t have access to this page') return JsonResponse('error') else: form_auth = AuthRoomForm() return render(request,'rooms/auth_join.html', {'form_auth':form_auth}) template <form method='post' class='ui form' id="form"> {% csrf_token %} <div class="ui middle aligned centered grid"> <div class="four wide column"> <h4 class="ui dividing teal header">Enter room password</h4> <div class="field"> <label>Password</label> {{form_auth.room_pass}} </div> <div class="field"> <label>Confirm password</label> {{form_auth.password2}} </div> <button type="submit" class="ui teal button">join</button> {% if messages %} {% for message in messages %} {% if message.tags == 'success' %} <div class="ui green message">{{message}}</div> {% else %} <div class="ui red message">{{message}}</div> {% endif %} {% endfor %} {% endif %} {% if form_auth.errors %} {% for i in form_auth %} <div class="ui red message"> {{i.errors}} … -
Call for model field validation in the serializer
I will try to make a check for the uniqueness of the field at the validation level in the serializer and can not understand why the validator is not called at all. models.py class Vendor(models.Model): active = models.BooleanField(default=False) ... class VendorContacts(models.Model): vendor = models.ForeignKey('Vendors', related_name='contacts', on_delete=models.CASCADE) email = models.CharField(max_length=80, blank=True, null=True) ..... serializer.py class VendorContactCreateSerializer(serializers.ModelSerializer): email = serializers.CharField(validators=[RegexValidator(regex=r'[^@]+@[^\.]+\..+', message='Enter valid email address')]) vendor = serializers.PrimaryKeyRelatedField(queryset=Vendors.objects.all(), required=False, allow_null=True) class Meta: model = VendorContacts fields = (..... ) def create(self, validated_data): ..... #some logic def validate_email(self, value): print('Start validation') exist_contact = VendorContacts.objects.filter(email=value) if exist_contact: vc = get_object_or_404(VendorContacts, email=value) v = vc.vendor if v.active: raise serializers.ValidationError('Email {} already exists'.format(value)) return value In the above serializer, I perform a check at the def validate_email() model field level. print('Start validation') is not called. I tried the same at the object level through def validate(): but it is not called either. -
Sending data to Django channels
I have an external Python script which generates JSON data every second; on the other side i have a Django application. I would like to stream that data on a webpage on my Django app. I already built a consumer with Django channels, but i don't know how to make Django have the data that i generate from the other Python script. Here is my basic consumer: class EchoConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) await self.send({ "type": "websocket.accept" }) async def websocket_receive(self, event): print("received", event) # Echo the same received payload async def websocket_disconnect(self, event): print("disconnected", event) Is there a specific way do this? Or am i supposed to use another service in the middle?Any advice is appreciated -
IS there any one help me for this errors
Hi evrey one I got this errors in image any help please -
How to download a .txt file from a django project
I find difficulty on how to download my .txt file after pressing the button which calls the view respnosible for that. My .txt file is created locally in the path where my manage.py file resides. snippet code of my view: file_name= open("example.txt","w+") file_name.write("\r\n\r\n%s%s%s%s%s" % (var1," ",var2," ",var3)) response = HttpResponse(file_name, content_type="text/plain,charset=utf8") response['Content-Disposition'] = 'attachment; filename={0}'.format(file_name) file_name.close() return response What i have to change to be able to download my .txt file? -
how to load bootstrap in Django?
so I tried loading Bootstrap to Django. But since I wanted to customize the styling with scss, instead of putting the CDN url in header, I replaced it with a separate css file which has all of the Bootstrap stylings. Here's the code. <!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="/style/main.css"> <title>{% block title %}BASE{% endblock %}</title> </head> <body> <div class="container"> {% block content %} {% endblock %} </div> </body> </html> I have the correct /style/main.css file, I've checked it by ctrl+clicking it. As mentioned, the file has ALL of the Bootstrap stylings. @charset "UTF-8"; /*! * Bootstrap v4.4.1 (https://getbootstrap.com/) * Copyright 2011-2019 The Bootstrap Authors * Copyright 2011-2019 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ :root { --blue: #007bff; --indigo: #6610f2; --purple: #6f42c1; --pink: #e83e8c; ### AND SO ON ### However my Django page wouldn't reflect it. When I hit refresh I don't see any styling. But when I restore the CDN url, Bootstrap is normally applied. I have no idea what the problem is. I would very much appreciate your help. :) -
Stripe - Retrieve Customer PaymentIntent history
I am building a platform where I am using Stripe's concept of a parent "platform" account and Connected Stripe accounts that belong to this platform. (e.g. Lyft model) Following Stripe's documentation, when I create a new customer in Stripe, I create it under the main platform account and also store all the payment methods under that customer. When a customer buys something from the Connected account, I follow this doc, where I clone payment method and create a PaymentIntent that is attached to the specific Connected account. And it all works. However, when I try to get a history of customer's transactions (List of PaymentIntents), it returns an empty list because it runs it against the main platform account: stripe.PaymentIntent.list(customer='cus_FJDHFGSJHDF') When I specify a customer AND connected account id, it returns an empty list, because that customer doesn't exist in that Connected account, however, the paymentIntents are present in that Connected account. So, what is the right way to create a PaymentIntent for a customer for a Connected account and then get the history of payments for that customer PER Connected Stripe account? Here is how I clone PaymentMethod and create PaymentIntent: payment_method = stripe.PaymentMethod.create( customer=customer, payment_method=customer.invoice_settings.default_payment_method, stripe_account=stripe_connect_id, ) intent …