Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access many2many field values before saving to database in clean method django
I have the below model and I am trying to raise a validation error in clean method based on the values of many2many field RULE_SET_CHOICES = ( ('G', 'GLOBAL'), ('C', 'LOCAL') ) class Books(models.Model): type = models.CharField(max_length=2, choices=RULE_SET_CHOICES, null=False, default='C') author = models.ManyToManyField(Author, related_name="books", blank=True, null=True) def clean(self): if self.type = 'G': // Check if type is Global and if we tried to associate / add authors then raise a validation error if self.author : raise ValidationError("When type is global, you should not associate authors") But when I tried to access self.author I am facing below error *** ValueError: "<Books: Hello World- G>" needs to have a value for field "author " before this many-to-many relationship can be used So is there any way to access many-2-many relationship field values before saving into database? as I need to raise a validation error based on its values as above -
Django: File Uploading vs File Creating (upload not working)
I have two forms: one where you create a new object (then it creates a new empty file for it), and one where you create an object with an existing file (it uploads the file). The creation form works just fine, it takes the name of the new created object and creates a file with the same name and uploads it in the static folder. However, the second form, it tells you that it got the file object and everything, but the file is not found anywhere. I tried to change directories and modify code and everything and it doesn't seem to work at all and I do not know where is the issue, here are my codes: views.py: def create(request): print request.POST filename = request.POST['name'] f = File(open(filename, "w+")) structure = Structure(name=request.POST['name'], file=f) structure.save() return redirect('/structures') def upload(request): print request.POST structure = Structure(name=request.POST['name'], file=request.POST['file']) structure.save() return redirect('/structures') models.py: class Structure(models.Model): name = models.CharField(max_length=120) file = models.FileField(upload_to='structures') created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) def __str__(self): return self.name html template: [...] <!--CREATE--> <div class="col-md-12"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Créer une nouvelle structure</h3> </div> <div class="panel-body"> <form class="form-horizontal" action="/create", method="post"> {% csrf_token %} <fieldset> <div class="form-group"> … -
Unable to convert dictionary object to JSON object
I want to convert my dictionary object as a JSON as i need to send it in ReactJS file. My code is below: def get(self, request, pk, format = None): queryset = SocialAccount.objects.filter(provider='twitter').get(id=pk) user_id= queryset.uid name = queryset.extra_data['name'] username = queryset.extra_data['screen_name'] data = {'user_id':user_id,'name':name,'username':username} data = json.dumps(data) print(type(json.loads(data))) return Response(json.loads(data)) In this view, I got " class 'dict' " in "print(type(json.loads(data)))" line instead of JSON object. If i am going wrong, please guide me. What i need to do? Thanks. -
how to upload multiple images with resizing with jquery to django backend server
I am using Jquery file upload and compressing code for images with this i can select multiple images but it only compressing and uploading the last image selected so how can i upload multiple images with compression? What modifications are needed plzz suggest. Html code: <input id="fileupload" type="file" name="file" multiple> Jquery code: function csrfSafeMethod(method) { return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $(function () { 'use strict'; var csrftoken = $.cookie('csrftoken'); var url = '/dashboard/{{name}}/{{name_product_type.type_product|urlencode}}/{{abc}}/'; $('#postbtn').on('click', function () { var $this = $(this), data = $this.data(); $this .off('click') .text('Abort') .on('click', function () { $this.remove(); data.abort(); }); data.submit().always(function () { $this.remove(); }); }); $('#fileupload').fileupload({ url: url, crossDomain: false, beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type)) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, dataType: 'json', uploadMultiple: true, // allow multiple upload autoProcessQueue: false, // prevent dropzone from uploading automatically maxFiles: 5, autoUpload: false, acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i, maxFileSize: 5000000, // 5 MB // Enable image resizing, except for Android and Opera, // which actually support image resizing, but fail to // send Blob objects via XHR requests: disableImageResize: /Android(?!.*Chrome)|Opera/ .test(window.navigator.userAgent), previewMaxWidth: 100, previewMaxHeight: 100, previewCrop: true }).on('fileuploadadd', function (e, data) { data.context = $('<div/>').appendTo('#files'); $.each(data.files, function (index, file) { var node = $('<p/>') .append($('<span/>').text(file.name)); if (!index) { node .append('<br>') // .append($('#postbtn').clone(true).data(data)); … -
Manually validate django-simple-captcha
I'm using django-simple-captcha in a project. I want show a captcha to the user in a mobile application and get the response and manually validate the response. The documentation only mentions validation by creating a form. How can I manually validate the response? -
Django "prepopulated_fields" did not work
I am trying to prepopulate the SlugField but it's not happening. I use python 3.6.1 and Django 1.11. Here is my code. models.py class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Черновик'), ('published', 'Опубликовано'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_posts', default=1,) body = RichTextUploadingField(blank=True, default='', config_name='awesome_ckeditor') publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published = PublishedManager() def __str__(self): return self.title class Meta: ordering = ('-publish',) def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) And this is admin.py class PostAdmin(admin.ModelAdmin): list_display = ('title', 'slug', 'author', 'publish', 'status') list_filter = ('status', 'created', 'publish', 'author') search_fields = ('title', 'body') prepopulated_fields = {"slug": ("title",)} raw_id_fields = ('author',) date_hierarchy = 'publish' ordering = ['-publish', 'status'] admin.site.register(Post, PostAdmin) Site is hosted on heroku. Maybe I can auto generate slug field in another way? -
Tree Structure (Foreign Keys to itself) and templates
I have a tree structure for Categories. Categories with a Foreign key that is referring to itself. class Category(MetaData): parent = models.ForeignKey('self', blank=True, null=True, verbose_name='parent category', on_delete=models.CASCADE) name = models.CharField(max_length=255) description = models.TextField() Because I don't know the depth of the categories tree(can't use for) I need to use a recursive function: def cat_for_parents(self, cat_obj): ... if cat_obj.parent_id: p = cat_obj.parent ... self.cat_for_parents(p) But how I implement the function in the template to get something like this(to theoretically infinite recursive loop): <ul> <li>CategoryA <ul> <li>SubCategA1 <ul> <li> Subcateg Subcateg B1 <ul> <li> Subcateg SubCateg C1> <li> Subcateg SubCateg C2> <ul> <li> Subcateg Subcateg B2> ............. -
How to access folder name in djangocms-filer plugin in which user is uploading files?
I want to store media file in folder whose name should be exactly same as folder name created in admin panel 'http://localhost:8000/en/admin/filer/folder/' How can we get folder name from djangocms-filer plugin and pass it to UPLOAD_TO so that file get uploaded at specific location '/media/project_name/Folder_name/file' FILER_STORAGES = { 'public': { 'main': { 'ENGINE': 'filer.storage.PublicFileSystemStorage', 'OPTIONS': { 'location': os.path.join(DATA_DIR, 'media'), 'base_url': '/media/filer/', }, 'UPLOAD_TO': 'filer.utils.generate_filename.randomized', 'UPLOAD_TO_PREFIX': 'project_name', }, 'thumbnails': { 'ENGINE': 'filer.storage.PublicFileSystemStorage', 'OPTIONS': { 'location': '/path/to/media/filer_thumbnails', 'base_url': '/media/filer_thumbnails1/', }, }, }, 'private': { 'main': { 'ENGINE': 'filer.storage.PrivateFileSystemStorage', 'OPTIONS': { 'location': '/path/to/smedia/filer', 'base_url': '/smedia/filer/', }, 'UPLOAD_TO': 'filer.utils.generate_filename.randomized', 'UPLOAD_TO_PREFIX': 'filer_public', }, 'thumbnails': { 'ENGINE': 'filer.storage.PrivateFileSystemStorage', 'OPTIONS': { 'location': '/path/to/smedia/filer_thumbnails', 'base_url': '/smedia/filer_thumbnails/', }, }, }, } -
MultiValueDictKeyError at /app/index "'access_key'"
I got an error,MultiValueDictKeyError at /app/index "'access_key'" .I wrote in views.py from django.shortcuts import render from .forms import UserIDForm from .models import User import json from django.http.response import JsonResponse from django.http import HttpResponseNotFound def index(request): inp_id = request.POST['access_key'] arr = [[100,2],[300,3],[500,4],[800,5],[200,6]] inp_id = int(inp_id) find = False for i in range(int(len(s)/2)): if inp_id == arr[i][0]: find = True if find: id_json = {"id": 100} else: return HttpResponseNotFound() return JsonResponse(id_json, safe=False) in index.html <html lang="en"> <head> <meta charset="UTF-8"> <title>Input</title> </head> <body> <p>Hello</p> </body> </html> in urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^index$', views.index, name='index'), url(r'^response$', views.response, name='response'), ] Now I use POSTMAN. My ideal system is when I post Key is access_key& Value is 100 to http://localhost:8000/app/index in POSTMAN,{"id": 100} is returned.What is matter in my code?Is it unicode error?How should I fix this? -
celery write specific log file for specific task
How to write specific log file for specific task in django celery,i have write overall celery log in single log file how to do that one from redington.celery import app from celery import shared_task @app.task(bind=True, name='load_ibm_machine_images') def load_ibm_machine_images(self): """ Task to perform To load soft-layer machine images """ from cloudapp.management.commands.update_softlayer_machine_types import Command soft_layer_command_object = Command() soft_layer_command_object.handle() return True Thanks in advance!!! -
Subprococess calling a python script in Django running a server through Apache in Linux - Raspbian.
I am working on a home automation project, and I want to run certain python codes when going to certain URLs of my Django Webpage. The subprocess.call() line from my Django Views.py works perfectly on my Django development server: from django.http import HttpResponse import subprocess def home(): subprocess.call(['python','path_to_python_file/python_file.py']) html = "<html><h1>Hello World</h1></html>" return HttpResponse(html) But the python script (or whatsoever command line) is not called on my Raspberry with Apache. According to many previous questions I've read, this could either be a SELinux issue or an premission issue. But I have given persmission to all users, groups, andd others to my python file: sudo chmod a=rwx python_file.py And still the python file is not executed. Using subprocess.Popeninstead of subprocess.call does not work, and neither does setting shell = True. Anyone has any idea of what I am missing here? Otherwise I'll try to switch over to CGI and drop subprocessing for running scripts :-) -
Django : queryset return empty data?
What i do is : 1: Create a Table Using MySQL query. CREATE TABLE data_info (id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, ein INT(100), start_date VARCHAR(50), end_date VARCHAR(50), year VARCHAR(10)); Successfully Done ! 2: Insert some records . 3: Update myapp/model.py from __future__ import unicode_literals from django.db import models from django.contrib.gis.db import models class Datainfo(models.Model): ein = models.IntegerField(blank=False, null=False) start_date = models.TextField(blank=True, null=True) end_date = models.TextField(blank=True, null=True) year = models.TextField( blank=True, null=True) class Meta: managed = True db_table ='data_info' 5: python manage.py makemigrations 6: python manage.py migrate 7: python manage.py shell Shell Screen >>> from main.models import Datainfo >>> Datainfo.objects.all() 0 What is exact error here ? -
How to run python script in html using django and get variable from html input form
i have a sentiment analysis python script, but I want to make it runs in html and get the input form from html page, and the shows the result back in html page. I already use a django framework to run html page. But i don't know how to connect it with python script I have. this is my python script query = input("query? \n") number = input("number of tweets? \n") results = api.search( lang="en", q=query + " -rt", count=number, result_type="recent" ) print("--- Gathered Tweets \n") ## open a csv file to store the Tweets and their sentiment file_name = 'Sentiment_Analysis_of_{}_Tweets_About_{}.csv'.format(number, query) with open(file_name, 'w', newline='') as csvfile: csv_writer = csv.DictWriter( f=csvfile, fieldnames=["Tweet", "Sentiment"] ) csv_writer.writeheader() print("--- Opened a CSV file to store the results of your sentiment analysis... \n") ## tidy up the Tweets and send each to the AYLIEN Text API for c, result in enumerate(results, start=1): tweet = result.text tidy_tweet = tweet.strip().encode('ascii', 'ignore') if len(tweet) == 0: print('Empty Tweet') continue response = client.Sentiment({'text': tidy_tweet}) csv_writer.writerow({ 'Tweet': response['text'], 'Sentiment': response['polarity'] }) print("Analyzed Tweet {}".format(c)) ## count the data in the Sentiment column of the CSV file with open(file_name, 'r') as data: counter = Counter() for row in csv.DictReader(data): … -
How to process a Celery task on a specific vhost?
I have a Celery task like: from celery.task import task from django.conf import settings @task(name="throw_exception") def print_value(*args, **kwargs): print('BROKER_URL:', settings.BROKER_URL) and I'm running a Celery worker inside my virtualenv like: celery worker -A myproject -l info The Worker shows: Connected to amqp://guest:**@127.0.0.1:5672/myapp And when I launch my task from the Django shell with: >>> from django.conf import settings >>> settings.BROKER_URL 'amqp://guest:**@127.0.0.1:5672/myapp' >>> from myapp.tasks import print_value >>> print_value.delay() I never see the task executed in my worker's log. However, if I instead change my worker to use a BROKER_URL with the default "/" vhost, then it immediately executes all the pending tasks, implying all my calls of print_value.delay() are sending it to the wrong vhost even though the correct BROKER_URL is set. What am I doing wrong? -
Celery ignoring vhost in BROKER_URL
I have several separate Celery workers each processing events from a unique RabbitMQ vhost. In my Django settings, I print out the BROKER_URL in the Celery log, which looks like: amqp://guest:guest@127.0.0.1:5672/myname However, immediately under that line in the log is Celery's initialization message: [2017-11-01 00:18:16,568: INFO/MainProcess] Connected to amqp://guest:**@127.0.0.1:5672// which shows no vhost. I have a sample event that sends an email. If I launch this for a specific vhost, it gets executed by a random Celery worker, instead of the Celery worker for the correct vhost. Why is Celery seemingly ignoring the BROKER_URL and my custom vhost? I setup my Django+Celery settings according to the docs, and it works perfectly when I run a single Celery worker on localhost. -
Django REST Generic View for related model
I have a setup similar to this - a Cookbook class, which has multiple Recipes. I have a class CookbookListCreateView(ListCreateAPIView): permission_classes = (IsAuthenticated,) queryset = Cookbook.objects.all() serializer_class = CookbookSerializer and this handles creating / listing the cookbooks. I need a ListCreateView for the Recipe model but the list must belong to a specific cookbook, in such a way that this url: /cookbook/2/recipes would return only recipes found in a cookbook with pk of 2. How can I modify ListCreateAPIView to follow this behavior? -
Storing image in a local file system without model in Django?
I'm a beginner in Django. I'mworking with Rest Api framework for creating a small image mangement api with just "get" and "post" methods. The problem i'm facing is i don't want to save the reference of images in my model instead i just want to save it in my local media folder without any image metadata in my model. So, is there any module to work around this and save it in my local file system after serializing every image that is sent using POST? -
django-auth-ldap installation not working
I am trying to install django-auth-ldap in my windows system it shows the following error \pip-build-3x6rkxb4\pyldap\modules\errors.h(8): fatal error C1083: Cannot open include file: 'lber.h': No such file or directory error: command 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe' failed with exit status 2 My versions are Python - 3.6.3 (64bit) Django - 1.11.6 (64bit) Windows 10 - 64bit Thanks -
Using 'templated_docs' in Libreoffice on AWS Linux (beanstalk)
We have a running project in Debian Server which is working just fine. When we moved into AWS Linux server (using beanstalk), we faced following error: OSError: cannot load library /opt/libreoffice5.4/program/libmergedlo.so: /usr/lib64/libxml2.so.2: version `LIBXML2_GLOBAL_VARIABLES' not found (required by /opt/libreoffice5.4/program/libmergedlo.so). Additionally, ctypes.util.find_library() did not manage to locate a library called '/opt/libreoffice5.4/program/libmergedlo.so Note that we added 'templated_docs' in installed app and also added TEMPLATED_DOCS_LIBREOFFICE_PATH = '/opt/libreoffice5.4/program'. Because there was not YUM repo for Libreoffice we manually installed it and it is installed in /opt/libreoffice5.4. There is symlin in /usr/bin/libreoffice5.4. We have installed version 5.4 while we test with version 5.3 also and we got the same error. Any idea appreciated. -
Django use `super(child,self)`instead of `super()` in latest version
In Django 1.11 tutorial and documentation,there's codes style as super(child,self) everywhere. for instance: return super(ContactView, self).form_valid(form) What's the advantage of it? to reminder you in the current class for memory? -
MultiValueDictKeyError at /signup/ "'username'" in django
i created a signup page which creates users in django admin this is how my signup.html looks alike <h1>signup</h1> <form method="post" action="{% url 'signup' %}"> username: <br/> <input type="text" name="username" > <br/> passwod: <br/> <input type="password" name="password1" > <br/> confirm passwod: <br/> <input type="password" name="passwod2" > <br/> <input type="submit" value="signup"> </form> and this is how i routed using my url to views: from django.conf.urls import url from django.contrib import admin import accounts.views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^signup/', accounts.views.signup, name='signup'), and here is my views section: from django.shortcuts import render from django.contrib.auth.models import User from django.template import RequestContext # Create your views here. def signup(request): if request.method == 'POST': User.objects.create_user(request.POST.get('username') , password=request.POST.get('password1') return render (request,'accounts/signup.html') else: return render (request,'accounts/signup.html') but when i tried to run the server and enter those details regarding username and password while submitting iam getting an error called MultiValueDictKeyError MultiValueDictKeyError at /signup/ "'username'" Request Method: POST Request URL: http://127.0.0.1:8000/signup/ Django Version: 1.11.1 Exception Type: MultiValueDictKeyError Exception Value: "'username'" Exception Location: C:\Python35\lib\site-packages\django\utils\datastructures.py in __getitem__, line 85 Python Executable: C:\Python35\python.exe Python Version: 3.5.3 Python Path: ['D:\\python programs\\reddit\\redditclone', 'C:\\Python35\\python35.zip', 'C:\\Python35\\DLLs', 'C:\\Python35\\lib', 'C:\\Python35', 'C:\\Python35\\lib\\site-packages', 'C:\\Python35\\lib\\site-packages\\win32', 'C:\\Python35\\lib\\site-packages\\win32\\lib', 'C:\\Python35\\lib\\site-packages\\Pythonwin'] Server time: Wed, 1 Nov 2017 04:05:10 +0000 any kind of help is … -
Browsing to AWS machine
I have installed a Python ecommerce framework on a new AWS Linux EC2 machine using SSH. I just created this EC2 instance for this purpose. The AMI had Python 2.7 installed already on it. After I was done with the installation - the installation steps are listed here - I ran the Python webserver using python manage.py runserver and it starts at http://127.0.0.1:8000 on the EC2 instance. The problem is that I am not able to connect to the webpage from my machine, I am using the URL with the following format (without the double quotes) http://"EC2 Public DNS":8000 but I am receiving This site can’t be reached refused to connect. ERR_CONNECTION_REFUSED I have configured the security group to allow incoming traffic on the ports 8000, 80, 443 and 22 When I run netstat -punta I see 127.0.0.1:8000 listed under local address. I even ran sudo service iptables stop the sudo chkconfig iptables off to disable the firewall rules in order to rule them out as a temporary test, but still no luck! I am pretty new to AWS, Python and Linux, so I highly appreciate your help! Thank you. -
Whats the difference when add `[ ]` to regular expressions?
When I watch a video, in the 2:13 second, there is a urlpatterns: urlpatterns = [ url(r'^$', PostListAPIView.as_view(), name='list'), url(r'^(?P<pk>\d+)/$', PostDetailAPIView.as_view(), name='detail'), url(r'^(?P<slug>[\w+])/edit/$', PostUpdateAPIView.as_view(), name='update'), url(r'^(?P<slug>[\w+])/delete/$', PostDeleteAPIView.as_view(), name='delete'), ] We know we can use \d+ to match the numbers, use \w+ to match character,number,and _. But why in there the \w+ be wrap with []? can do not wrap it? And by the way, many Django model use a slug field, why use it? and the slug field has what function? whats the deep meaning of slug? -
How to change sqlite3 from django by tinyDb?
I need your help, I'm finishing a web app, in django, in which we are mining data. We realize that sqlite3 will not support the amount of data. So I started looking for databases NoSQL of the document-oriented type. Because I need quick access to the data when to search. I chose ArangoDB and TinyDB for testing. But I did not find any practical material on how to change sqlite3 by tinydb or arangodb. So I ask: How should I do? Already tried adding other NoSQL databases, such as mongodb and I did not succeed. Python reported that it was not possible to make use of the database. -
django 1.11 - how to get radio dynamic name in view?
this's my template code, I don't know how to get the input name in view.py what should I do ? {% for visitor in visitors %} VIP Black Guest {% endfor %}