Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
URLConnection hits server twice when downloading file?
After reading HttpURLConnection request being hit twice to the server for downloading file it was very similar and helped, but I still see my server gets two requests for a single download. This is my AsyncTask that I use to download a file from a Django web server. @Override protected String doInBackground(String... sUrl) { String path = "/sdcard/YourApp.apk"; try { URL url = new URL(sUrl[0]); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.addRequestProperty("Authorization", "Token " + authToken); urlConnection.connect(); int fileLength = urlConnection.getContentLength(); // download the file InputStream input = new BufferedInputStream(urlConnection.getInputStream());//url.openStream()); OutputStream output = new FileOutputStream(path); byte data[] = new byte[1024]; long total = 0; int count; while ((count = input.read(data)) != -1) { total += count; //publishProgress((int) (total * 100 / fileLength)); output.write(data, 0, count); } output.flush(); output.close(); input.close(); urlConnection.disconnect(); } catch (Exception e) { Log.e("SVC0", e.getMessage()); } return path; } Then I look at the Django logs and I can see that two requests are present: [09/Oct/2019 02:30:29] "GET /update HTTP/1.1" 301 0 [09/Oct/2019 02:30:35] "GET /update/ HTTP/1.1" 200 19451876 I have tried commenting out many parts but I just can't figure out why it's causing the 301 error. Any help tracking this 'bug' down would be very appreciated. -
How to send dictionary data with redirect function in Django
I'm trying to send a dictionary by the redirect method. But not getting it in the redirected template. I tried to pass the dictionary like it used to pass in the render function but I don't think I am doing this in the right way. I also tried HttpResponseRedirect but that doesn't work too. views.py def index(request): if request.method == "POST": url = request.POST.get('url', '') r = requests.get(url) soup = BeautifulSoup(r.content, features="lxml") p_name = soup.find_all("h2",attrs={"class": "a-size-mini"}) p_price = soup.find_all("span",attrs={"class": "a-price-whole"}) p_image = soup.findAll('img', {'class':'s-image','src':re.compile('.jpg')}) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="product_file.csv"' for name,price,image in zip(p_name,p_price,p_image): writer = csv.writer(response) row = writer.writerow([image['src'],name.text, price.text,]) name_data = [data.text for data in p_name] price_data = [data.text for data in p_price] image_data = [data['src'] for data in p_image] dec = {'name':name_data, 'price':price_data, 'image':image_data, 'url':url} return redirect('data', dec) return render(request, 'index.html') -
Noob Django question: When do I make an app vs coding something for the whole website?
I want to implement things like user logins for the entire website and not within a specific app. Can someone point me in the right direction/some reference I can look up? I've looked at tutorials for the login, and they all refer to building logins within an app, not the main website. Should I build a "Welcome" or "Registration" app, and then import it into every other app? -
API response time is too slow using DRF
Activity is tourist information and tag (Preference) is tag information (such as Instagram hash tag). Function of Activity ListPreference api: For every activity, check that each activity contains tags from the request list. Only the activities that contain the tags are serialized. But it's too slow. It takes about 1 minute. The api, which returns all activities, only takes 2 seconds. What's the problem? class ActivityListByPreference(APIView): permission_classes = (permissions.AllowAny,) def get(self, request): request_tag = [6, 7, 8] activity_list = [] activity_items = Activity.objects.filter() activity_nums=activity_items.values_list('num', flat=True) b=1 for activity_num in activity_nums: print(activity_num) activity_preference_items = Activity_Preference.objects.filter(activity_num_id=activity_num) activity_tag = [] preference_nums= activity_preference_items.values_list('preference_num_id',flat=True) activity_tag=list(preference_nums) intersection = set([]) intersection = set(request_tag).intersection(set(activity_tag)) inter_list = list(intersection) inter_list.sort() if (request_tag == inter_list): print('ν¬ν¨ν©λλ€.') activity_list.append(activity_num) activity_preference_items = Activity_Preference.objects.all() for activity_preference_item in activity_preference_items: activity_tag.append(activity_preference_item.preference_num_id) print('λ') data = Activity.objects.filter(pk__in=activity_list) serializer = ActivitySerializer(data, many=True) print(data) return Response({"ActivityListByPreference" : serializer.data}) -
I keep receiving "No Reverse Matchup" when implementing my urls
I am getting Django error NoReverseMatch when trying my urls, along with "Reverse for 'shop' with keyword arguments '{'product_category': 'badges'}' not found. 1 pattern(s) tried: ['shop/$']" I have tried changing my url patterns and my get_absolute_url method from slug to things as "product_category", and changed the way I call in the template from obj.get_absolute_url to url 'products' slug, but neither works. Here is the get_absolute_url: def get_absolute_url(self): return reverse("shop", kwargs={"product_category":self.slug}) The urls: urlpatterns = [ path('', CategoryView.as_view(), name='shop'), path('<slug:product_category>/', ProductListView.as_view(), name='products'), path('<slug:product_category>/<slug:product>/', ProductDetailView.as_view(), name='detail'), ] The template: <a href="{{ obj.get_absolute_url }}">{{ obj.title }}</a> -
Display queryset count sitewide?
Very easy question yet I can't get it to display. I have the total number of users in the footer of the webpage. The problem is that it only shows on the home page, once I go to any other page on the site it goes away. I don't want to call it in every view. How do I get the user count to stay static in the footer site wide? Main URLs rl(r'^$', views.index, name="home"), Main views.py def index(request): users = Profile.objects.all().count() return render(request, 'layout.html', {'users': users}) layout.html <P>Total Users: ({{users}})</P> -
My images are not showing in the home ppage
Sir can you help me with this questions am very thankful for you -
AttributeError: __enter__ During connection to mysql database
I am getting AttributeError: __enter__ while executing the following code to get connection and cursor. from contextlib import closing def _connect(): return closing(mysql.connect( host=settings.DATABASES['data_base_name'].get('HOST', 'localhost'), user=settings.DATABASES['data_base_name']['USER'], passwd=settings.DATABASES['data_base_name'].get('PASSWORD', ''), db=settings.DATABASES['data_base_name']['NAME'], cursorclass=cursors.DictCursor)) with _connect() as conn, conn as cursor: I have got following error during execution. with _connect() as conn, conn as cursor: AttributeError: __enter__ -
How to execute custom SQL query when deleting a model item in Django?
I want to execute an SQL query, when an item gets deleted in the admin interface. In models.py I do this: from django.db import connection class LList(models.Model): item = models.ForeignKey(Item, models.DO_NOTHING) def delete(self, *args, **kwargs): cursor = connection.cursor() cursor.execute('DELETE FROM some_table where item = %d', [self.item.id]) When I turn debugging on I see all the queries executed. It seems the DELETE FROM query is not executed, I only see (0.000) DELETE FROM `llist` WHERE `llist`.`id` IN (27); args=(27,) Why is the other DELETE FROM query not executed? How can I fix that? -
Reverse for 'book-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['catalog/book/(?P<pk>[0-9]+)$']
My website is working well on my local environment, as well as it has been working well on heroku env until my recent deployment. Code is same on both environments and I referred to all 11 posts related to similar issue,example Reverse for 'todo-user' with arguments '('',)' not found. 1 pattern(s) tried My issue looks different than what I have seen in other posts here, I think it is related to environment settings/variables, which I am not able to identify it yet. But the solutions provided on stack overflow, makes me think like the real problem of this issue is something else. When I try to click on http://127.0.0.1:8000/catalog/mybooks/ link, local website works fine, however, production (heroku), same code throws following exception NoReverseMatch at /catalog/mybooks/ Reverse for 'book-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['catalog/book/(?P[0-9]+)$'] Request Method: GET Request URL: https://.herokuapp.com/catalog/mybooks/ Django Version: 2.2.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'book-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['catalog/book/(?P[0-9]+)$'] Exception Location: /app/.heroku/python/lib/python3.7/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 673 Python Executable: /app/.heroku/python/bin/python Python Version: 3.7.3 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python37.zip', '/app/.heroku/python/lib/python3.7', '/app/.heroku/python/lib/python3.7/lib-dynload', '/app/.heroku/python/lib/python3.7/site-packages'] Server time: Wed, 9 Oct 2019 04:52:47 +0000 Error during template rendering In template /app/catalog/templates/base_generic.html, error β¦ -
Django writing Middleware to extend self.request
I am very new to writing custom middleware in Django. We know in Django, there is built-in self.request. in self.request, there are too many instances like self.request.user, self.request.data, self.request.authenticator etc I am trying to add self.request.mycustom; in self.request.mycustom, I want to get my models MyCustom instance. This is My Models: from django.contrib.auth.models import User class MyCustom(models.Model): auth_user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='auth_user', ) I am trying to write the middleware but not getting how to write this. this is my attempt to write: class MessMiddleWare(obect): def precess_view(request): mycustom = MyCustom.objects.filter(id=request.user.pk) request.mycustom = mycustom Can anyone help me to achieve this? I just I want to get self.request.mycustom -
Jquery apply callback on OnChange event which call api
Hi i'm trying to apply a callback to use on my dynamic select boxes instead of TimeOut Currently i have 4 select options boxes(3 are dynamic options): City, District(options based on city options), Ward(options based on district options) and Street(options based on district options) It's a search form so the next page form should has the previous form values, i use Django to determined if a previous form values are select , then if so it will add a hidden div with id="value-filter" in the template. And now i use the Jquery to check if that div exists to change the select options If a user click on the city option then it will activate the city onchange event to call an api that populate District options with the corresponding city Id, Ward and Street options are the same but based on District options to call their api in order to populate their options. $(document).ready(function() { //call district api if city option is selected $('select#city').change(function(event) { $.getJSON("/api_get_districts/", { id: $(this).val() }, function(j) { var options = '<option selected disabled>-- District --</option>'; for (var i = 0; i < j.length; i++) { options += '<option value="' + j[i].id + '">' + β¦ -
Return response to download file in Django
I'm new in Django and I'm making an app that can scrap product data from Amazon. I'm able to get the data, now I want to download it as CSV file but my logic is not working. I made two forms in index.html one is to get the data & the other is to download the file. The first form is working properly but doesn't understand what is wrong with download logic or form. views.py def index(request): if request.method == "POST": url = request.POST.get('url', '') down = request.POST.get('download','') r = requests.get(url) soup = BeautifulSoup(r.content, features="lxml") p_name = soup.find_all("h2",attrs={"class": "a-size-mini a-spacing-none a-color-base s-line-clamp-2"}) p_price = soup.find_all("span",attrs={"class": "a-price-whole"}) p_image = soup.findAll('img', {'class':'s-image','src':re.compile('.jpg')}) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="product_file.csv"' for name,price,image in zip(p_name,p_price,p_image): writer = csv.writer(response) row = writer.writerow([image['src'],name.text, price.text,]) name_data = [data.text for data in p_name] price_data = [data.text for data in p_price] image_data = [data['src'] for data in p_image] dec = {'name':name_data, 'price':price_data, 'image':image_data, 'url':url} if down: return response else: dec = {} return render(request, 'index.html',dec) index.html <div class="col-md-6"> {% if name %} <form action="" method="POST">{% csrf_token %} <input type="text" id="url" name="url" class="form-control" value="{{url}}" placeholder="URL" required autofocus> <p class="mt-1 text-light"> Download Your Scraped File</p> <button type="submit" class=" btn btn-info btn-lg" β¦ -
Django model instance not saving and no errors thrown
The Customer data and the Contact data in the below method is not getting saved and there is no error thrown. Also when I printed the Customer objects after assigning it in the def then it shows the correct data but the same is not reflected in the DB. I have also overridden the save def in the model class and included exception handling but no exception is thrown either. Not sure what else needs to be added. Please advise. views.py @login_required def modify(request, customer_customerid): #print_request(request) customer = get_object_or_404(Customer, pk=customer_customerid) contact = Contact.objects.get(reftable='Customer', refid=customer_customerid) if request.method =='POST': print(request.POST['txtCustomerName'],'Hi') if request.POST['txtCustomerName'] and request.POST['txtCustShortName'] and request.POST['dtMSAStartDate'] and request.POST['dtMSAEndDate'] and request.POST['selCustState'] and request.POST['selCustCountry'] and request.POST['selCustTimeZone']: customer.CustomerName = request.POST['txtCustomerName'] customer.CustomerShortName = request.POST['txtCustShortName'] customer.MSAStartDate = request.POST['dtMSAStartDate'] customer.MSAEndDate = request.POST['dtMSAEndDate'] if request.POST['chkExternalCustomer'] == u'true': customer.ExternalCustomer = True else: customer.ExternalCustomer = False customer.State = request.POST['selCustState'] customer.Country = request.POST['selCustCountry'] customer.TimeZone = request.POST['selCustTimeZone'] if request.POST['chkIsActive'] == u'true': customer.Active = True else: customer.Active = False customer.AllDataSourceRequired = True customer.LastModifiedUTC = timezone.datetime.now() customer.LastModifiedBy = request.user try: print(str(customer.CustomerShortName),'Hello') customer.save(update_fields=["customershortname"]) transaction.commit() print(Customer.objects.values()) except Exception as e: print(e.message()) contact.FirstName = request.POST['txtContactFirstName'] contact.LastName = request.POST['txtContactLastName'] contact.ContactEmail = request.POST['txtCustomerEmail'] contact.save() return redirect('/customers/' + str(customer_customerid)) else: return render(request,'customers/detail.html' ,{'error':'All fields are required.'}) else: detail(request, customer_customerid) models.py from β¦ -
Django ading custom instance in self.request
I am not getting how to extend self.reqeust In Django rest framework or Django view, we can access to many things with self.reqeust like if we want to get authenticated user, then we write self.request.user also, you know there are too many instances of self.request like self.request.user, self.request.data, self.request.authenticator I am trying to extend this and want to get self.request.mycustominstance Can anyone help me where can I extend like this? -
Serving pytorch model with django and uwsgi, how can the system support multi requests concurrency?
If I street-test the API with 10 concurrency requests: using django built-in server, python3 manage.py runserver, the average response time is about 10 times longer than 1 concurrency request using uwsgi to start 10 progress, the average response time is about 5 times longer than 1 concurrency request How can I handle multi requests in instant response time? -
Rename Django User fields
I'm using the default Django User class and authentication for a simple user LogIn. This User model has two important fields: "username" and "password". I want them to be "user" instead of "username", and "pass" instead of "password". I know I can make a RenameField, but that will only change the column name in the database, it won't change how Django asks for the username and password in the body of the POST request. I need to change the keys in the JSON given in the request. from: { "username": "user123", "password": "pass123" } to: { "user": "user123", "pass": "pass123" } And I think I can create a file called serializer and do something there but I'm not sure how, and I didn't found anything in the documentation. If they're useful, these are my files. urls.py: from rest_framework.authtoken.views import obtain_auth_token from django.contrib import admin from catanAPI.catan import views from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('users/login/', obtain_auth_token) ] settings.py INSTALLED_APPS = [ #... 'django.contrib.auth', 'rest_framework', 'rest_framework.authtoken' #... ] AUTH_USER_MODEL = 'auth.User' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ] } I know this question may be stupid or something, but I'm new in Django, and I'm trying to learn. -
How to retrieve validation error in Django CreateView?
I have a model, form, and view that used to work and now that I changed the form to add receiver it is not submitting the form but rather just reloading the form in-place (validation error). How do I find what exactly is causing this error? How do I troubleshoot this for future reference? Models.py class Memo(models.Model): EMPLOYEE_CHOICES = ( ('dealer', 'DEALER'), ('server', 'SERVER'), ('cage staff', 'CAGE STAFF'), ('security', 'SECURITY'), ('casino supervisor', 'CASINO SUPERVISOR'), ('food bev supervisor', 'FOOD BEV SUPERVISOR'), ('cage supervisor', 'CAGE SUPERVISOR'), ('security supervisor', 'SECURITY SUPERVISOR'), ) title = models.CharField(max_length=100) content = models.TextField() date_time = models.DateTimeField(default=timezone.now) sender = models.ForeignKey(User, on_delete=models.CASCADE) receiver = models.CharField(max_length=30, choices=EMPLOYEE_CHOICES, default='dealer') def __str__(self): return self.title def get_absolute_url(self): return reverse('memos-detail', kwargs={'pk': self.pk}) Forms.py class MemoForm(forms.ModelForm): EMPLOYEE_CHOICES = ( ('dealer', 'DEALER'), ('server', 'SERVER'), ('cage staff', 'CAGE STAFF'), ('security', 'SECURITY'), ('casino supervisor', 'CASINO SUPERVISOR'), ('food bev supervisor', 'FOOD BEV SUPERVISOR'), ('cage supervisor', 'CAGE SUPERVISOR'), ('security supervisor', 'SECURITY SUPERVISOR'), ) title = forms.CharField() content = forms.CharField(widget=forms.Textarea) receiver = forms.ChoiceField(choices=EMPLOYEE_CHOICES, widget=forms.CheckboxSelectMultiple) class Meta: model = Memo fields = ('title', 'content', 'receiver', ) Views.py class MemoCreateView(LoginRequiredMixin, CreateView): model = Memo form_class = MemoForm def form_valid(self, form): form.instance.sender = self.request.user form.save() return super(MemoCreateView, self).form_valid(form) -
Django + django-rest-framework-simplejwt protect view
I just installed django-rest-framework-simplejwt in a Django project and if I send an invalid Authentication Bearer <<token>> header, it blocks my request with 401 code. Which is the expected behavior. The problem is that if I remove the Authentication header, I can access my view, so it's unprotected. How can I protect the view to return 401 if there is no Authentication header? Here's the view code: class AuthTestView(views.APIView): http_method_names = ['get'] def get(self, request): response_data = { 'result': 'Restricted access test ok.', } return Response(data=response_data, status=status.HTTP_200_OK) -
permission_classes preventing Android app from accessing DRF?
I am having trouble developing a Android app that I want to authenticate with Django REST framework to securely access information. I am being successfully issued a REST token but IsAuthenticated remains false for all of my views. In Django I have a class based view that responds if both authentication.TokenAuthentication permissions.IsAuthenticated are valid: class TestAuthView(APIView): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) def get(self, request, format=None): return GetRestData() In Android I acquire a token by POSTing my uname and passwd to the default /rest-auth/login/url which responds with token similar to string: {"key":"c03c1238ab99d91301d34567bda9d417d2b48c0c"} public static String getResponseFromHttpUrl(String... params) throws IOException { ArrayList<AbstractMap.SimpleEntry<String,String>> paramssss = new ArrayList<>(); paramssss.add(new AbstractMap.SimpleEntry<>("username", "root")); paramssss.add(new AbstractMap.SimpleEntry<>("password", "mypass")); URL url = new URL(params[0]); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setReadTimeout(3000); urlConnection.setConnectTimeout(3000); urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); OutputStream os = urlConnection.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(getQuery(paramssss)); writer.flush(); writer.close(); os.close(); urlConnection.connect(); try { InputStream in = urlConnection.getInputStream(); Scanner scanner = new Scanner(in); scanner.useDelimiter("\\A"); boolean hasInput = scanner.hasNext(); if (hasInput) { return scanner.next(); //eg. {"key":"c03c1238ab99d91301d34567bda9d417d2b48c0c"} } else { return null; } } finally { urlConnection.disconnect(); } } I then store the token and later use it to request some data: @Override protected String doInBackground(String... sUrl) { String path = β¦ -
Django some static files not found
I am unable to understand why do I get "not found" errors on files with same setup as working ones, when running locally with runserver: [09/Oct/2019 02:06:03] "GET /static/css/congrat.css HTTP/1.1" 200 69 [09/Oct/2019 02:06:11] "GET /static/images/congrat.css HTTP/1.1" 404 1667 this is dirs hierarchy : βββ static β βββ css β β βββ congrat.css β β βββ flex-slider.css β β βββ flipclock.css β β βββ font-awesome.css β β βββ main.css β βββ fonts β β βββ Flaticon.woff β β βββ flexslider-icon.eot β β βββ flexslider-icon.svg β β βββ flexslider-icon.ttf β β βββ flexslider-icon.woff β β βββ FontAwesome.otf β β βββ fontawesome-webfont.eot β β βββ fontawesome-webfont.svg β β βββ fontawesome-webfont.ttf β β βββ fontawesome-webfont.woff β β βββ fontawesome-webfont.woff2 β β βββ slick.eot β β βββ slick.svg β β βββ slick.ttf β β βββ slick.woff β βββ images β β βββ banner-bg.png β β βββ blog-item-01.png β β βββ blog-item-02.png β β βββ blog-item-03.png β β βββ circle-dec.png β β βββ congrat.css β β βββ favicon.ico β β βββ featured-item-01.png β β βββ frame.png β β βββ fun-facts-bg.png β β βββ left-image.png β β βββ logo.png β β βββ right-image.png β β βββ testimonial-icon.png β β βββ work-process-bg.png β β βββ work-process-item-01.png β β¦ -
Force URL to match a view with re_path
I've a view that should be called when entering: 1) stickersgallit.pe/ordenes/ingresos or 2) http://127.0.0.1:8000/ordenes/ingresos (locally). However, it is entering and activating other view AddProduct, as it is guessing ordenes is c_slug and ingresos is product_slug, when they aren't: path('<slug:c_slug>/<slug:product_slug>', views.AddProduct, name='AddProduct'), Questions: a) How to force /ordenes/ingresos to activate my classOrdersListView (in order/views/class OrdersListView(ListView))? b) Or How can I limit what the URL views.AddProduct considers as c_slug and product_slug? Proyect urls.py: from django.contrib import admin from django.urls import path, include, re_path from shop import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), re_path('^/ordenes/', include('order.urls')), path('', include('shop.urls')), path('carrito_de_compras/', include('cart.urls')), path('marketing/', include('marketing.urls')), path('registrarse/', views.signupView, name = 'signup'), path('ingresar/', views.signinView, name = 'signin'), path('salir/', views.signoutView, name = 'signout'), path('province/', views.get_province, name = 'province') ] shop URLs: from django.contrib import admin from django.urls import path, re_path from . import views app_name = 'shop' urlpatterns = [ path('admin', admin.site.urls), path('', views.allCat, name='allCat'), path('packs/', views.PacksPage, name='PacksPage'), #Todos los packs path('catalogo', views.CatalogoListView.as_view(), name='catalogo'), #Todos los productos unitarios path('muestras/', views.SamplePackPage, name='SamplePackPage'), #Todas las muestras path('province/', views.get_province, name='province'), path('district/', views.get_district, name='district'), path('quienes-somos/', views.quienes_somos, name='quienes_somos'), path('como-comprar/', views.como_comprar, name='como_comprar'), path('contactanos/', views.contactanos, name='contactanos'), path('preguntas-frecuentes/', views.preguntas_frecuentes, name='preguntas_frecuentes'), path('legales/privacidad', views.legales_privacidad, name='legales_privacidad'), path('legales/terminos', views.legales_terminos, name='legales_terminos'), path('muestras/<slug:sample_slug>/medida-y-cantidad', views.StepOneView_Sample.as_view(), name='SampleDetail'), path('muestras/<slug:sample_slug>/subir-arte', β¦ -
Extracting array with indices from GET parameters in Django
My Django project has a page that features a table powered by DataTables. In this case, the table uses server-side processing using a Django view and the GET http method. The Django view unpacks the query string into a QueryDict object, and my task is to unpack the DataTables parameters for each column of the table from this QueryDict. Note that I must use GET, not POST, because I want to use the POST method for other things that actually change data on the server. DataTables submits data for each column in the table relating to search strings and sorting for each column. This data is submitted as per their documentation here; the main point is that columnar params are sent up in the query string like this: ...&column[5][search][value]=searchme&column[6][search][value]=more&... I would like this to be unpacked in such a way that the resultant data structure looks something like this: column = [ { 'search': { 'value': 'searchme' } }, ... ] ...With the elements of the array submitted in the query string in the order specified by their indices. Is there a standard way of accomplishing this with Django's QueryDict? -
Request.POST or Request.POST.get both not providing values in views.py
I am not using Forms in my solution and only trying to get the values from the request.POST so as to save it in the database in the Views.py. It was working before but strangely when I print the key, value pair of the request object it sometimes shows the value and sometime has None in it. HTML : <form id="modify" class="form-horizontal" action="{% url 'modify' customer.customerid %}" method="POST"> {% csrf_token %} <fieldset class="scheduler-border"> <legend class="scheduler-border">{{ customer.customername }}</legend> <div class="form-group"> <span class="col-md-1 col-md-offset-2 text-center"><i class="fa fa-building bigicon"></i><label for="txtCustomerName">Customer Name</label></span> <div class="col-md-11"> <input type="text" name="txtCustomerName" id ="txtCustomerName" class="form-control" placeholder="Customer Name" value="{{ customer.customername }}" disabled="True"> </div> </div> <div class="form-group"> <span class="col-md-1 col-md-offset-2 text-center"><i class="fa fa-building bigicon"></i><label for="txtCustShortName">Customer Short Name</label></span> <div class="col-md-11"> <input type="text" name="txtCustShortName" id="txtCustShortName" class="form-control" placeholder="Customer Short Name" value="{{ customer.customershortname }}" disabled="True"> </div> </div> <div class="form-row"> <div class="form-group col-md-5 col-md-offset-2 text-left"> <span class="col-md-1"><i class="fa fa-user bigicon"></i><label for="txtContactFirstName">Contact Person First Name</label></span> <div class="col-md-12"> <input type="text" name="txtContactFirstName" id="txtContactFirstName" placeholder="Contact Person First Name" class="form-control" value="{{ contact.firstname }}" disabled="True"> </div> </div> <div class="form-group col-md-1 text-left"> </div> <div class="form-group col-md-5 col-md-offset-2 text-left"> <span class="col-md-1"><i class="fa fa-user bigicon"></i><label for="txtContactLastName">Contact Person Last Name</label></span> <div class="col-md-12"> <input type="text" name="txtContactLastName" id="txtContactLastName" placeholder="Contact Person Last Name" class="form-control" value="{{ contact.lastname }}" disabled="True"> </div> β¦ -
Taking a form response, making an api call then displaying the api call in Django
I'm trying to have a Django form capture data from a user's input, take the input to make an API call to Aylien API and display the raw json result on the same page. I'm able to take the form input and successfully make an API call & get the JSON to print on the console, but am having a hard time displaying the call's result on the page. I keep getting UnboundLocalError: local variable 'api_response' referenced before assignment error. Code below models.py from django.db import models # Create your models here. class News(models.Model): title = models.TextField(max_length=120) form.py from django import forms from .models import News class NewsForm(forms.ModelForm): class Meta: model = News fields = [ 'title'] views.py from django.shortcuts import render from .models import News from .form import NewsForm import requests import aylien_news_api from aylien_news_api.rest import ApiException def news_create_view(request): ## link form to model for gathering search term from user form = NewsForm(request.POST) if form.is_valid(): # create an instance of the aylien api class api_instance = aylien_news_api.DefaultApi() ## build opts for api call from the response from the user opts = { 'title': form.cleaned_data['title'], 'language': ['en'], 'not_language': ['es', 'it'], 'published_at_start': 'NOW-7DAYS', 'published_at_end': 'NOW' } try: # List the stories β¦