Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
HTTPS for localhost for Django development with stunnel
I'm working through the book "Django 2 by example". The second excercise creates a bookmarklet launcher, which loads some javascript from the local Django folder. Testing with a/the recent Firefox version (I'm using arch linux by the way), means that a HTTPS connection is required. For this I set up stunnel, however it doesn't seem to work fully: The bookmarklet loads correctly on the website that I'm developing, however on all other sites I'm getting Loading failed for the <script> with source “https://127.0.0.1:8443/static/js/bookmarklet.js?r=797695449745”. message in the FF web dev console. The book recommends ngrok, however I don't feel comfortable relying on a third party for these simple tests nor do I feel comfortable necessarily exposing my laptop to the whole web. Hence my efforts with stunnel. While I'm on the webpage I'm developing (https://127.0.0.1:8443/account/#), FF complains about the connection not being secure when checking where usually the green lock is, though the site loads. # dev_https pid= cert = stunnel/stunnel.pem key = stunnel/stunnel.key options=NO_SSLv3 foreground = yes output = stunnel.log debug = 7 output = stunnel.log [https] accept=127.0.0.1:8443 connect=127.0.0.1:8001 TIMEOUTclose=1 and started with stunnel dev_https. The Django development server is started with HTTPS=1 python manage.py runserver 8001 What changes can … -
How do I make this serializer display correctly?
Django is giving me this error. The solution I've tried does not seem to work. It is asking me to make this an instance of Medication...Am I not already doing that? I'm trying to have two serializers cat and medication under the one careLogSerializer. Is that even possible? How can I best solve this error? builtins.ValueError ValueError: Cannot assign "OrderedDict([('name', 'carelog3'), ('duration', 'short'), ('frequency', '4')])": "CareLog.medication" must be a "Medication" instance. Here is my serializer.... class CareLogSerializer(serializers.HyperlinkedModelSerializer): cat = CatSerializer() medication = MedicationSerializer() # cat = CatSerializer(read_only=True) this allows put BUT TURNS OFF POST class Meta: model = CareLog fields = ( 'cat', 'slug', 'foster_manager', 'weight_unit_measure', 'weight_before_food', 'food_unit_measure', 'amount_of_food_taken', 'food_type', 'weight_after_food', 'stimulated', 'medication', 'medication_dosage_given', 'medication_dosage_unit', 'notes', 'created', 'photo', ) extra_kwargs = { 'foster_manager': { 'read_only': True, 'required': False, 'lookup_field': 'id', }, 'medication': { 'read_only': True, 'required': False, 'lookup_field': 'slug', }, 'cat': { 'read_only': True, 'required': False, 'lookup_field': 'slug', }, } @staticmethod def create(validated_data): cat_data = validated_data.pop('cat') cat_obj = Cat.objects.get(**cat_data) return CareLog.objects.create(cat=cat_obj, **validated_data) @staticmethod def update(instance, validated_data): instance.weight_unit_measure = validated_data['weight_unit_measure'] instance.weight_before_food = validated_data['weight_before_food'] instance.food_unit_measure = validated_data['food_unit_measure'] instance.amount_of_food_taken = validated_data['amount_of_food_taken'] instance.food_type = validated_data['food_type'] instance.weight_after_food = validated_data['weight_after_food'] instance.stimulated = validated_data['stimulated'] instance.stimulation_type = validated_data['stimulation_type'] instance.notes = validated_data['notes'] instance.save() Here is my model class CareLog(models.Model): … -
Django : Add download link in email
I'm trying to add download link inside my email in order to download pdf files stored in media directory. I dont overcome to create this url link in my email content. This is my views.py with post function : def post(self, request, *args, **kwargs): form = self.form_class() document_choice = request.POST.getlist('DocumentChoice') if request.method == 'POST': form = self.form_class(request.POST) for checkbox in document_choice: document_edqm_id = Document.objects.get(id=checkbox).edqm_id email = request.POST['email'] plain = email + document_edqm_id + str(datetime.now()) token = hashlib.sha1(plain.encode('utf-8')).hexdigest() Download.objects.create(email=email, pub_id=checkbox, token=token) document_link = Document.objects.get(id=checkbox).upload print(document_link) context = {'document_link': document_link} if form.is_valid(): message = get_template('freepub/message.txt').render(context) html_message = get_template('freepub/message.html').render(context) subject = 'EDQM HelpDesk and Publications registration' mail = EmailMultiAlternatives(subject, message, 'freepub@tec.eu', [email]) mail.attach_alternative(html_message, "text/html") mail.send(fail_silently=False) print('Email envoyé à ' + email) else: print('form invalid') return HttpResponseRedirect(self.get_success_url()) And my message.txt and message.html file : #message.txt == This E-mail is automatically generated, please do not reply to it == Please find below your download link for the free EDQM publication: {{ document_link }} You can use this link as much as you like. It will expire in 0 days. Thank you for your interest in EDQM publications. and #message.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <p>== This E-mail is automatically generated, please … -
How to give user input dynamically in API?
I am making an API using Django.Since i am giving static type input and getting output in json format.how to give userinput dynamically. views.py from django.shortcuts import render,redirect from django.views.generic import TemplateView from .models import * from django.http import HttpResponse from django.views.generic.edit import FormView from .forms import TweetForm from django.views import View import json import pdb import tweepy from pprint import pprint import pickle consumer_key = 'VR95CmIMrv7q7vfDoPcjC8NZS' consumer_secret = 'YlWo6BzDnhXozSZnvnN1cIcjvRKrJFJVnYA9vvqMDocOdjyBNu' access_key = '1006840281361047553-JQPFugH9xVNifKRY1b4BjgpdTLiVND' access_secret = '5R3DXQmf6Xf3FwZHZzqSU3P3oYQAReUqwux9ttj5Gj7K5' def get_tweets(request): auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_key, access_secret) api = tweepy.API(auth) number_of_tweets=10 tweets = api.user_timeline("realdonaldtrump") tmp= [] for tweet in tweets: tmp.append({"text":tweet.text,"user":tweet.user.name,"retweet_count":tweet.retweet_count,"img":tweet.user.profile_image_url}) return HttpResponse(json.dumps(tmp)) urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'Tweet/$', views.get_tweets, name='Tweet'), ] that output is right but we can see tweets = api.user_timeline("realdonaldtrump") line in views.py static input.how to give it dynamically -
Retrieve function not mapped with ViewSet and SimpleRouter DRF
I am trying to create a simple entry point with a list and retrieve methods, for the list entrypoint works fine but when I try to retrieve a single object I get a Method Not Allowed error. I have tried to map methods to functions for with not avail (urls are not created). I am using DRF 3.3.1 This is an example of the code: class SomeModelSerializer(ModelSerializer): class Meta: model = SomeModel fields = [u'id', u'first_name', u'last_name'] class SomeModelViewSet(ListModelMixin, RetrieveModelMixin, viewsets.ViewSet): permission_classes = (SomePermission,) def list(self, request): data = SomeModelSerializer.data() return Response(serializer.data) def retrieve(self, request, *args, **kwargs): //some unreachable logic urls.py router = routers.SimpleRouter() router.register( r'somenedpoint', SomeModelViewSet, base_name=u'somename') urlpatterns = router.urls When I visit the someendpoint/1 or some id, I get the method get is not allowed I have tried adding SomeModelViewSet(actions={"get": "list", "get": retrieve}) but then urls are not created. Tried to add detail_route decorator to the retrieve method but neither changing the name to the method or using the same retrieve name works. The urls are created, I can see one url for lists and another for a detail but the method is not mapped. What am I missing? -
Multi Datepicker in Django
I'm quite new in Django. I can embed datepicker(single) to my website. However, I don't know how can I use multiple datepicker. I want to use multiple datepicker with database(as a list or something like that). How can I do this? -
Django: ImportError: No module named doc
here is the traceback System check identified 1 issue (0 silenced). September 10, 2018 - 13:01:31 Django version 1.8, using settings 'settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Traceback (most recent call last): File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/home/basha/UpgradeMloss/venv1.8/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 170, in __call__ self.load_middleware() File "/home/basha/UpgradeMloss/venv1.8/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 50, in load_middleware mw_class = import_string(middleware_path) File "/home/basha/UpgradeMloss/venv1.8/local/lib/python2.7/site-packages/django/utils/module_loading.py", line 26, in import_string module = import_module(module_path) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named doc and here is the installed libraries pip freeze: certifi==2018.8.24 chardet==3.0.4 Django==1.8 django-contrib-comments==1.5 django-markup-deprecated==0.0.3 django-recaptcha2==1.3.0 idna==2.7 Markdown==2.6.11 Pillow==5.2.0 pytz==2018.5 recaptcha-client==1.0.6 requests==2.19.1 urllib3==1.23 and here is also the INSTALLED_APPS: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'django_comments', 'django.contrib.syndication', 'django.contrib.flatpages', 'django.contrib.humanize', 'software', 'revision', 'registration', 'community', 'forshow', 'user', 'subscriptions2', 'aggregator', 'blog', 'captcha', 'snowpenguin.django.recaptcha2', 'markup_deprecated', ) I don't know exactly where is the problem or how can I resolve it. I've been searching about this ImportError but there is nothing talking about such an error.! -
Server Response 400 saying FIled is Required by Post reuqest using android
The Title being entered is Edit Text which using the id to get data The Response by server using debugger which stats the 400 response and also uses the getErrorStream() method to get the specific problem but still i am entering the data but response from server is that i need that specific field to enter data which is required by the database but others fields are not mandatory only the title field is. The Code of button Click Button submitButton = findViewById(R.id.uploaddata); submitButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { JSONObject postData = new JSONObject(); try { //Button image = (Button)findViewById(R.id.sendImage); postData.put("title", title.getText().toString()); postData.put("technology", platform.getText().toString()); postData.put("date", date.getText().toString()); postData.put("description", description.getText().toString()); //postData.put("image", image.getText().toString()); //postData.put("deviceID", deviceID.getText().toString()); if((title == null) ){ Toast.makeText(getApplicationContext(),"Please Enter Title",Toast.LENGTH_SHORT).show(); } else { new SendDeviceDetails().execute("http://url/data/details/", postData.toString()); } } catch (JSONException e) { e.printStackTrace(); } } }); -
apply form data from Django website to .exe file to generate link
I have built a Django website to accept user input form (an e-book application website). Upon application by the user, I could see their application on the backstage of the website and approve their application. I want to add a function: when I approve their application, the application form received from the web should be pass to an existing exe file automatically and generating a txt file in the server. At the same time, a link should be shown to the application history of the user so they could download the files generated by the exe. This website is only for several people. I have tried pythonanywhere but it's a linux server so I do not think exe file could be run in it. Are any other windows server, and how to add the exe files generating function to my Django project? -
Error during WebSocket handshake: Unexpected response code: 500 IBM cloud
I have problem witch webbsocket app on IBM Cloud (bluemix). I was prepared and deploy django channels app on ibm cloud without any error, but when i open page in browser i have websocket error: (index):202 WebSocket connection to 'wss://ibm.mybluemix.net/' failed: Error during WebSocket handshake: Unexpected response code: 500 I supose there is problem with HTTP serwer but i dont know how to check and fix that. -
Prevent test migrations from being run on a specific database
I have a Django application connectinig to 2 database. Both of them as seen by Django as PostgreSQL database but one of them is not a PostgreSQL (but uses the PostgreSQL binary protocol so it uses the same driver (CockroachDB). Currently it looks like during test runs, Django try to run the migration on both databases. How can I avoid that ? I still need the database to be accessible during the tests, but no to run the migration (As it's not compatible for now and the migrations are run outside from Django) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', ... }, 'livedb': { 'ENGINE': 'django.db.backends.postgresql', ... } } -
not getting any exceptions but data is not getting stored to database
I am new to ajax,getting issue with checkbox field, i tried get_list() of to access checkboxes field but not working. issue is with checkbox field. what change should i make to send request form ajax and access through view for checkbox fields. I tried in the following way javascript: function submitContactForm() { var token = '{{csrf_token}}'; var name = $('#inputName').val(); var sharewith = $("#sharewith").val() if (name.trim() == '') { alert('Please enter your name.'); $('#inputName').focus(); return false; }else{ $.ajax({ headers: { "X-CSRFToken": token }, type:'POST', url:'sharing', dataType:"json", traditional: true, data:'contactFrmSubmit=1&name='+name+'&sharewith'+sharewith, beforeSend: function () { $('.submitBtn').attr("disabled","disabled"); $('.modal-body').css('opacity', '.5'); }, success:function(msg) { if (msg == 'ok') { $('#inputName').val(''); $('.statusMsg').html('<span style="color:green;">sucessfully saved</p>'); } else { $('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>'); } $('.submitBtn').removeAttr("disabled"); $('.modal-body').css('opacity', ''); } }); } } views.py: def test(request): if request.method == "POST" and request.is_ajax() : if "name" in request.POST: name=request.POST["name"] sharewith=request.POST.getlist["sharewith"] instance=Test.objects.create(name=name) for user in sharewith: instance.add(user) instance.save() return HttpResponse(json.dumps({'msg': "ok"}), content_type="application/json") else: return render(request,template_name='registration/basetest.html') form: <div class="modal-body"> <p class="statusMsg"></p> <form role="form">{% csrf_token %} <div class="form-group"> <label for="inputName">knowledge category</label> <input type="text" class="form-control" id="inputName" placeholder="Enter your name"/> </div> <div class="form-check" id="sharewith"> <label for="sharewith">Share with</label></br> {% for sharewith in sharewithonly %} <input class="form-check-input position-static" type="checkbox" value="{{ sharewith.id }}"> <label>{{ sharewith.email }}</label></br> … -
get djcelery periodic task data inside the django app and keep the data in the entire application without store in file and db?
I am getting the polling data by running celery beat scheduler and periodic task. I like to share this data with the Django server. this data should available for the entire Django application server. is there anyway? and I don't want to share this data either DB or file. please suggest me to do this in a better way, thank you in advance. -
Filter related objects Django
Imagine such models in Django: class Organisation(Model): ... class Guest(Model): organisation = ForeignKey(Guest, CASCADE, 'guests') class Booking(Model): guest = ForeignKey(Guest, CASCADE, 'bookings') start_date = DateField() end_date = DateField() Using Django Rest Framework it is needed to perform a endpoint for all organisations to be listed all guests to be listed bookings to be filtered agains start_date and listed Sample of response: "Organizations": [ { ..., "Guests": [ { ..., "Bookings": [ {...}, {...} ] }, { ..., "Bookings": [ ] } ] }, { ..., "Guests": [ { ..., "Bookings": [ {...}, ] }, ] } ] So, as you can see, I need all Organisations and Guests to be present, not only those who have Bookings. What is the optimal way to perform that? Thank you! -
Django the time to fetch the data vs the over all time
I am facing poor performance in my django model it takes lots of time to execute the query and fetch the data the number of row is just 100 not more than that what i am missing can anyone experienced this before if so can you provide a solution to fix it up. 1)If you look on the tool we are able to see there are 5 queries being executed out which 3 queries are something different and in every service i am able to see this 3 queries as common.How to avoid it if I hope it will increase the performance as it takes nearly 50% of the overall time to execute the sql query. SELECT @@SQL_AUTO_IS_NULL SELECT VERSION() SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED 2)The total time taken by the sql query is 106ms where as the overall time to execute is 2160ms what are the other factors which is taking so much time to execute how to identify it and improved the performance. -
how to implement custom authorization in django?
I'm developing python web application using Django framework . could you please tell me how to implement custom authorization. -
Set-up (software, service providers, etc.) for a web tool
Hi stack overflow community I am working for a company and my task is to develop a web tool about energy storage technologies. The tool should: -allow the users to get information about a specific technology (parameters, applications, SWOT analysis,... so basically numbers and text, shown nicely (some of them in various plots) -allow the user to compare parameters of different technologies that share a specific category (e.g. application), also with plots. The tool should be interactive, meaning that users should be able to for example tick/ untick a technology to show/ hide it or they should be able to hover over an i sign and the tool shows them some info about a technology or parameter. They should also be able to hide some of the plots. E.g. If they want to compare batteries and Pumped Hydro Storage but they don't care about Global Warming Potential then they should be able to hide that plot. The issue is that I only have some basic coding knowledge (Python and other languages) but absolutely no experience in web development or anything that has to do with databases. Neither do I know anything about plotting tools or design issues. I am an … -
Adding additional fields in Django User Model - Only for logged in users
What's the best method to extend user models in Django? Only logged in users should be able to add the additional details. These fields won't be available during registration. Also, how can I create a public profile link of the users using this additional fields? The public profile should look like this http://website.com/username -
Django; How to update objects using InlineFormset?
I'm trying to update an object using InlineFormset and I tried some ways but never done well. Here is 'views.py'. @login_required def edit_entry(request, pk): entry = get_object_or_404(Entry, id=pk) if request.method != 'POST': form = EntryForm(instance=entry) formset = PhotoInlineFormset(instance=entry) else: form = EntryForm(instance=entry, data=request.POST) formset = PhotoInlineFormset(request.POST, request.FILES) if form.is_valid() and formset.is_valid(): edited_entry = form.save(commit=False) formset = PhotoInlineFormset(request.POST, request.FILES, instance=edited_entry) edited_entry.save() formset.save() return HttpResponseRedirect(reverse_lazy('users:my_entry')) context = { 'entry': entry, 'form': form, 'formset': formset, } return render(request, 'feeds/entry_form.html', context) and forms.py PhotoInlineFormset = inlineformset_factory( Entry, Photo, form=PhotoForm, extra=4, max_num=4, ) for this way, when I try to change something to the original object and save, an error is coming up on the form. It says (Hidden field entry) The inline value did not match the parent instance. How can I fix this and how am I wrong with this? -
Django Upload/Download File
I am new to django. In my project I need to add user forms to upload some files and download the uploaded files. Consider this as an online storage space. This needs to be handled by class based views so that expansion of the views will be easy. As of now I tried django-downloadview for objectdownloadview https://django-downloadview.readthedocs.io/en/1.9/views/object.html This works quite fine with the example. But I am not able to expand it for class based views for my project. More over example is with slug I tried changing it to PK but its throwing errors. Can someone please help me here Or share a working example of simple 1 page django file upload and download stuff. Regards, Jaiswal -
Django try/except on DoesNotExist still throws it
I'm struggling with a DoesNotExist error on my application. The point is that I don't really understand why this error is thrown as I already handle it: import socket from django.core.exceptions import ObjectDoesNotExist from django.db import Models class MyClass(models.Model): name = models.CharField(max_length=250, default=socket.gethostname(), unique=True) @staticmethod update_some_list(some_list): for some_item in some_list: try: MyClass.objects.get(name=some_item) except ObjectDoesNotExist: # I also tried with MyClass.DoesNotExist MyClass.objects.create(name=some_item) The point here is that, when I run into this code, I have some "module-level" DoesNotExist that is thrown away, as if this try/except block is never hit: Traceback (most recent call last): File "/app/backend/shared/models.py", line 201, in update_some_list MyClass.objects.get(name=some_item) File "/usr/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/lib/python3.6/site-packages/django/db/models/query.py", line 399, in get self.model._meta.object_name shared.models.DoesNotExist: MyClass matching query does not exist. -
Change user used to access database connected to django website in runtime
Currently I implemented a login routine for the website I am working on, according to This Tutorial. Also I am not authenticating the user with djangos own system, because I am using authentication against the LDAP of my company (django-auth-ldap). Currently I am using a general user to login to the database, which has universal access to all data, which also gives full access to any user logging in to the website. To avoid that I would like to know how I can connect to the database as the individual user, who just logged in to the website. Thanks in advance and sorry for bad english -
Django Checkbox value. handling list value. comparing it to filter for values
I was working on Django. I am trying to read a checkbox(different table) qualification_degree = request.POST.getlist('degree[]'), I saved this in the database. After this value, I have to compare to a student list and filter only students having a degree in the mentioned checkbox item. student = Student.objects.get(major=qualification_degree). But since this returns a list item, I am unable to compare. I tried reading each degree in the list and compare, something like this for degree in qualification_degree: #was unable to handle this part Resulted in unable to iterate, some other error. -
How to configure django-cors-headers and geoserver
I would like to understand how to enable cors I followed some examples but still cannot figure it out how to configure it. I have built a mapp using Geoserver wms layers and I have added a function to open attributes for a certain entity. I have installed cors plugin on chrome but I have to switch it off. So I installed django-cors-headers so this is how my settings.py looks like now: But it is still not working. Also is it possible that other LAN computers can see my app if I run it on the server without having to install Apache Tomcat? settings.py """ Django settings for geodjango project. Generated by 'django-admin startproject' using Django 2.0.6. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'x%eegc6h@9z6yautlozipqumn*9zoruvatk6mox3+%f_c8uyie' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ … -
Model Inheritance or Foreign Key?
I'm sure there are probably several ways to do what I am achieving, but have run into some problems. I have a "Member" model and I'm also trying to add a "Dependent" model that inherits some fields and data from the parent (Member) but also has some of the same fields, but their own data. What would be the best way to achieve this? ForeignKey, OneToOne, or ManyToMany, or is it even possible? Example: class Member(models.Model): name = models.CharField(max_length=128) address = models.CharField(max_length=128) age = models.DateField() class Dependent(models.Model): name = models.CharField(max_length=128) (different name) address = models.CharField(max_length=128) (same address as Member) age = models.DateField() (different age) Thank you for your help.