Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django inlineformset_factory not saving the froms data
Why the data of inlineformset_factory not saving? here is my code: models.py class HeaderImage(models.Model): header_image = models.ImageField() post = models.ForeignKey(Post, on_delete=models.CASCADE) froms.py BlogImageFormSet = inlineformset_factory(Post, # parent form HeaderImage, # inline-form fields=['header_image'] ,can_delete=False, extra=1) #views.py class BlogUpdateView(PermissionRequiredMixin,UpdateView): raise_exception = True permission_required = "blog.change_post" model = Post template_name = "blog_update_post.html" form_class = BlogPost def get_success_url(self): self.success_url = reverse_lazy('my-account') return self.success_url def get_context_data(self, **kwargs): context = super(BlogUpdateView, self).get_context_data(**kwargs) if self.request.POST: context['form_image'] = BlogImageFormSet(self.request.POST, instance=self.object) else: context['form_image'] = BlogImageFormSet(instance=self.object) return context def form_valid(self, form): context = self.get_context_data() image_form = context['form_image'] if image_form.is_valid(): self.object = form.save() image_form.instance = self.object image_form.save() return HttpResponseRedirect(self.get_success_url()) else: return self.render_to_response(self.get_context_data(form=form)) I am not understanding why data is not saving for inlineformset_factory field. -
Django JSONfield update element in list
I'm using a JSONField to store a list of elements in this format: [{"name": "field1", "value": "100"}, {"name": "field2", "value": "500"}] This is my model: from django.contrib.postgres.fields import JSONField class MyModel(models.Model): json_data = JSONField(default=list, null=True) # Create an empty list always I have a form to update the values stored in json_data, I update the data like this: obj = MyModel.objects.get(pk=1) json = obj.json_data # [{"name": "field1", "value": "100"}, {"name": "field2", "value": "500"}] new_data = {"name": "field2", "value": "99"} # data to update that comes from form fields_not_updated = [field for field in json if new_data['name'] != field['name']] # Create a list of elements that are not updated fields_not_updated.append(new_data) # Add the new data, output: [{"name": "field1", "value": "100"}, {"name": "field2", "value": "99"}] obj.json_data = fields_not_updated # set new json obj.save() # save object I was wondering if there is an easier or more efficient method to update the elements inside the list and save them in the JSONField using django functions or methods or directly using python. -
When I try to run my Django Project on safari I get a safari can't open page
My venv is running, and everything seems to be fine besides that I cant run it on safari. Any help would be greatly appreciated. Thank you -
Can't access ip 0.0.0.0 and ip 127.0.0.1
There's no problem with the code, but it doesn't work. The same applies when i change the port number or turn off the firewall. I'm sorry if there's a problem because this question was written with a translator. I've already tried many ways on the Internet. enter image description here # file name : index.py # pwd : /project_name/app/main/index.py from flask import Blueprint, request, render_template, flash, redirect, url_for from flask import current_app as app main= Blueprint('main', __name__, url_prefix='/') @main.route('/main', methods=['GET']) def index(): return render_template('/main/index.html') # file name : __init__.py # pwd : /project_name/app/__init__.py from flask import Flask app= Flask(__name__) from app.main.index import main as main app.register_blueprint(main) <!--file name : index.html--> <!--pwd : /project_name/app/templates/main/index.html--> <html> <head> This is Main page Head </head> <body> This is Main Page Body </body> </html> # file name : run.py # pwd : /project_name/run.py from app import app app.run(host="0.0.0.0", port=80) Serving Flask app "app" (lazy loading) Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. Debug mode: off Running on http://0.0.0.0:80/ (Press CTRL+C to quit) /error code/ http://0.0.0.0:80/ access > ERR_ADDRESS_INVALID or 127.0.0.1 - - [21/May/2021 06:41:30] "GET /show HTTP/1.1" 404 - -
Django creates two model instances instead of one
I'm trying to learn some django basics and have got strange result when I try to create some model instances using forms. This is my view: from django.shortcuts import render from .forms import ProductModelForm from .models import Product def create(request): form = ProductModelForm(request.POST or None) if form.is_valid(): obj = form.save(commit=False) data = form.cleaned_data Product.objects.create(title_text=data.get("title_text")) obj.save() return render(request, "test_app/create.html", {"form": form}) Form: from django import forms from .models import Product class ProductModelForm(forms.ModelForm): class Meta: model = Product fields = [ "title_text", ] And a template: {% block content %} <form action="." method="post">{% csrf_token %} {{ form }} <button type="submit">Save Model</button> </form> {% endblock %} Thanks in advance. -
submit button is not working in django form using crispy
I have a contact form in django and i use crispy in my template but in both Class base view and Function base view my submit button is not working and i have no errors. here is my fbv code i also tried it with cbv my template is using jquery,bootstrap,moment.js here is my code: models.py class ContactUs(models.Model): fullname = models.CharField(max_length=150, verbose_name="Full Name") email = models.EmailField(max_length=150, verbose_name="Email") message = models.TextField(verbose_name="Message") is_read = models.BooleanField(default=False) class Meta: verbose_name = "contact us" verbose_name_plural = "Messages" forms.py class CreateContactForm(forms.Form): fullname = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "Full Name"}), validators=[ validators.MaxLengthValidator(150, "Your name should be less than 150 character") ], ) email = forms.EmailField(widget=forms.EmailInput(attrs={"placeholder": "Email address"}), validators=[ validators.MaxLengthValidator(150, "Your email should be less than 150 character") ], ) message = forms.CharField(widget=forms.Textarea(attrs={"placeholder": "Your Message"})) views.py def contact_page(request): contact_form = CreateContactForm(request.POST or None) if contact_form.is_valid(): fullname = contact_form.cleaned_data.get('fullname') email = contact_form.cleaned_data.get('email') message = contact_form.cleaned_data.get('message') ContactUs.objects.create(fullname=fullname, email=email, message=message, is_read=False) # todo : show user a success message contact_form = CreateContactForm(request.POST or None) context = {"contact_form": contact_form} return render(request, 'contact_page.html', context) template <form id="contact-form" class="contact-form" data-toggle="validator" novalidate="true" method="post" action=""> {% csrf_token %} <div class="row"> <div class="form-group col-12 col-md-6"> {{ contact_form.fullname|as_crispy_field }} {% for error in contact_form.fullname.errors %} <div class="help-block with-errors">{{ error }}</div> {% … -
Using Django to create Strava Webhook subscription
I am trying to create a Strava webhook subscription to recieve events from users who have authorised my Strava application. I was able to successfully create a subscription using the code in this Strava tutorial. However, I don't understand Javascript, so can't adapt the code to my needs. I am therefore trying to replicate it's functionality within Python using Django. My basic approach has been to follow the setup outlined in the Django section of this webpage, then replace the code in the file views.py with the code below. I have tried to make the code function as similarly as possible to the Javascript function within the tutorial I linked above. However, I'm very new to web applications, so have taken shortcuts / 'gone with what works without understang why' in several places. from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.clickjacking import xframe_options_exempt import json @csrf_exempt @xframe_options_exempt def example(request): if request.method == "GET": verify_token = "STRAVA" str_request = str(request) try: mode = str_request[str_request.find("hub.mode=") + 9 : len(str_request) - 2] token = str_request[str_request.find("hub.verify_token=") + 17 : str_request.find("&hub.challenge")] challenge = str_request[str_request.find("hub.challenge=") + 14 : str_request.find("&hub.mode")] except: return HttpResponse('Could not verify. Mode, token or challenge not valid.') if (mode == 'subscribe' … -
Autocomplete for input with Django, Bootstrap and JQuery
I have a form in Django + Bootstrap/JQuery, and the fields (labels/inputs) are generated from a ModelForm, that is, directly from Django and not in the .html, just like this: <div class = "panel" id = "personal_data"> <div class = "panel-body"> {% bootstrap_form client_form%} </div> </div> This "client_form" is a .py, which contains a ModelForm, which contains the fields automatically generated when the page is loaded My goal is to make an autocomplete on a specific input of this form, for example "Client Name". This autocomplete would show names the same as those typed by the user in real time, and each name would have a link to redirect to another page, it could be, for example, a page to change that customer's data The autocomplete data must come from a function that queries the database! Consider that this function already exists I tried to do this with Typeahead and Bloodhound but I couldn't -
AttributeError: 'NoneType' object has no attribute 'attname'
I am using this django_multitenant library to implement multi tenancy. I tried creating an object in python manage.py shell using the below code >>> from ReportingWebapp.models import * >>> from django_multitenant.utils import * >>> org = Organization.objects.first() >>> set_current_tenant(org) >>> get_current_tenant() <Organization: Organization object (1)> >>> a = ApplicationSetting(username="a",password="b",client_secret="c",client_id="d",tenant_id="e") Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\hp\Desktop\reporting_multitenant\env\lib\site-packages\django_multitenant\mixins.py", line 58, in __init__ super(TenantModelMixin, self).__init__(*args, **kwargs) File "C:\Users\hp\Desktop\reporting_multitenant\env\lib\site-packages\django\db\models\base.py", line 416, in __init__ self._state = ModelState() File "C:\Users\hp\Desktop\reporting_multitenant\env\lib\site-packages\django_multitenant\mixins.py", line 62, in __setattr__ if (attrname in (self.tenant_field, get_tenant_field(self).name) File "C:\Users\hp\Desktop\reporting_multitenant\env\lib\site-packages\django_multitenant\mixins.py", line 115, in tenant_field return self.tenant_id File "C:\Users\hp\Desktop\reporting_multitenant\env\lib\site-packages\django\db\models\query_utils.py", line 149, in __get__ instance.refresh_from_db(fields=[field_name]) File "C:\Users\hp\Desktop\reporting_multitenant\env\lib\site-packages\django\db\models\base.py", line 623, in refresh_from_db db_instance_qs = self.__class__._base_manager.db_manager(using, hints=hints).filter(pk=self.pk) File "C:\Users\hp\Desktop\reporting_multitenant\env\lib\site-packages\django\db\models\base.py", line 573, in _get_pk_val return getattr(self, meta.pk.attname) File "C:\Users\hp\Desktop\reporting_multitenant\env\lib\site-packages\django\db\models\query_utils.py", line 147, in __get__ val = self._check_parent_chain(instance) File "C:\Users\hp\Desktop\reporting_multitenant\env\lib\site-packages\django\db\models\query_utils.py", line 163, in _check_parent_chain return getattr(instance, link_field.attname) AttributeError: 'NoneType' object has no attribute 'attname' Why did i get this error? Tenant is already set in thread local. -
Django - catch migrating process
I am using django-background-tasks, which is unfortunately short of maintainers atm and has an oen issue: click. it results in errors when deploying and can easily be worked around with by just commenting django-background-tasks related functions when migrating. as I do the process fairly often: Can I check for migrating/makemigrations being in process? something like: if migrating() == True: pass else: activate_django_background_tasks_related_stuff() -
Reverse for 'projeto' with no arguments not found. 1 pattern(s) tried: ['delete/(?P<pk>[0-9]+)/projeto/$']
Hail Devs. I have an app that in the index I call some queries with ForeignKey between table fields, using the User as argument. The views work for other tables without ForeignKey. But when I invoke the CRUD (delete, update, create) functions that request the database, it returns an error: Request Method: GET Request URL: http://127.0.0.1:8000/delete/13/ Django Version: 3.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'projeto' with no arguments not found. 1 pattern(s) tried: ['delete/(?P<pk>[0-9]+)/projeto/$'] Exception Location: C:\webcq\venv\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\webcq\venv\Scripts\python.exe Python Version: 3.8.6 Python Path: ['C:\\webcq', 'C:\\webcq\\venv', 'C:\\webcq\\venv\\lib\\site-packages'] Server time: Thu, 20 May 2021 21:03:07 +0000 url.py project from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('', include('imagem.urls', namespace='home')), path('view/<int:pk>/', include('imagem.urls', namespace='view')), path('edit/<int:pk>/', include('imagem.urls', namespace='edit')), path('update/<int:pk>/', include('imagem.urls', namespace='update')), path('delete/<int:pk>/', include('imagem.urls', namespace='delete')), ] urls.py app from django.urls import path from . import views app_name = 'imagem' urlpatterns = [ path('', views.home, name='home'), path('projeto/', views.projeto, name='projeto'), path('form/', views.form, name='form'), path('create/', views.create, name='create'), path('view/<int:pk>/', views.view, name='view'), path('edit/<int:pk>/', views.edit, name='edit'), path('update/<int:pk>/', views.update, name='update'), path('delete/<int:pk>/', views.delete, name='delete'), ] views.py app The views work, but do not redirect to the view name and return the above error. def edit(request, pk): data = {} data['db'] … -
How can I add a relationship in Django to a model that's created before the model I need to reference?
I have two different models: Movies and Characters. I want Characters to have a movies field where I can see the movies in which the characters appear and I want Movies to have the characters that appear in them. However, since one of the models has to be defined first, I am not sure how to make the first one relate to the second one. This is my code so far but this doesn't show 'movies' when I access the Character model: class Character(models.Model): image = models.ImageField() name = models.CharField(max_length=100) age = models.IntegerField() story = models.CharField(max_length=500) def __str__(self): return self.name class Movie(models.Model): image = models.ImageField() title = models.CharField(max_length=100) creation_date = models.DateField(auto_now=True) rating = models.IntegerField() characters = models.ManyToManyField(Character) def __str__(self): return self.title I am not sure how to add the movies to the Character model since it's referenced before the Movie model, how can I accomplish this? Thank you. -
how to implement PUT method in Django views
I am new to Django. I have assigned a task to create a PUT API. I don't know how to proceed. Already POST method is there: if request.method == 'POST': """ add a new rule """ data = JSONParser().parse(request) validated_data=data ruleParam=validated_data.pop('ruleParam') ruleTypeDetail=validated_data.pop('ruleTypeDetail') rule= Rule.objects.create(**validated_data) for rp in ruleParam: RuleParameter.objects.create(rule=rule,**rp) print(validated_data) if validated_data['ruleType']=='Simple': qcData = ruleTypeDetail.pop('qualifyingCaluse') fl=FieldList.objects.get(id=ruleTypeDetail['allFieldList']['id']) ag=AggregateFunction.objects.get(id=ruleTypeDetail['allAggregateFunction']['id']) fldList= ruleTypeDetail.pop('allFieldList') aggFunction = ruleTypeDetail.pop('allAggregateFunction') simpleRule=RuleSimple.objects.create( rule=rule, fieldList = fl, aggregateFunction = ag, **ruleTypeDetail ) for qc in qcData: fl=FieldList.objects.get(id=qc['fieldListDetail']['id']) cl=ConditionList.objects.get(id=qc['conditionListDetail']['id']) QualifyingClause.objects.create( ruleSimple=simpleRule, detailSrl=qc['detailSrl'], fieldList=fl, conditionList=cl, value=qc['value'] ) Please help me or show mee similar to this. -
Django project not rendering React.js
In my project, I am trying to tie together Django and React. index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> {% load static %} <link rel="icon" href="{% static 'logofavicon.ico' %}" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta property="og:image" content="{% static 'Banner.png' %}"> <meta name="description" content="The future of digital content" /> <link rel="apple-touch-icon" href="{% static 'logo192.png' %}" /> <link rel="manifest" href="{% static 'manifest.json' %}" /> <title>Drop Party</title> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> </body> </html> index.js import React from "react"; import ReactDOM from "react-dom"; import "./index.css"; import App from "./App"; import reportWebVitals from "./reportWebVitals"; import "./styleguide.css"; import "./globals.css"; ReactDOM.render( < React.StrictMode > < App / > < /React.StrictMode>, document.getElementById("root") ); reportWebVitals(); settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/frontend/' STATICFILES_DIRS = ( FRONTEND_DIR / 'build', FRONTEND_DIR / 'src', FRONTEND_DIR / 'public' ) Project Hierarchy I have looked at this post, and confirmed that this solution is not applicable for me. The primary issue, I think, is that Django is serving the html, but not running the .js, so I'm unsure of where to go with this. I have also confirmed that the image linking is … -
Two packages with the same import name conflicting
I am interacting with the InfusionSoft API in a Django project that I am working on. I would like to use both infusionsoft-client package and infusionsoft-python. However, they both require import infusionsoft so now I am getting error messages regarding infusionsoft-client attributes that are already working. How can I set these up so that they do not conflict? -
how to make sure if an instance of a model does not exist then create one else return instance all ready exists
i am stuck at a point where i have to make sure if a payment does not exists corresponding to an order then create one else return payment all ready done. Bellow is the code what i have tried: if(transaction_status=='SUCCESS'): try: payment= Payments.objects.get(orders=order,direction=direction) except (Payments.DoesNotExist): payment = Payments( orders=order, amount=amount, is_active='True' ) payment.full_clean() payment.save() return Response({"payment":"All ready exists"}) if there is a better way please do suggest. -
Django Class based views and their cohesion
I'm coming from laravel and trying to do something like laravael model controller where functions are mapped to request methods and no of arguments. I tried to find something similar in Django but the class based views are too scattered. The conventional approach with CBVs(ListView,TemplateView,GenericEditView) won't let me implement all the function in one class. That would make a number of classes and a number of URLs to handle also, so with my low knowledge, I have done the thing below. Please check and guide. class InvoiceView(View): @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): if (args or kwargs) and request.method == 'GET': if kwargs['data'] =='create': return self.create(request,*args,**kwargs) else: return self.show(request, *args, **kwargs) else: return super().dispatch(request, *args, **kwargs) def get(self,request): all_invoice = Invoice.objects.all() content = {'invoices': all_invoice} return render(request, 'Invoicing/invoice/index.html', context=content) @transaction.atomic def post(self, request): data = json.loads(request.POST.get('data')) inv = Invoice(payment_mode=data['invoice_details']['payment_mode'], total_amount=float( data['invoice_details']['total_amount']), created_by=User.objects.get(pk=1)) inv.customer = Customer.objects.get( pk=data['invoice_details']['customer_id']) inv.full_clean(exclude='id') inv.save() inv_data = data.pop('invoice_details') for key in data: if key in ('sublimation', 'printing'): self.addOrder(inv, data[key], key) elif key in ('designing', 'transfer', 'ink', 'paper', 'part'): self.addItems(inv, data[key][0], key) message = 'Stored successfuly' if inv_data['payment_mode'] == '0': inv.payment_status = 0 inv.save() pmnt = Payment(invoice=inv, amount=inv.total_amount, payment_method=2) pmnt.save() return HttpResponse(json.dumps({ 'message': message, 'link': reverse('invoice'), 'template': render_to_string('Invoicing/invoice/printPreview.html',context=self.extract_invoice_data(inv.id)) … -
Django loading image from url - ImageField objected has no attribute _committed
I am using Django 3.2 I am trying to programatically create a model Foo that contains an ImageField object, when passed an image URL. This is my code: image_content = ContentFile(requests.get(photo_url).content) # NOQA image = ImageField() # empty image data_dict = { 'image': image, 'date_taken': payload['date_taken'], 'title': payload['title'], 'caption': payload['caption'], 'date_added': payload['date_added'], 'is_public': False } foo = Foo.objects.create(**data_dict) # <- Barfs here foo.image.save(str(uuid4()), image_content) foo.save() # <- not sure if this save is necessary ... When the code snippet above is run, I get the following error: ImageField object does attribute _committed I know this question has been asked several times already - however, none of the accepted answers (from which my code is based) - actually works. I'm not sure if this is because the answers are old. My question therefore is this - how do I fix this error, so that I can load an image from a URL and dynamically create an object that has an ImageField - using the fetched image? -
Add columns in django model table postgres
I recently edited my table and had overriden the primary_key to a title attribute. I tried deleting all previous migrations and even so, the model id, which should be the pk by default, isn't so. Since then I've been trying to add a new column id to my appname_model table. Here the appname is courses and model-class is course (written in lowercase in reference to the tablename statement I just made) I've entered the following commands multiple times and none have managed to add the field id: ALTER TABLE courses_course ADD COLUMN id int constraint; I've tried several other variants of the same syntax from other stackoverflow questions but none have worked out so far. I also want to set id to the primary key in that table. -
Django raw sql %d for ID not working for integer parameters
I have this raw sql for my Django model: cursor.execute('SELECT crowdfunding_offering.offering_name FROM crowdfunding_offering WHERE crowdfunding_offering.id = %d ORDER BY crowdfunding_offering.id DESC LIMIT 1', (int(self.offering.id),)) Which does not work. I am receiving this error: Exception Value: near "%": syntax error Then I try to change %d to %s, only then it works. I thought %d are for number parameters and %s are for strings, but why is it not working for %d? Here is the table with the id clearly being an integer: -
Cannot assign "'1'": "Offers.state must be a "States" instance
I have read several answers to this same question, but none have worked for me. Here's my model: class States(models.Model): name = models.CharField(max_length=20) abrev = models.CharField(max_length=3) def __str__(self): return self.abrev class Offers(models.Model): *other fields* state = models.ForeignKey(States on_delete=models.PROTECT) so in views i am doing this: if request.method == 'POST': try: **other fields** state = States.objects.get(pk=request.POST['state']) Offers.objects.create(**other fields**, state=state) except Exception as e: print ("error in form") But am always getting the same Error Cannot assign "'1'": "Offers.state must be a "States" instance. And as you can see, i am passing an instance, not the id of the element. I use the id that comes from the form just to query the DB and find the instance with this: state = States.objects.get(pk=request.POST['state']) The form works just fine, and I tried to do it with forms.py and if form.is_valid(), but got the exact same result. am on: django 3.2.3 python 3.9.2 -
Django automatically appending csrftoken to cookies send by React Native request
I've got a React Native app that is making requests using axios to my django server. const axios = require("axios").create({ baseURL: BASE_URL, headers: { 'cookie': `credentials=abc123;`, 'X-Requested-With': 'my_custom_app', } }); On my Django app, I am printing out the cookies for the request. print(request.COOKIES) When I'm printing the cookies on my local instance of the backend, things look fine: Here's the output from my local instance: {'credentials': 'abc123'} But on my prod instance of the server, the output is different: {'csrftoken': 'B17DuZmxWPyuTAEdcldsJqZX0dsDct4k6nHLXYtRPiJQFEpBrSPIH5G7M6rty0FH,credentials=abc123'} This obviously gets read incorrectly by the server and it thinks that my credentials are not available in the cookie. I'm not sure what is going on here, or why this only happens on my production instance. -
Optimal way for letting user download big files in the server using Django
I am making a Django application for an experiment and it will offer the possibility to the user to be able to download really big image files to a specific directory in the server. I have a PoC of that working, where the user sees a button clicks on it and the process to download begins. I have put the download process inside views.py which means it occurs upon visiting a specified URL. The code responsible for the download part similar to the following: with open(loc, "wb") as f: response = s.get(pos, stream=True) total_length = response.headers.get('content-length') if total_length is None: f.write(response.content) else: dl = 0 total_length = int(total_length) for data in response.iter_content(chunk_size=4096): dl += len(data) f.write(data) The problem is that for some images which are > 500MB the process takes quite some time and there are several issues, like if the user closes the app, or clicks away then the process stops. How can I make it in such a way so the user visits that page and clicks that button and the download process begins on the background without binding the user to stay to that page. Also maybe creating another endpoint which could update the user about the … -
Django jquery sortable save in database
I'm new in django and javascript and I have an issue that I can't find a solution . I'm trying to save in my database the position of a sortable with jquery . The model is call : Reflexion Model class Reflexion(models.Model): name = models.CharField(max_length=100) content = RichTextUploadingField(null=True ,blank=True) position = models.IntegerField(default=1) project = models.ForeignKey('project.Project', on_delete=models.CASCADE, null=True) class Meta: ordering = ['position'] def __str__(self): return self.name **The url ** path('<slug:pslug>/reflexion/', views.reflexion_list, name='reflexion_list'), path('reflexion/<int:pk>/', views.sort, name='sort'), Page : Reflexion_list - HTML , the draggable item <div class="block draggable-item" data-pk="{{ reflexion.id }}"> </div> Same page , jquery <script type="text/javascript" charset="utf-8" > $(document).ready(function() { $(".draggable-column").sortable({ update: function(event, ui) { window.CSRF_TOKEN = "{{ csrf_token }}"; var serial = $('.draggable-column').sortable('serialize'); $.ajax({ url: "reflexion/"+ $(this).data('pk'), type: "post", data: {csrfmiddlewaretoken: window.CSRF_TOKEN , serial } }); }, }).disableSelection(); }); </script> The view for sorting @csrf_exempt def sort(request, pk): for index, pk in enumerate(request.POST.getlist('reflexion[]')): reflexion= get_object_or_404(Reflexion, pk=pk) reflexion.order = index reflexion.save() return HttpResponse('') What did a do wrong ? I think is the link with my url in the script but I don't know what to do , please help me -
forex_python.converter CurrencyRates Failed to establish a new connection: [Errno 11001] getaddrinfo failed
I use forex python CurrencyRates in many of my project, but now it doesn't work, none of them. Is there any problem with my code or are the server down? or what happend? Here is my Code: from forex_python.converter import CurrencyRates c = CurrencyRates() usd = c.get_rate('EUR', 'USD') And the error: Traceback (most recent call last): File "D:\MeineDaten\Programmieren\Python\Projekte\Flask\ProjectX\main.py", line 2, in <module> from files.currency import currency File "D:\MeineDaten\Programmieren\Python\Projekte\Flask\ProjectX\files\currency.py", line 7, in <module> usd = c.get_rate('EUR', 'USD') File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\forex_python\converter.py", line 66, in get_rate response = requests.get(source_url, params=payload) File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\api.py", line 76, in get return request('get', url, params=params, **kwargs) File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\api.py", line 61, in request return session.request(method=method, url=url, **kwargs) File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\sessions.py", line 542, in request resp = self.send(prep, **send_kwargs) File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\sessions.py", line 655, in send r = adapter.send(request, **kwargs) File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\adapters.py", line 516, in send raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.ratesapi.io', port=443): Max retries exceeded with url: /api/latest?base=EUR&symbols=USD&rtype=fpy (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x000001F0C1D056A0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))