Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - Upload Image Fails at decoding data
I have an application which offers endpoint for adding a image. Posting image to api works well from when I tried from django rest endpoint page. What I want to accomplish is that posting a image to api from different application. I was receiving: “The submitted data was not a file” error first. Then I follow the answer for this question : Django REST Framework upload image: "The submitted data was not a file" and tried to decode data, but it didn't work well for me. I am receiving the following error: ValueError: string argument should contain only ASCII characters When I printed the photo data I got from POST request it looks like the following: Output of photo data Here is my model, serializer, and API Class to upload photos: class PictureStep(Step): type = 'PICTURE' photo = models.ImageField( upload_to='infrastructure/steps/pictures/%Y/%m/%d', blank=True, null=True ) note_from_driver = models.TextField(blank=True, null=True) class PictureStepSerializer(ModelSerializer): photo = Base64ImageField(max_length=None, use_url=True) class Meta(StepSerializer.Meta): model = PictureStep fields = StepSerializer.Meta.fields + ( 'photo', 'note_from_driver', ) class Base64ImageField(serializers.ImageField): def to_internal_value(self, data): from django.core.files.base import ContentFile import base64 import six import uuid # Check if this is a base64 string if isinstance(data, six.string_types): # Check if the base64 string is in … -
Python django URL brackets modification
I am trying to write a Python script which will replace the brackets with: ( -> %28 ) -> %29 I found that the django module in Python can do this using the function iri_to_uri. For example I want to convert https://example.com/pat(da35dd40)/index.html into https://example.com/pat%28da35dd40%29/index.html but for some reason my script doesn't work: #!/usr/bin/env python import subprocess import json import os.path # -*- coding: utf-8 -*- from django.utils.encoding import iri_to_uri print uri_to_iri(https://example.com/pat(da35dd40)/index.html) And it reports invalid syntax, if I put the URL into quotes it doesn't transform the brackets. The ultimate goal is this script to process an input from the user and escape all special characters, so that the script could be processed by other processes. -
django 1.10 csrf_token not creating hidden input field
I have a form, but django not creating a hidden input like - <input type="hidden" name="csrfmiddlewaretoken" value="80NGejzAPl2aCbEEuyLqIT3ppMTJLilY"> If trying send a form I have 403 mistake, CSRF token missing or incorrect. This is my code: html <form class="get-info" action="/" method="post">{% csrf_token %} ... </form> middleware 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.csrf.CsrfResponseMiddleware', 'django.template.context_processors.csrf', views.py from django.core.mail import BadHeaderError, send_mail from django.http import HttpResponse, HttpResponseRedirect, request from django.shortcuts import render, render_to_response from django.template import RequestContext from django.template.context_processors import csrf from django.contrib import messages def callback(request): phone = request.POST.get('phone', None) lastpath = request.POST.get('lastpath', None) if validatePhone(phone): if sendMail(phone): messages.success(request, 'Мы скоро перезвоним Вам') return HttpResponseRedirect(lastpath) else: messages.error(request, 'Ошибка в отправке запроса. Попробуйте позже.') return HttpResponseRedirect(lastpath) else: messages.error(request, "Неверный формат номера телефона. Телефон нужно вводить в формате +99999999999") args = {} args.update(csrf(request)) args['form'] = phone return render(request, 'index.html', args) -
How to auto login in django application using windows authentication
I want the login system which auto authenticates the user based on the windows credentials. And it should also be integrated with LDAP. My app is working with LDAP only but not automatically signing the users based on windows credentials. Below is the link which i have followed to auto login the users https://docs.djangoproject.com/en/1.10/howto/auth-remote-user/ Please help -
how to upload audio files to s3 using django api?
how to upload audio files to S3 buckets by creating different playlists using django apis import boto3 s3 = boto3.resource('s3') s3.meta.client.upload_file('filename', 'bucketname', 'desired filename in s3') other than boto -
Django refresh_from_db for ForeignKey
Is there a way to use refresh_from_db and automatically propagate it on ForeignKey ? model.py: class TestItemModel(models.Model): value = models.IntegerField(default=0) relies_on_item = models.ForeignKey('self', on_delete=models.SET_NULL, blank=True, null=True ) shell: >>> end_product = TestItemModel(value=1) >>> end_product.save() >>> container_product = TestItemModel(value=10,relies_on_item=end_product) >>> container_product.save() >>> end_product.pk 12 >>> end_product_for_update=TestItemModel.objects.get(pk=12) >>> end_product_for_update.value = 4 >>> end_product_for_update.save() >>> container_product.relies_on_item.value 1 >>> container_product.refresh_from_db() >>> container_product.relies_on_item.value 1 The value returned at this point is still the initial one. Is there an option to make refresh_from_db automatically cascade on elements referenced by ForeignKey? It is possible to do it by explicitly using refresh_from_db on the referenced item - shown below. But I would like to only have to do refresh_from_db on container_product itself. shell (continued): >>> container_product.relies_on_item.refresh_from_db() >>> container_product.relies_on_item.value 4 -
Converting Django QuerySet to JSON
I want to convert Django QuerySet to json format. I have next code: users = list(Calculations.objects .values('user__first_name', 'user__last_name') .distinct().exclude(user=request.user) .annotate(num_calculations=Count('user')) .order_by('-num_calculations')[:10]) users_json = json.dumps(users) Thus, I want to get 10 users with the most calculations. With my code users_json is as follows: '[ { "user__first_name": "John", "user__last_name": "Doe", "num_calculations": 4 }, { "user__first_name": "Jane", "user__last_name": "Doe", "num_calculations": 2 } ]' Any advice how to solve it? -
How do I directly modify the li inside of a django block?
My project.db is corrupt. I have a navigation menu that is being generated by django_cms, and all I want to do is modify the li's in the navigation bar. But because I can't access the html directly, I have no way of doing this. How do I modify the html of a django block? this is the code that I have: {% show_menu 0 1 100 100 "menu.html" %} I'd like to be able to get into show_menu directly, and modify all of the li's so that I can change their names. -
Use AJAX to update django if-else template
In template I have: {% for item in items %} {% if item.public is True%} <a href="{% url 'motifapp:article_public_edit' article.id %}"> show icon1 </a> {% else %} <a href="{% url 'motifapp:article_public_edit' article.id %}"> show icon2 </a> {% endif %} {endfor} I use ajax to handle the request here: $(anchor).click(function(e){ e.preventDefault(); var href = $(this).attr('href') $.ajax({ type: 'POST', url: href, data: {csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),}, success: function (response) { //refresh a div ? } }); }); Ajax handle the post, and in view it reverse a boolean value 'public'. Question is, how do I update the template? I can pass the opposite icons and value, but it seems very redundant. Is there a way just to refresh that div with anchor and let the if else statement takes care of what's showing ? Thanks -
what is the best way to create copy of Model on save?
I am creating a simple application which has these 2 simple Models: from django.db import models from django.core.exceptions import ValidationError, ObjectDoesNotExist class Node(models.Model): title = models.CharField(max_length=50) def __str__(self): return "{}".format(self.title) class Path(models.Model): class Meta: unique_together = ['from_node', 'to_node'] from_node = models.ForeignKey(Node, on_delete=models.CASCADE, related_name='from_node') to_node = models.ForeignKey(Node, on_delete=models.CASCADE, related_name='to_node') distance = models.DecimalField(max_digits=19, decimal_places=2) def __str__(self): return '{0} to {1}'.format(self.from_node, self.to_node) def clean(self): if self.from_node == self.to_node: raise ValidationError("From and to Nodes must be different ") So far so good.. No what i want is to create and Manage another Mirror Copy of the Path Model like this: Suppose we have 3 Nodes "A", "B", "C" when a user creates a path from A & B i want to also create another mirror path from B to A which will also have the same distance. So i added this save method to my Path model: def save(self, force_insert=False, force_update=False, using=None, update_fields=None): super(Path, self).save(force_insert, force_update, using, update_fields) try: mirror_path = Path.objects.get(from_node=self.to_node, to_node=self.from_node) if not self._state.adding: mirror_path.distance = self.distance mirror_path.save() except ObjectDoesNotExist: Path.objects.create(from_node=self.to_node, to_node=self.from_node, distance=self.distance) So now when a new Path is created a mirror Path is also created, However when any existing path is updated there is a recursion as the two models … -
How to query as GROUP BY two table in django?
How do I use the django query? The following is a written sql statement: SELECT a.name, count(uri_id) as counts from interface_uri a LEFT JOIN interface_interfacetestcase b on a.id = b.uri_id GROUP BY a.name, a.version_id; -
script array to django database
I add x and y to array. web can appear x and y. but googlemap can't print. hlep me and thanks. function initialize() { var myLatLng = {lat:24,lng:121}; map = new google.maps.Map(document.getElementById('map'), { zoom: 8, center: new google.maps.LatLng(23.6, 121),}); //mapTypeId: google.maps.MapTypeId.ROADMAP setMarkers(map); } var beaches = [ ['Bondi Beach', 24.890542, 121.274856, 4], ['Coogee Beach', 24.923036, 121.259052, 5], ['Cronulla Beach', 24.028249, 121.157507, 3], ['Manly Beach', 24.80010128657071, 121.28747820854187, 2], ['Maroubra Beach', 24.950198, 121.259302, 1] ]; function setMarkers(map){ for (var i = 0; i < beaches.length; i++) { var beach = beaches[i]; var marker = new google.maps.Marker({ position: {lat: beach[1], lng: beach[2]}, map: map, title: beach[0], //zIndex: beach[3] }); } } is all good but let code chang to : [enter image description here][3] [enter image description here][4] web is not error and have x and y,but map can't print marker. [enter image description here][5] function initialize() { var myLatLng = {lat:24,lng:121}; map = new google.maps.Map(document.getElementById('map'), { zoom: 8, center: new google.maps.LatLng(23.6, 121),}); //mapTypeId: google.maps.MapTypeId.ROADMAP setMarkers(map); } //var beaches = [ // ['Bondi Beach', 24.890542, 121.274856, 4], // ['Coogee Beach', 24.923036, 121.259052, 5], // ['Cronulla Beach', 24.028249, 121.157507, 3], // ['Manly Beach', 24.80010128657071, 121.28747820854187, 2], // ['Maroubra Beach', 24.950198, 121.259302, 1] //]; {% … -
Django - Rollback is not happening when exception raised
settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'diva', 'USER': 'root', 'PASSWORD': 'admin', 'ATOMIC_REQUESTS':True, 'HOST': 'localhost', 'PORT': '3306', }, } views.py def create_project(self, request): try: with transaction.atomic(): code here except Exception as e: print "Exception--->",str(e) response = {"status":"failed",'response': ugettext("projects.services.create_project.failure")} stat = status.HTTP_400_BAD_REQUEST return Response(response, status=stat) in my code, if it raises ObjectDoesNotExist Exception rollback is not happening, can anyone explain how transactions work in django with example. -
Send user data in python requests module
I am unable to send the user details along with requests module i had to hard code the user details in the data payload to identify the user. full_url = ''.join(['http://', get_current_site(request).domain, '/am/reply']) data = { 'agent_type':'trigger', 'input':platform, 'userid':request.user.id ####==>> had to send userid like this } a = requests.get(full_url,params=data) Is there way to send all general request data using requests.? -
Make an api using django-rest-framework and pandas
I am planning to make an api using django-rest-framework and pandas. My task is to use the already existing api of my project and collect the data and convert it to pandas dataframe and make my own api using django-rest-framework.I am not able to understand should I use my own django models and use them with already existing models or should I don't use my models and use the already existing api data models. How should I implement this using django-rest-framework. Can someone help me iam a bit confused. -
String not matching in django/python
the problem i have that if condition is not working. both p.user and username gives same value when i write print(p.user) & print(username) but still it is not matching and when i print context it always have false value for author. def post_full(request, username, slug): post = Post.objects.filter(slug = slug) instance = get_object_or_404(Post, slug = slug) files = file.objects.filter(Post = instance) context = {'post': instance,'file':files} for p in post: if p.user==username: context.update({'author': True}) else: context.update({'author': False}) try: slug = request.POST["query"] if slug: print(slug) query = slugify(slug) return HttpResponseRedirect('/search/%s/'%query) except Exception as e: pass return render(request, "post_detail.html", context) -
views must be a callable or a list\tuple in case of include
Django==1.10.5 Login. I have made login form, then write these codes and wanted to run the server Urls.py: urlpatterns = [ #previous login view #url(r'^login/$', views.user_login, name='login'), #login/logout urls url(r'^$', views.dashboard, name='dashboard'), url(r'^login/$', 'login', name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout', name='logout'), url(r'^logout-thenlogin/$','django.contrib.auth.views.logout_then_login', name='logout_then_login'), ] Views.py: from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required from .forms import LoginForm def user_login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(username=cd['username'], password=cd['password']) if user is not None: if user.is_active: login(request, user) return HttpResponse('Authenticated successfully') else: return HttpResponse('Disabled account') else: return HttpResponse('Invalid login') else: form = LoginForm() return render(request, 'account/login.html', {'form': form}) @login_required def dashboard(request): return render(request, 'account/dashboard.html', {'section': 'dashboard'}) When i wanted to runserver- i got this message: Views must be a callable or a list\tuple in case of include -
Django logging do not log with Apache
My django logging works perfectly on localhost. When I pushed it to the server (with Apache), it stops working. In tail /var/log/apache2/error.log was reported problem with permission, so I add the permission to write in the log to www-data user. After that, file django.log was created, and Apache did not complain anymore. But the file is empty, even if I access the pages (application work). My logging settings: DJANGO_LOG_PATH = os.path.join(BASE_DIR, 'logs', 'django.log') LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'console':{ 'class':'logging.StreamHandler', 'formatter': 'simple', 'stream': sys.stderr, }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': DJANGO_LOG_PATH, }, }, 'loggers': { 'django': { 'handlers': ['console'], 'propagate': True, }, 'django.request': { 'handlers': ['file', 'console'], 'level': 'ERROR', 'propagate': False, }, 'django_crontab': { 'handlers': ['file', 'console'], 'level': 'INFO', } } } Any idea why it does not log anything? -
dajaxice.core.js is not getting updated
I have a django project in which dj-dajaxice 0.8.2 is used. I am creating a new app in that project. In my app I have defined my functions in ajax.py file and also in my html file I have included the static dajaxice.core.js file. My html file has following function call <p> <input type="button" onclick="normalFunc()" value="Test"> </p> {% dajaxice_js_import %} <script> function normalFunc() { console.log('here I am working'); Dajaxice.evaluate.testFunction(Dajax.process, {'value':'hello i am here!'} ); alert('here also!!!'); } </script> In console tab of chrome I am able to see the log message 'here I am working' but after that Uncaught TypeError: Cannot read property 'testFunction' of undefined is there. I have registered my testFunction by adding @dajaxice_register line in my ajax.py file. I have also done collecstatic. But no help. My dajaxice.core.js is not getting updated. Any help is much appreciated. -
Django admin search should include inline fields too
I am trying to include a inline field in model admin search_fields but I am not able to figure it. from django.contrib import admin from yourapp.models import Supplier, Product class ProductInline(admin.TabularInline): model = Product class SupplierAdmin(admin.ModelAdmin): inlines = [ProductInline,] admin.site.register(Supplier, SupplierAdmin) Here I want to search product in SupplierAdmin class, though product is inline I am not able to get search functionality -
Script entered data into the database - should colons be given special treatment
So I wrote a script that basically reads data from a txt file and populates this model. class modelNursing(models.Model): item = models.CharField(max_length=250, default="") This is the script (it looks like this). Essentially the txt file contain a string on each line and this script extracts each line string and enters that string into the db as an entry. def PopulateNursing(request): with open('../content.txt') as fp: try: for line in fp: try: modelNursing.objects.create(item=line) except Exception as e: print str(e) except Exception as e: print str(e) Now here is the funny part one of the items modelNursing instance in the database has the item value equal to "Vitals:q4". So doing something like this nursing = modelNursing.objects.filter(item="Vitals:q4") should return a row but unfortunately it does not.So I went into the admin interface to double check if the entry was really there and yes it was there. I then noticed if I delete the column in the string Vitals:q4 from the admin interface and then add it again and save then the query works.Any suggestions on why this might be happening ? Is there a chance that the automation script might be screwing up the colon insertion or something. Any advice would be appreciated. I … -
Modify the choice field depending on type of form in Django Admin
models.py class Configurations(models.Model): all_urls = evaluate_string_json(Data().get_all_urls()) # all urls sample # ["url1", "url2", "url3", "url4"] all_urls.sort() choices_tuple = () for url in all_urls: url_tuple = (url, url) choices_tuple += (url_tuple,) url_name = models.CharField( max_length=250, blank=False, null=False, choices=choices_tuple #choice filed in question here ) url_name above contains a list of choices as shown, on the admin page. What i am trying to do is that if "url1" is already there in db, remove it from choices_tuple for any new entry.Similarly, if admin is used for updating an existing entry, say "url1", choices_tuple shouldn't show any other entry apart from "url1". I am looking for a way to achieve this in my admin form, meaning, models send the value as it is and i modify it on admin page depending on condition(s). admin.py class ConfigurationsForm(forms.ModelForm): class Meta(object): model = Configurations def __init__(self, *args, **kwargs): super(ConfigurationsForm, self).__init__(*args, **kwargs) # Tried this as well to change the tuple. # if kwargs.get('instance'): # print "self.fields['url_name'].value = " + kwargs.get('instance').url_name + "\n" # self.initial['url_name'] = kwargs.get('instance').url_name # else: # pass # self.request = kwargs.pop('request', None) # Voila, now you can access request anywhere in your form methods by using self.request! class ConfigurationsAdmin(admin.ModelAdmin): form = ConfigurationsForm def … -
Django channels socket.send() not sending data
I'm using web sockets built from Django Channels and I have a small Javascript function that when added in my template, should send data to the web sockets via a urls.py type file called routing.py and into a views type file called consumers.py. When I render this template on the browser and go to the browser console and hit socket.send("hi"), it pings me back with data, but I have this command in my code anyway, why isn't getting executed when the page loads? My code should explain the scenario better My template: {% block javascript %} {{ block.super }} var socket = get_websocket('/echo2/'); //Echo2 is the route in route.py socket.onmessage = function(e) { console.log( e.data ); } socket.send('hi'); //This line isn't being executed, why? {% endblock javascript %} Routing.py: from channels.routing import route channel_routing = [ route("websocket.receive", consumers.ws_echo2_message, path='^/echo2/$'), ] Consumers.py def ws_echo2_message( message ): message.reply_channel.send({ 'text': json.dumps({ 'message': message.content['text'], 'dave': 'hi' }) }, immediately = True) time.sleep(2) message.reply_channel.send({ 'text': message.content['text'], }, immediately = True) time.sleep(2) message.reply_channel.send({ 'text': message.content['text'], }, immediately = True) When I go to my browser console and say `socket.send('hi'), it gives me this: >socket.send("HI"); > {"message": "HI", "dave": "hi"} > HI So, if `socket.send' works in … -
How to integrate Django API project with nodejs and react on frontend?
I have a project in Django of an API and I want to use node js together with django and know if you can use react in conjunction with both to realize the frontend of my application and if possible it would be advisable to develop the application this way? Or which would be a better option to work with these technologies? In django I'm using ->Django Rest Framework Node js I want to use it to give Real-Time to my application -->Socket.io React -->Redux -->React-router Thank you very much for your time and your attention. -
Understanding where to put the IPN reciever function in django-paypal
I have a similar issue to the post here in regards to setting up the receiver function for the paypal-ipn What we are trying to do(I don't know this other person but I assume we stand together on this topic) is to understand how to deduce a path to receiving a paypal IPN signal in which we then can update the django database. I have implemented the django-paypal API by following the directions here Overall what I do is I create a view in my views.py as follows def payment_page(request): """This fucntion returns payment page for the form""" if not request.session.get('form-submitted', False): return HttpResponseRedirect(reverse('grap_main:error_page')) else: amount = set_payment() paypal_dict = { "business": "business@gmail.com", "amount": str(amount), "item_name": "2017 USGF Championships", "notify_url": "https://15b6b6cb.ngrok.io" + reverse('paypal-ipn'), "return_url": "https://15b6b6cb.ngrok.io/Confirm", "cancel_return": "https://15b6b6cb.ngrok.io/RegistrationForm", } form = PayPalPaymentsForm(initial=paypal_dict) context = confirm_information() context["amount"] = amount context["form"] = form request.session['form-submitted'] = False valid_ipn_received.connect(show_me_the_money) return render(request, "grap_main/payment.html", context) Where my then I have payment.html which then create the paypal button simply by using the line as advised in the documentation {{ form.render }} Now I can receive a POST to the paypal url that I specified in the documentation however I don't know where I should put my signal function …