Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django database model creation and indexing for Postgres
I'm trying to create new table and index the columns in Postgres through Django model. The table creation uses another table's setup and the indexing uses pg_trgm I can do it directly on Postgres by CREATE TABLE my_table (like my_other_table); and Insert data like INSERT INTO my_table SELECT * FROM MY_OTHER_TABLE TABLESAMPLE BERNOULLI (5); This will take 5% of the data from my_other_table into my_table Then I index the column by CREATE INDEX mycolumn_trgm_idx ON my_table USING GIN (my_column gin_trgm_ops); There's no issue when I perform these actions on postgres directly, but I don't know how (or if it's possible) to do it through django migration -
How to get all the data of an ajax data into django without using request.post
I want to get the data part of an ajax request into django as a dictionary without using request.post['name'] $.ajax({ url: "getAppointments", method: "POST", data: data, //I want to get this data as a dictionary in django context: document.body, }).done(function(data) { alert("Successfully Edited"); }).fail(function(returnedText) { window.alert("An error has occurred. Check log for details"+returnedText.responseText); console.log(returnedText.responseText); }); -
to do or not to do Django to use its own database?
For me now, it's the real dilemma of my past days, and perhaps some expert can give me some advice. It's my first time with Django, and I wanted to use it for a project of assets management, for which I have just designed a new database with its tables/relations/procedures and also because we have already another CMDB based on it, to which, perhaps, we could add our models. Now my doubt is if it better uses Django as a "simple" interface to my newDB or to let Django do use its own database(s), after conversion of my one to some models.py. In the last case I'm also uncertain about how to use, eventually in the future, the database with another framework (I guess it's more comfortable moving from a MySQL to s.else than from Django to s.else..) -
Heroku/Django/S3: Static files not serving from S3, even though media is working
I configured my Heroku/Django app to serve media files from S3 using this tutorial a while back. I only cared about media files on S3 at the time, so I didn't use a custom storage originally, and stored the files in the root of my S3 bucket. But it's working. However, now I want to store my static files on S3 because I have a few static videos and they're larger than I want to serve from my dyno. But when I configure the static files according to the tutorial, they still serve from the dyno. Here's my settings: ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', ... ] ... # Django storages configuration AWS_STORAGE_BUCKET_NAME = os.environ.get('S3_BUCKET') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_AUTO_CREATE_BUCKET = False AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_S3_ENCRYPTION = True AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' # Static file storage STATICFILES_STORAGE = 'core.custom_storages.StaticStorage' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_LOCATION = 'static' STATIC_URL = 'https://{}/{}/'.format(AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) # Media file storage DEFAULT_FILE_STORAGE = 'core.custom_storages.MediaStorage' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media') ... And here's custom_storages.py: $ cat core/custom_storages.py # custom_storages.py from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class StaticStorage(S3Boto3Storage): location … -
How to choose which framework to use?
I am going to make an university project and I need to choose which framework I'll use for the back-end. I'm deciding between Flask, DJango, RoR, Node.js or Spring. What can help me decide which of them to use? Is there any other that I should take into account? I kinda like Spring but I want to know the advantages of each and how they're more suitable for different projects. Thanks. -
Check if values satisfy conditions of Django model
Say I have the django model: class Data(models.Model): name = models.CharField(max_length=50, blank=False) some_number = models.DecimalField(max_digits=6, blank=False) optional_field = models.CharField(max_length=20) And I'm trying to validate whether a list of data will satisfy the conditions of the model. Say I have this list: myData = [ ['bob', 25.22,None], #should pass ['jane', 123.45678,"foo"], #should fail some_number max_digits=6 [None, 25.22,"bar"] #should fail name blank=False ] Is there a clean and fast way to test if each row will pass or fail and also get which condition is not met if it fails? -
How to serve a zip file download in Django?
I have a zip file stored in the Django project directory. How can I serve it to users for downloading. -
Django doesn't take care about Javascript locale
I'm trying to automatically format a number input in a Django project. I add: var fnf = document.getElementById("id_amount"); fnf.addEventListener("keyup", function(event) { var n = parseInt(this.value.replace(/\D/g, ''), 10); fnf.value = n.toLocaleString('es-ES'); }, false); The problem is that in the input field I always have ',' instead of '.' and Django thinks it's a decimal value. -
OpenEDX CMS, we're having trouble rendering your component
I have manually installed the full OpenEdx stack, but when trying to edit an existing unit (creating one works), I get the following error: Here is the exception stack from the logs: Oct 3 16:47:51 ip-xxx [service_variant=cms][contentstore.views.preview][env:sandbox] WARNING [ip-xxx 17550] [preview.py:318] - Unable to render author_view for <VerticalBlockWithMixins @9018 graded=False, annotation_token_secret=u'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', hide_after_due=False, giturl=None, edxnotes=False, source_file=None, course_edit_method=u'Studio', default_tab=None, children=[BlockUsageLocator(CourseLocator(u'Company', u'TD101', u'2018', None, None), u'html', u'8ca5de5b3eae4d95bae0df2c4c67ccce')], in_entrance_exam=False, showanswer=u'finished', display_name=u'Unit', video_speed_optimizations=True, graceperiod=None, format=None, due=None, start=datetime.datetime(2018, 5, 3, 17, 11, tzinfo=tzutc()), xml_attributes={u'filename': [u'vertical/693fb3e8136844e7a3e8c844ece0c0ae.xml', u'vertical/693fb3e8136844e7a3e8c844ece0c0ae.xml']}, days_early_for_beta=None, visible_to_staff_only=False, parent=BlockUsageLocator(CourseLocator(u'Company', u'TD101', u'2018', None, None), u'sequential', u'd7f0672550ec45f9adb6a3e504b6c8fc'), tags=[], matlab_api_key=None, xqa_key=None, is_entrance_exam=False, annotation_storage_url=u'http://your_annotation_storage.com', use_latex_compiler=False, video_bumper={}, show_correctness=u'always', static_asset_path=u'', hide_from_toc=False, show_reset_button=False, name=None, group_access={}, video_auto_advance=False, rerandomize=u'never', user_partitions=[], chrome=None, edxnotes_visibility=True, position=None, max_attempts=None, self_paced=False> Traceback (most recent call last): File "/edx/app/edxapp/edx-platform/cms/djangoapps/contentstore/views/preview.py", line 316, in get_preview_fragment fragment = module.render(preview_view, context) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/xblock/core.py", line 202, in render return self.runtime.render(self, view, context) File "/edx/app/edxapp/edx-platform/common/lib/xmodule/xmodule/x_module.py", line 1903, in render return self.__getattr__('render')(block, view_name, context) File "/edx/app/edxapp/edx-platform/common/lib/xmodule/xmodule/x_module.py", line 1310, in render return super(MetricsMixin, self).render(block, view_name, context=context) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/xblock/runtime.py", line 812, in render updated_frag = self.wrap_xblock(block, view_name, frag, context) File "/edx/app/edxapp/edx-platform/common/lib/xmodule/xmodule/x_module.py", line 1262, in wrap_xblock frag = wrapper(block, view, frag, context) File "/edx/app/edxapp/edx-platform/openedx/core/lib/xblock_utils/__init__.py", line 259, in replace_static_urls static_asset_path=static_asset_path File "/edx/app/edxapp/edx-platform/common/djangoapps/static_replace/__init__.py", line 218, in replace_static_urls return process_static_urls(text, replace_static_url, data_dir=static_asset_path or data_directory) File … -
Iterating multiple for loops based on the same list
Multiple for loops in Template I have the following code in views.py: @login_required def edit_doctorslots(request, cliniclabel, doctor_id): doctor_id=int(doctor_id) doc = get_object_or_404(doctor, docid=doctor_id) cl = Clinic.objects.get(label=cliniclabel) print("Clinic name", cl.name) formslot = SlotForm() formspecialdays = SpecialdaysForm() formweekdays = WeekdaysForm() weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] weekdaynum = [0,1,2,3,4,5,6] weekzip = zip(weekdays, weekdaynum) newweekzip = weekzip return render(request, 'clinic/editslots.html', {'rnd_num': randomnumber(), 'clinic': cl, 'doctor': doc, 'formslot': formslot, 'formspecialdays': formspecialdays, 'formweekdays': formweekdays, 'weekzip': weekzip, 'newweekzip': newweekzip }) My template: <div class="container ml-5 mr-5"> <div class="jumbotron slotgroup slotavailable mb-1 mt-5" id="jumbo_week_avail"> <div class="slot-header" role="alert"> Enter your weekly consultation hours at {{ clinic.name }}. This will supercede regular hours. If you specify some week days, but not others, you will be assumed to be on leave during those days. If you dont specify any week days, but specify regular hours, you will be assumed to be working on all days. </div> {% for weekday, weeknum in weekzip %} <div class="row row_week_avail" id="row_week_avail{{ weeknum }}"> <div class="col-md-1 mr-2"> <label class="switch switch_type1 greenswitch" role="switch"> <input type="checkbox" id="chk_week_avail{{ weeknum }}" class="switch__toggle"> <span class="switch__label"></span> </label> </div> <div class="col-md-2 text-right"> <span class="">{{ weekday }}</span> </div> <div class="col-md-6"> <input type="text" class="form-control timeinput" id="start_week_avail{{ weeknum }}" aria-describedby="mainslotstarthelp" placeholder="Starts at"> <small … -
AVPlayer fails to play video in ios, Error Domain=NSOSStatusErrorDomain Code=-12939
We have an api to upload video using django , the video plays perfectly in android and web but when we play in iOS we get following issue : AVPlayer fails to play video in ios from django api with nginx server, also return Error Domain=NSOSStatusErrorDomain Code=-12939 and Error Domain=AVFoundationErrorDomain Code=-11850 Can you please help me with finding the problem exactly it is from backend or frontend? -
Enabling multiple versions of Django's default form validation errors
A Django form is getting two types of users: user A and user B. These users fill out a solitary text field and press the submit button. In case the users leave the text field empty and press submit, Django's in-built required validation error fires. My requirement is to have two different required validation errors. User A would see the regular required validation error, whereas user B would see the different version. I'm unable to implement this. I passed a special argument to the __init__ method of the form class via self.user_type = kwargs.pop('user_type',None). However, I can't seem to use that to override the required validation error. Why? Because here's how the required validation error is currently defined: class CreateNickNewForm(forms.Form): text = forms.CharField(error_messages={'required':'Please write something'}) I don't know how to access self.user_type available within error_messages in order to pull of what I want to do. Can a more experienced developer chime in? Thanks in advance and let me know in case you need more information. -
ModuleNotFoundError: No module named 'django
I have deployed my site to AWS web server and have setup a python environment running 3.6 and django 2.1.1. I have pulled the logs and am getting the following error: Traceback (most recent call last): File "/opt/python/current/app/weddingProject/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' Target WSGI script '/opt/python/current/app/weddingProject/wsgi.py' cannot be loaded as Python module. I have read other posts and they are saying that django is not installed however, the requirements.txt file does have it listed as a package to install. So I am not sure whats causing the issue and I dont know how to check the server to ensure it is installed. Any help would be great. -
importing json file into django / django rest framework (fixtures vs json load)
I'm trying to build a web-app, using Django and DRF to build a rest API. I have a large JSON file that I'd like to import into Django / just generally use. An example of the json is below: [{"id": 1, "title":"Hello", "sub_title":"", "tag":"", "body": "lorem ipsem"}, {"id": 2, "title":"Hello", "sub_title":"", "tag":"", "body": "lorem ipsem"}] There are many more fields and objects than the example, so it's unrealistic to edit the data manually. What is the best practice with importing this JSON file so it can be used with Django? Some of the existing posts recommend fixtures, however you seem to need additional information describing the model inside the JSON to do this. My models.py looks like this: from django.db import models # Create your models here. class Articles(models.Model): id = models.IntegerField(primary_key=True) title = models.CharField(max_length=256, null=True) author = models.TextField() body = models.TextField() and serializers.py: from rest_framework import serializers from api import models class ArticleSerializer(serializers.ModelSerializer): class Meta: model = models.Articles fields = '__all__' -
Django query is it possible to use self
I am wondering if is possible to use self parameters in django models lets says in MyModel I have date_from and date_to I wish to select the models where date_from != date_to how is it possible to achieve it? I need something like myvar = MyModel.objects.all().exclude(self.date_from=self.date_to) -
Adding instances with a one-to-many connection
I have objects: class Subscribe(models.Model): id=models.AutoField(primary_key=True) name=models.CharField(max_length=30,null=False); owner=models.ForeignKey(User,related_name='owner', null=False, blank=True, on_delete=models.PROTECT)# владелец подписки subscription = models.ManyToManyField(User,null=True,related_name='subscription') #те, на кого он пдписалса In this code I want to connect the objects of the user with the object article like in admin: https://stackoverflow.com/questions/ask# @login_required(login_url="/account/login") def sunscribe(request,id): user=User.objects.get(pk=id) #article author try: sunscribe1=Subscribe.objects.get(owner=request.user) except Subscribe.DoesNotExist: sunscribe1 = Subscribe(); But I have error: "" needs to have a value for field "id" before this many-to-many relationship can be used. But I have field id! -
mocking a QuerySet function
I am creating testcases for a Django project where I am retrieving a value from an instance of a model. For example, instanceDog = models.Dog() which leads to another model, Tail, and read by: instanceDog.tail.all()[0].value But in the unittest, I can't seem to mock up the all() function. Right now I have, @mock.patch('path.to.code.models.Dog.all') @mock.patch('path.to.code.models.Dog.objects.all') @mock.patch('path.to.code.models.Tail.all') @mock.patch('path.to.code.models.Tail.objects.all') and if set to mock_all, used mock_all.return_value = [models.Tail(value='value')] -
run a .py file in Django project via clicking a button in the admin
win7 python 2.7 Django 1.11 I have a Django project, in which I want to run a .py file via clicking a button in the admin interface. how to do it? -
How to save form by using Input type = "datetime-local" In Django
In my form i have an input field of ENDDATE AND TIME but when i select end date and time and i give submit the form was not valid. Here i have mentioned my html, views.py models.py and form.py. i don't why its happening so please help me to do this. HTML <label>End Date & Time</label> <div > <input class="form-control" id="party" type = "datetime-local" name="end_date"> </div> Views.py def event(request): if request.method == 'POST': form = EventForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, "Insertion Success!") return redirect('/event') else: messages.success(request,"You missed to fill some fields!") return HttpResponse(form) form.py class EventForm(forms.ModelForm): class Meta: model = Events fields = ['end_date'] widgets = { 'end_date': DateTimeInput(attrs={'type': 'datetime-local'}), } models.py class Events(models.Model): end_date =models.DateTimeField(auto_now=False,blank=True) -
Python/Django - Data does not appear from fetch request in template
I am new to python and am trying to pull data from an imported news api, however, even though I am getting no visible error it does not appear to be showing up in the template. I'm trying to a MVC framework to organize my code Starting with views.py from future import unicode_literals import json import logging import requests from django.http import HttpResponse from django.template import loader from django.shortcuts import redirect, render from django.urls import reverse_lazy from django.views import generic from newsapi import NewsApiClient from .forms import UserProfileCreationForm from .models import Animals def news_list(request): newsapi = NewsApiClient(api_key='123') all_articles = newsapi.get_everything( q='animals', sources='bbc-news,national-geographic, new-scientist, reddit-r-all', from_param='2018-09-29', to='2018-09-22', language='en', sort_by='relevancy')['articles'] context = {'articles': all_articles, 'type': str(type(all_articles)), 'name': 'Someone'} template = loader.get_template('home.html') return HttpResponse(template.render(context, request)) Then urls.py from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^$', views.news_list, name="news_list"), ] Here is also urls.py from the project folder, not sure if it is helpful or not from django.conf.urls import url, include from django.contrib import admin from django.views.generic.base import TemplateView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'), url(r'^users/', include('dangerzone.urls')), url(r'^users/', include('django.contrib.auth.urls')) ] And lastly the templates base.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> {% block title %} Python App … -
Django 2.1 link as field in DjangoAdmin List
I've read every question here regarding this issue but unfortunately none of them is working for me. My goal is to show custom column in Django Admin ModelAdmin as HTTP Link (<a> tag). admin.py def device_url(dev_id, dev_name): html = '/v1/admin/devices/device/{}/change/'.format(dev_id) return format_html('<a href="{0}">{1}</a>', html, dev_name) @admin.register(Machine) class MachineAdmin(admin.ModelAdmin): form = MachineForm list_display = ('name', 'location', 'devices', 'last_maintenance_log') inlines = [CommentInline, ] def devices(self, obj): devices_with_links = ', '.join([device_url(d.id, d.name) for d in obj.devices.all()]) if len(devices_with_links) > 1: return devices_with_links else: return '-' devices.allow_tags = True But it is still escaping those and showing it as plaintext. Devices is device_set from Machine model. 1 Machine : N Devices relationship. According to what I've read here, it should just work, even without the allow_tags=True when using format_html. Is this not working because I dont have format_html in the inner function devices? If not, does anybody has an idea how to solve this? -
Could not parse the remainder: '[1]' from 'form2[1]'
This is my index2.html I'm trying to display the area where I could input the second element's data of form2. form2 consists of fields from the database. <h1>Fill the form below</h1> <form method="post"> {% csrf_token %} <h1>Enter second area</h1> {{ form2[1] }}<br><br> <input type="submit" value="Submit file1"/> </form> Displaying the inputting fields for all the fields in the form2(refer below) is working good. <h1>Fill the form below</h1> <form method="post"> {% csrf_token %} {% for field in form2 %} {{field}}<br><br> {% endfor %} <input type="submit" value="Submit file1"/> </form> -
Exposing scripts to Django Rest API
I have a simple existing Django app that does a few REST calls to a third party tool to create some users. Now, I have been tasked to expose the existing django application to REST API calls from another platform. My question is, how do I pass parameters, sent in via RESST requests from the third party tool, to my existing application, so that those parameters can be used to drive the REST requests executed in my app to create/update users in another third party platform. I assume this is possible. Below isd part of the existing code: This is part of the views.py file: (I want to expose this views page as a REST API a user can call and pass the nessary info (server_name, user_name, password, site_url) to it so that it can be passed to the addUser function to drive the subsequent REST request def signIn(server_name, user_name, password, site_url, contentUrl): site_url = contentUrl[site_url] payload = { "credentials": { "name": user_name, "password": password, "site": { "contentUrl": site_url } } } headers = { "accept" : "application/json", "content-type" : "application/json" } signIn_req_url = "https://{server}/api/{api}/auth/signin".format(server=server_name, api=api) signIn_req = requests.post(signIn_req_url, json=payload, headers=headers, verify=False) response = json.loads(signIn_req.content) headers["X-tableau-auth"] = response["credentials"]["token"] site_id = … -
TemplateDoesNotExist at /update_product/4/
so my problem that when i click 'Edit' an error occurs telling me that the template 'mini_store/product_form.html' does not exist but i haven't include this template :( views.py class ProductUpdate(UpdateView): model = Product fields = '__all__' template = 'store/update_product.html' def get_success_url(self): return reverse_lazy('my_products', kwargs={'pk': self.object.pk}) url.py url(r'update_product/(?P<pk>[\w-]+)/$', views.ProductUpdate.as_view(), name='product_update') update_product.html <form method="post" action="" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-outline-success">update</button> url in my_products.html <a href="{% url 'product_update' pr.pk %}" class="btn btn-primary"> <i class="fa fa-pencil fa-fw"></i> edit </a> -
pass value from one class/function to another class/function
I have written two class one for posting datas for payment and other one to show payment-successful message iwth order_id. I am sending order id from first function and i want to catch this id to show in my payment-successful template. class ApiVIew(TemplateView): template_name = 'payment.html' def post(self,request): r = requests.post(url='www.randomsite.com',params = {'authToken':'12345','card_no':'1234','card_cvv':'****'}) return HttpResponse(json.dumps({'response':r.json(),'status':'ok'})) so response gives me a json() data {'isSuccess': 1, 'order_id': 1cq2,} so i want to get this oder_id and pass it to another function/class written below. def payment_successfullView(request): return render(request,'payment-successfull.html') How can i achieve so?Thanks in advance.