Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i am not able to get my uploaded picture in edx-ora2
Request Method: GET Request URL: http://127.0.0.1:8000/openassessment/storage/1/ Raised by: openassessment.fileupload.views_filesystem.filesystem_storage enter code here urlpatterns = patterns('openassessment.fileupload.views_filesystem', url(r'^(?P.+)/$', 'filesystem_storage', name='openassessment-filesystem-storage'), )` enter code here @require_http_methods(["PUT", "GET"]) def filesystem_storage(request, key): if isinstance(key, unicode): key = key.encode("utf-8") if request.method == "PUT": if not is_upload_url_available(key): raise Http404() content, metadata = get_content_metadata(request) save_to_file(key, content, metadata) return HttpResponse() elif request.method == "GET": if not is_download_url_available(key): raise Http404() return download_file(key) enter code here class Backend(BaseBackend): def get_upload_url(self, key, content_type): make_upload_url_available(self._get_key_name(key), self.UPLOAD_URL_TIMEOUT) return self._get_url(key) def get_download_url(self, key): make_download_url_available(self._get_key_name(key), self.DOWNLOAD_URL_TIMEOUT) return self._get_url(key) def _get_url(self, key): key_name = self._get_key_name(key) url = reverse("openassessment-filesystem-storage", kwargs={'key': key_name}) return url -
chain filter query params
I know it's a know subject but hear me out, I'm currently filter on query_params in my view like this: filter_date = self.request.query_params.get('filter_date', None) if filter_date is not None: queryset = queryset.filter(next_action_date__gte=filter_date) return queryset and I'm showing my contacts by next_action_date, now I have this custom data structure and I need to add it to this filter so it will show my contacts from most important to unimportant, I've tried to add it to the filter but I'm not getting any data, so how can I appropriately get this done, can someone show me? This is my get_queryset: def get_queryset(self): queryset = LeadContact.objects.none() user = self.request.user if user.has_perm('cms_sales.can_view_full_lead_contact_list'): queryset = LeadContact.objects.all() elif user.has_perm('cms_sales.can_view_lead_contact'): queryset = LeadContact.objects.filter(account_handler=user) filter_date = self.request.query_params.get('filter_date', None) # This is the custom ordering data structure virgin_data = LeadContact.objects.filter(status=LeadContactConstants.STATUS_PRISTINE) contacted_data = LeadContact.objects.filter(status=LeadContactConstants.STATUS_CONTACTED) qualified_data = LeadContact.objects.filter(status=LeadContactConstants.STATUS_QUALIFIED) client_data = LeadContact.objects.filter(status=LeadContactConstants.STATUS_CLIENT) order_data = list(client_data) + list(qualified_data) + list(contacted_data) + list(virgin_data) if filter_date is not None: queryset = queryset.filter(next_action_date__gte=filter_date) return queryset -
Recursive Model in Admin Add Page
I have a model called Category which is recursive. The model goes like this: from django.db import models class Category(models.Model): name = models.CharField(max_length=255, blank=False) description = models.CharField(max_length=255, blank=False) sub_category = models.ForeignKey('self', blank=True, null=True, related_name='subcategory') def __str__(self): return self.name my admin.py for category is: from django.contrib import admin from category.models import Category from django import forms class CategoryAdmin(admin.ModelAdmin): list_display = ['id', "name", "sub_category", 'description'] list_filter = ["name"] search_fields = ["name"] ordering = ('sub_category',) class Meta: model = Category admin.site.register(Category, CategoryAdmin) When I want to add more categories to the database, I go to the admin section and do it however, suppose I need to distinguish which category is a part of its parent category how would I go about doing that? right now, I'm seeing: which is not quite helpful, Is there a way to perhaps have the parent category next to the subcategory? like this format: [Java] Tutorials [Python] Tutorials -
Runtime issues using django and sqlite - too much queries
I'm having a runtime problem with the following code: # filter start and end date matches = database.objects.filter(start__gte= Start, end__lte= End) # iterate through matches for Item in matches: # filter database again test = database.objects.filter(cm1=Item.cm1, cm2=Item.cm2, cm3=Item.cm3) # compare first item of filter with iterated Item if test[0] == Item: TrueRun = True else: TrueRun = False I have a database with around 80k rows. In a first step I filter the rows I want to look at, should be normally around 8k. In a second step I iterate over all of these items and check if they're unique or the first ones with some specicific attributes (cm1, cm2, cm3). The Problem is now, that I do 8k database queries, which all together take about 15 minutes. Is there any way to accelerate this, for example using a dict before the loop which contains all possibilities of cm1 and it's matching rows? Thanks for your help! -
How to show in template current users role in project?
Can someone say where I did mistake? I have Project model. Every project has members. I have project_detail page where I want to show current user's username and his role in project. Right know in template it shows me only current user's username but not his role in project. models.py: class Project(models.Model): members = models.ManyToManyField(User, through='Member', help_text=_('Members')) ROLE_CHOICES = ( ('manager', _('Manager')), ('developer', _('Developer')), ('business_analyst', _('Business Analyst')), ('system_analyst', _('System Analyst')), ) class Member(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) role = models.CharField(max_length=20, choices=ROLE_CHOICES) views.py: def project_detail(request, project_code): project = get_object_or_404(Project, pk=project_code, status='open') context = {'project': project,} return render(request, 'project/project_detail.html', context) project_detail.html: <span class="nav-link active navbar-text"> {{ user.get_username }}: {% for member in project.member_set.all %} {% if member.user == user.get_username %} {{ member.get_role_display }} {% endif %} {% endfor %} </span> -
Django Media File deployment - change in file location
I am having a web server running in Digitalocean. We are in a situation where we need to upload our clients' images (media files). Now, as far as the understating goes, in the following case: class Car(models.Model): ... photo = models.ImageField(storage=fs) The photo field will store the url of the file, right? Now we might move to amazon (with S3 as the storage system) in near future. Will the model field value change? How do you, then, suggest us in taking care of the change (as we will have two servers then, one EC2 for django & S3 for media & static files)? -
Django return different class-based view according to whether an object has been created
I would like ,if possible to have a function where according to whether an object exists,it would either call my CreateView or my UpdateView and redirect to the corresponding template of the view. I have already created the CreateView and UpdateView and they both work fine,seperately. I tried to create a function to call the relevant template each time, but it doesn't redirect . Which I think is wrong to think that I need it to redirect but I can't think something else. here's my code: def getArchived(request): archived = '' q = request.GET.get('q',None) archived = Archivedfolder.objects.get(folder=q) template_create = "commondev/Archivedfolder/create.html" template_update = "commondev/Archivedfolder/update.html" if archived.pk: return render(request,template_update) else: return render(request,template_create) At the code I am showing I use render() . I have also tried HttpResponse(),HttpResponseRedirect(),redirect(),render_to_response(). -
Django sever access
Is it possible to view your database schema using the django server like one does using phpmyadmin or any other tool to view what is in your database. I have used laragon with laravel was wondering if there is something similar to it in django. -
Angular2 - Cannot POST data to Django Model Foreign key
I try to POST data to my JSON API but the data cannot save/post in to the Foreign Key Field. This is my serializer: class LevelSerializer(serializers.HyperlinkedModelSerializer): id = serializers.ReadOnlyField() levelling_class = serializers.SlugRelatedField(slug_field='name', required=False, read_only=True) lclass = serializers.HyperlinkedRelatedField(view_name='class-detail',source='levelling_class',read_only=True) levelling_type = serializers.SlugRelatedField(slug_field='name', required=False, read_only=True) regional_office = serializers.SlugRelatedField(slug_field='name', required=False, read_only=True) code = serializers.SlugRelatedField(slug_field='name', required=False, read_only=True) file_id = serializers.SlugRelatedField(slug_field='number', required=False, read_only=True) status = serializers.SlugRelatedField(slug_field='name', required=False, read_only=True) group = serializers.SlugRelatedField(slug_field='name', required=False, read_only=True) class Meta: model = File_Levelling fields = ('__all__') This my code in Angular2 this.levelling={ levelling_class: "", levelling_type: "", regional_office: "", code: "", running_number: "", status: "", name: "", year: "", file_name: "", route: "", group:"", } PostData(){ let body = JSON.stringify(this.levelling); let process = JSON.stringify(this.levelling_process); let database = JSON.stringify(this.create_db); let task = JSON.stringify(this.file); let headers = new Headers({ 'Content-Type': 'application/json' , 'accept': 'application/json'}); let options = new RequestOptions({ headers: headers }); this.http.post(this.level_url, body, options) .subscribe( data => this.event = body, error=> alert(error), () => alert('Successfully Create File'), ) The problem is i can only save Name, Year, File Name and Route. Do i need to change my serializer or my function in angular? -
How to show APScheduler's name and next_run_time on the django template?
This is my project: https://github.com/easytrader/Apscheduler_for_django I want to show APScheduler's job imformation. This is my APScheduler's code: from apscheduler.schedulers.background import BackgroundScheduler scheduler = BackgroundScheduler() scheduler.start() I have add two jobs into the scheduler: scheduler.add_job(test_1, 'interval',id='my_test_job1', seconds=3) scheduler.add_job(test_2, 'interval',id='my_test_job2', seconds=3) This is my view function: def hello_world(request): running_jobs = scheduler.get_jobs() return render_to_response('hello_world.html',{},context_instance = RequestContext(request)) I use the template code below, but it can't work well: {% for running_job in running_jobs %} {{running_job}} {% endfor %} How to show APScheduler's name and next_run_time on the django template? Thank you. -
Filtering Many-to-many field in Rest Framework
Im working with the Django REST Framwork and got some issues with the Browsable api. I cannot filter a ManyToMany field so that it only shows the objects which the user is owner of. I do manage to filter the the user and filter out m own objects. In the serializer I have def __init__(self, *args, **kwargs): super(BidSerializer, self).__init__(*args, **kwargs) request_user = self.context['request'].user self.fields['my_items'].queryset = Item.objects.filter(owner=request_user) print(self.fields['OfferObject1'].queryset) self.fields['others_items'].queryset = Item.objects.exclude(owner=request_user) self.fields['user'].queryset = User.objects.filter(username=request_user) The strange thing is that the fields 'user' and 'others_items' are filtered as supposed. While 'my_items' is not filtered but showing all items. However the line containing the print statement shows a correct output. The difference between the fields is that my_items is a ManyToMany field and others_items is a foreign key. Should it be possible to filter as I like? If not why and how could I filter my choices in a better way? -
Special characters in filenames and paths
I have django app that allows users to enter a query and in response returns a list of documents sorted by their relevance. On clicking the download button the users can download the files. For most cases the option works fine but breaks when the file name or the folder path has special characters (such as - &). The download button contains the location of where the file is located. If the path or filename contains a special character, only the string upto the special character is passed to the function in the views.py file and hence returns a FileNotFoundError at .... So how do I ensure that django reads the complete path in cases where there are special characters involved -
Link Azure Connection String with Django WebApp?
It's my first website on Azure with Python. I developed before with .NET. Sorry if my question is a basic one. I deployed my Django website on Azure. It works fine with the DB settings in the settings.py. Next step, I thought, is to transfer the DB settings to Azure's Application Settings - Connection Strings, what I did. I am aware that I need the prefix MYSQLCONNSTR_connectionString1. How can I now link my Django/Python WebApp with the Connection String in the Azure Application Settings? I would be very grateful for help. -
How to display image from api in django?
I have an API response which contains multiple images.I am using get service to get the text and images on the form.Text is coming but I am facing difficulties in retrieving images from API. Key value from API for my image is:-*** result_data_for_editing.media.mediaPath My HTML where I want to retrieve my image is:- <img type="file" id="files" multiple name="media" accept="image/*"/> <output id="list" value="result_data_for_editing.media.mediaPath"></output> and the corresponding javascript for creating thumbnails for that image is:- $(document).on('click', '.browse', function () { var file = $(this).parent().parent().parent().find('.file'); file.trigger('click'); }); $(document).on('change', '.file', function () { $(this).parent().find('.form-control').val($(this).val().replace(/C:\\fakepath\\/i, '')); }); //function to create thumbanil of images uploaded on client-side function handleFileSelect(evt) { $("#list").html(""); var files = evt.target.files; // FileList object // Loop through the FileList and render image files as thumbnails. for (var i = 0, validatedfiles, f; f = files[i], validatedfiles = files[i]; i++) { var reader = new FileReader(); var imagearray = []; imagearray = files[i]; // Closure to capture the file information. reader.onload = (function (theFile) { return function (e) { // Render thumbnail. var span = document.createElement('span'); span.innerHTML = ['<img class="thumbs_image" src="', e.target.result, '" title="', escape(theFile.name), '"/>'].join(''); document.getElementById('list').insertBefore(span, null); }; })(imagearray); // Read in the image file as a data URL. reader.readAsDataURL(imagearray); } } … -
Django python How to insert a json containing several objects in postgresql
I would like to insert a json containing several publications in my database. I want to create a field for each publication. For the moment I managed to insert a json containing a single publication, however when I try with two, it makes me a mistake: Script python : fichier = open("result2.json","r") filedata = json.load(fichier) #for '{' in filedata: #print "ici un {" prod = Production() prod.cle = filedata.get("UT") prod.titre = filedata.get("TITRE") prod.publis = filedata prod.maj = timezone.now() prod.save() fichier.close() result2.json { "UT": "WOS:123456", "TI": "firstpubli", "DT": "journal", "PY": "2016", "TITRE" :"firstpubli2016", "AU": "me, you" } What does it do enter image description here Now if I put 2 publications in result2.json: { "UT": "WOS:123456", "TI": "firstpubli", "DT": "journal", "PY": "2016", "TITRE" :"firstpubli2016", "AU": "me, you" } { "UT": "WOS:78910", "TI": "secondpubli", "DT": "journal", "PY": "2016", "TITRE" :"secondpubli2016", "AU": "me, you" } When I run the python script to insert the data, I have this error Traceback (most recent call last): File "test.py", line 45, in <module> filedata = json.load(fichier) File "/usr/lib/python2.7/json/__init__.py", line 291, in load **kw) File "/usr/lib/python2.7/json/__init__.py", line 339, in loads return _default_decoder.decode(s) File "/usr/lib/python2.7/json/decoder.py", line 367, in decode raise ValueError(errmsg("Extra data", s, end, len(s))) ValueError: Extra data: … -
Create queue and assign tasks to it
I am using celery 4.0.2, celerybeat, rabbitMQ as a broker, django 1.10,python 2.7. I have a multi tenant system where a process is given to celery as a task for it to process. The process may take a long time to complete and at present every task is in a single queue and hence takes a long time to complete. I want to run the task and the cron job is set to run every hour. When the task takes more than an hour, the celerybeat will restart the complete process or overlap it. So, I want to handover each task to different queues dynamically and each queue to a different worker. I have tried doing it but could only achieve transferring each task to different pool worker. HELP! -
How to create online judge on Django?
I created website django and want to include online judge. How to do it? I have no idea. I found https://github.com/paramsingh/poj. But I does not work. It gives error and I could not see how it works. -
Python/Django "Import Error" in project directory
I've been having troubles with this and cannot find the solution... I've browsed all SO questions about this but nothing worked in my case... So here's the problem: I clone a project from git repository Set up a virtualenv called env in project base dir with proper Python version(2.7) & install all reqs succesfully Here's where it gets fun... I navigate to the folder that has my manage.py and do a python manage.py makemigrations which results in from foo.bar.data import CoolioClass ImportError: No module named foo.bar.data My directories look like this (just for illustration): project_root/ ├──env/ ├──django/ │ ├── app │ │ └── models.py (from foo.bar.data import CoolioClass) │ ├── django │ │ └── settings.py │ └── manage.py └──foo/ ├── bar │ ├── __init__.py │ ├── data.py │ └── test.py ├── baz │ ├── __init__.py │ ├── data.py │ └── test.py └── __init__.py When I print sys.path in python shell it results in: /home/johnny/project_root/env/lib/python2.7 /home/johnny/project_root/env/lib/python2.7/plat-x86_64-linux-gnu /home/johnny/project_root/env/lib/python2.7/lib-tk /home/johnny/project_root/env/lib/python2.7/lib-old /home/johnny/project_root/env/lib/python2.7/lib-dynload /usr/lib/python2.7 /usr/lib/python2.7/plat-x86_64-linux-gnu /usr/lib/python2.7/lib-tk /home/johnny/project_root/env/local/lib/python2.7/site-packages /home/johnny/project_root/env/lib/python2.7/site-packages -
Django Admin restrict foreign keys with Grappelli autocomplete feature
I'm using Grappellis (v2.8.3) autocomplete feature to lookup foreign keys. That works great so far. I have two foreign keys customer and location in my model TheContract which are related to each other. A location belongs to one customer and one customer could have multiple locations. Now, If I have chosen a Customer (e. g. "Customer A" with location "Location A") in the admin view, I want to use the autocomplete feature again, but with a restriction to the belonging locations (in this case "Location A") of the previous chosen customer "Customer A". I don't want to see the locations of the other customers. How could I achieve this? Here's my code: model.py class TheCustomer(models.Model): name = models.CharField(max_length=64, verbose_name=_('Customer Name')) def __unicode__(self): return self.name @staticmethod def autocomplete_search_fields(): return "id__iexact", "name__icontains", class TheLocation(models.Model): name = models.CharField(max_length=64, verbose_name=_('Location Name')) customer = models.ForeignKey(TheCustomer, verbose_name=_('Customer')) def __unicode__(self): return self.name @staticmethod def autocomplete_search_fields(): return "id__iexact", "name__icontains", class TheContract(models.Model): contract_no = models.CharField(max_length=64, verbose_name=_('Contract Number')) customer = models.ForeignKey(TheCustomer, verbose_name=_('Customer')) location = models.ForeignKey(TheLocation, verbose_name=_('Location')) def __unicode__(self): return self.contract_no admin.py @admin.register(TheCustomer) class TheCustomerAdmin(admin.ModelAdmin): pass @admin.register(TheLocation) class TheLocationAdmin(admin.ModelAdmin): pass @admin.register(TheContract) class TheContractAdmin(admin.ModelAdmin): raw_id_fields = [ 'customer', 'location' ] autocomplete_lookup_fields = { 'fk': [ 'customer', 'location', ], } Thanks for your … -
Can't install msqlclient for django/python3 [OSX 10.12.4]
when im running python3 manage.py runserver I get this msg: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'. Did you install mysqlclient or MySQL-python? and because im using mysql datebase on python I tried to install mysqlclient with pip3 I get another error: Collecting mysqlclient Using cached mysqlclient-1.3.10.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "", line 1, in File "/private/var/folders/dd/vlr9cjt17_j4ccyzz89mld1w0000gn/T/pip-build-wt6g2_0e/mysqlclient/setup.py", line 17, in metadata, options = get_config() File "/private/var/folders/dd/vlr9cjt17_j4ccyzz89mld1w0000gn/T/pip-build-wt6g2_0e/mysqlclient/setup_posix.py", line 54, in get_config libraries = [dequote(i[2:]) for i in libs if i.startswith('-l')] File "/private/var/folders/dd/vlr9cjt17_j4ccyzz89mld1w0000gn/T/pip-build-wt6g2_0e/mysqlclient/setup_posix.py", line 54, in libraries = [dequote(i[2:]) for i in libs if i.startswith('-l')] File "/private/var/folders/dd/vlr9cjt17_j4ccyzz89mld1w0000gn/T/pip-build-wt6g2_0e/mysqlclient/setup_posix.py", line 12, in dequote if s[0] in "\"'" and s[0] == s[-1]: IndexError: string index out of range ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/dd/vlr9cjt17_j4ccyzz89mld1w0000gn/T/pip-build-wt6g2_0e/mysqlclient/ Also i read online that mysqlclient is not supported by python3 but i get the similar error when trying to instal MySQL-python: Collecting MySQL-python Using cached MySQL-python-1.2.5.zip Complete output from command python setup.py egg_info: Traceback (most recent call last): File "", line 1, in File "/private/var/folders/dd/vlr9cjt17_j4ccyzz89mld1w0000gn/T/pip-build-jp09s51k/MySQL-python/setup.py", line 13, in from setup_posix import get_config File "/private/var/folders/dd/vlr9cjt17_j4ccyzz89mld1w0000gn/T/pip-build-jp09s51k/MySQL-python/setup_posix.py", line 2, in from ConfigParser import SafeConfigParser ModuleNotFoundError: No … -
render() takes exactly 2 arguments (1 given)
I am getting the error "render() takes exactly 2 arguments (1 given)" after migrating my application to new server. Here is content of my urls.py file: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^warlist/', include('warlist.urls')), url(r'^warlist/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}), ] and in my views.py i am doing below: template = loader.get_template('warlist/index.html') image = loader.get_template('warlist/image.html') table = loader.get_template('warlist/welcomepage_table.html') info = loader.get_template('warlist/info.html') return HttpResponse(image.render()+ template.render()+info.render()+table.render()+info_str+table_str) The above application is working fine in my old server with given code. -
How to return data from a table in a Django template
I am trying to display data from a website in HTML. I have created a class called Video in models.py as follows: class Video(models.Model): filename = models.CharField("File Name", max_length=100) title = models.CharField("Video Title", max_length=250) The database is migrated and I am able to insert data into it using a Django form. I have checked and there is data in the database. I have the following code in my HTML template file, but the page is empty when it is displayed, and is showing no data. {% for video in Video %} <div class="row"> <div class="col-md-3"> <a href="{{ video.filename }}">{{ video.title }}</a> </div> </div> {% endfor %} Why isn't this displaying any data in the rendered HTML page? Edit: This is the relevant code from the view: def listvideos(request): """Renders the listvideos page.""" assert isinstance(request, HttpRequest) return render( request, 'app/listvideos.html', ) -
Understanding django's logging
I am a bit confused on how django is handling the logging. I have this setting for loggers in my settings: Logging settings LOGGING = { ... 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': LOG_BASE_DIRECTORY + '/django.log', 'maxBytes': LOGFILE_SIZE, 'backupCount': LOGFILE_COUNT, 'formatter': 'verbose' }, 'mail_admins': { 'level': 'ERROR', #'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django': { 'handlers': ['file','mail_admins'], 'level': 'INFO', 'propagate': True, }, 'app1': { 'handlers': ['file','mail_admins'], 'level': 'DEBUG', 'propagate': True, }, ... }, } As one can see, I have 2 handlers defined for django and app logs, file and mail_admins. The log level for file is debug. Hence I assume all logs which are debug and above shall use this handler. The level for mail_admins is error. The problem that I am seeing though is that in case of 500 errors while email handler runs and sends the mail there is no logging on the file. -
How to access MEDIA_ROOT files within the view
How do i get MEDIA_ROOT files in the view function, am i suppose to use request.FILES[path]? if so then how do i get the file i want by using settings.MEDIA_ROOT request.FILES[settings.MEDIA_ROOT/file] -
MySql copy data from production to development DB keeping FK references
I am trying to figure out a way to copy data from the production DB(I'll call it prod DB from now on) into the development(I'll call it dev DB from now on). My system is: MySQL Python - Django(if it is any help) The sittuation is like that: assume I have all the tables, and even the rows needed for me from the prod DB the tables have FK refs between them. the PK on every table is self inc. I need to keep data in the dev DB, meaning my mission is to "merge" the data from prod to dev. I've read about mysql dump and not sure it will work since the pk and the fk connection will be all wrong(correct me if I am wrong), So I've been thinking about implementing it on my own, but just not sure about how to preserve the fk connection since after the export of data from prod it will be with the PK of the prod and they will all change when inserted to dev. so far my best idea is to use python and save a mapping of old key to new key but that is a messy way …