Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What happens when server request files exceed memory size?
I'm trying to figure out what happens when files of varying sizes are uploaded to the server at the same time and their collective size exceeds that of the memory. More specifically, what does Django do then? Does virtual memory come into play or are the files moved to disk? According to Django documentation, you can specify the FILE_UPLOAD_MAX_MEMORY_SIZE value which decides whether the temp file remains in memory or goes to disk. If I set this value to, say, 50 GB, and I send one or more files at the same time to the server, AND my RAM is only 16 GB, what happens then? I'm asking this question because I need to encrypt the files I receive at the server without saving them flat anywhere in the disk, even as a temporary file, due to sensitivity of the data. I want to make sure that under no circumstance the file(s) will be moved from the (volatile) memory to (secondary) disk storage in its original form. -
Can anyone help in Django image modal display in web template?
I'm pretty new to Django Framework for web designing. In my web project, I have a template which contains a table coming from Oracle database and it is designed by django-tables2. In this table, I'm having a column which is linked to local images stored on my local machine. When user clicks the link in the table, an image is displaying on the same tab. Now my question is can I display this image in a separate popup window or in new tab or in modal dialog box instead of displaying it in same tab? I have referred online for this but in most cases results are for Form modal and not for media files and I could not figure it out that how those would be implemented in my case. Please, can anyone help me in this? I'm using Django-Bootstrap for overall UI design, django-tables2 for table design, django-material for form design, Oracle database 11g, Python3.6 and Django 11.1. Thanks in advance... -
How to secure web services when authentication is done at client side (frontend)
I have web application which structure is as- webapi : django web services [NOT REST] no security implemented frontend : Angular2. authentication implemented via SAML Database : Mongodb Can you please suggest best way to secure webapi, as currently anyone can access web services who has server[api] url It will be big help if you suggest the authentication and authorization flow because I am totally stuck. Thanks in advance. -
:: acting as delimiter in my csv file and spliting data
I have a django template where I have stored some tables and have written a function to export it to csv but when i am doing it some columns in my table have :: in them and csv is treating it as a delimiter and splitting the column there how can i prevent this from happening my views.py f = open("static/output.csv", "w") f.write("Customer Name" + "," + "Status" + "," + "Product" + "," + "Operating System" + "," +"Server_Type" + "," + "Version"+"," +"Citrux_URL"+"," +"F5_URL"+","+"\n") for c in custom: f.write(c.summarise()+"\n") my models.py def summarise(self): s = ",".join([str(self.name), str(self.Status), str(self.Product),str(self.SSO),str(self.SSO_URL),str(self.JCES_URL),str(self.L3),str(self.PM))]) return s -
ImportError: No module named 'mysite' from omv of pi3
I want to work with Apache 2 and Django 2.0. So I modified /etc/apache2/sites-sites-available/000-default.conf and /home/duen/django/mysite/wsgi.py. python = 3.4.2 django = 2.0 apache = 2.4.10 device = raspbarry pi 3 model B os = OpenMediaVault 3.0.88 000-default.conf <VirtualHost *: 80> ServerAdmin sin12070@gmail.com DocumentRoot / var / www / html ErrorLog $ {APACHE_LOG_DIR} /error.log CustomLog $ {APACHE_LOG_DIR} /access.log combined WSGIDaemonProcess mysite python-path = / home / duen / django / mysite: /home/duen/django/venv/lib/python3.4/site-packages WSGIScriptAlias / /home/duen/django/mysite/wsgi.py <Directory / home / duen / django / mysite> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> wsgi.py import os import sys sys.path.append ('/ hoem / duen / django') sys.path.append ('/ hoem / duen / django / mysite') sys.path.append ('/ home / duen / django / venv / lib / python3.4 / site-packages') from django.core.wsgi import get_wsgi_application os.environ.setdefault ("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application () However, when I accessed the web page, I could see this error in error.log. error.log mod_wsgi (pid=9040): Exception occurred processing WSGI script '/home/duen/django/mysite/wsgi.py'. Traceback (most recent call last) File "/home/duen/django/mysite/wsgi.py", line 20, in <module> application = get_wsgi_application() File "/usr/local/lib/python3.4/dist-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/usr/local/lib/python3.4/dist-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/local/lib/python3.4/dist-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/local/lib/python3.4/dist-packages/django/conf/__init__.py", line … -
Upload_to with name of objects
I have a question I think it's easy to your guys about upload_to in Django but it's difficult to me. Hope your helps! # Upload_to Def from datetime import datetime def avatar_country_path(instance, filename): ext = filename.split('.')[-1] filename = '%s' % (instance.id) datetime_str = datetime.now().strftime("%Y%m%d%H%M%S") return "geo/country/%s/%s_avatar.%s" %(filename, datetime_str, ext) def cover_country_path(instance, filename): ext = filename.split('.')[-1] filename = '%s' % (instance.id) datetime_str = datetime.now().strftime("%Y%m%d%H%M%S") return "geo/country/%s/%s_cover.%s" %(filename, datetime_str, ext) def flag_country_path(instance, filename): ext = filename.split('.')[-1] filename = '%s' % (instance.id) datetime_str = datetime.now().strftime("%Y%m%d%H%M%S") return "geo/country/%s/%s_flag.%s" %(filename, datetime_str, ext) class BaseCountry(Place, SlugModel): # More avatar = models.ImageField(max_length=1024, upload_to=avatar_country_path, blank=True) cover = models.ImageField(max_length=1024, upload_to=cover_country_path, blank=True) flag = models.ImageField(max_length=1024, upload_to=flag_country_path, blank=True As you see, I need 3 Defs to make upload_to with a similar Path, just different in NAME OF FIELDS (avatar, cover, flag) but I dont know how to shorten it. Could you guys help me? -
Updating point total on User model via signals and save() method django
I want to assign points to a User via another model (UserPoints). I know that I need to use the save() method to save the points to the correct User. And I also know that I need to use a signal to notify the User model to save the points there. However, the code I wrote generates this error: 'User' object has no attribute 'userpoints_set' Can someone please tell me what I am doing wrong? Why am I getting that error? And how do I fix it? The goal is to store the points in one model and then update the point total on the User model. Thanks in advance! models import datetime from django.contrib.auth.models import AbstractUser from django.core.urlresolvers import reverse from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.db.models import Sum from django.db.models.signals import post_save from django.dispatch import receiver from points.models import PointValue @python_2_unicode_compatible class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = models.CharField(_('Name of User'), blank=True, max_length=255) image = models.ImageField(upload_to='user/%Y/%m/%d', default='') point_total = models.IntegerField(default=1) def __str__(self): return self.username def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username}) @python_2_unicode_compatible class UserPoints(models.Model): … -
django forms multiple form with one field same by default
I have a list of links,(A,B,C,D,) each link opens the same pop up form with fields (name , email, region, service) all the inputs except SERVICE is user input. I want the service field to have a default name of the links. EXAMPLE: LINK A ---FORM------- NAME= ......... EMAIL=........ REGION=........ SERVICE=FORM A =========================== LINK B ---FORM------- NAME= ......... EMAIL=........ REGION=........ SERVICE=FORM B ==================================== I want the service field to have that default value. how can I achieve that in Django?????? -
Save avatar from facebook in allauth
There are questions here which answer this, but my case is different. Instead of letting allauth create a new user I'm catching wheter or not the email exists and performing a login using user = User.objects.get(email=email) sociallogin.connect(request, user) social_account_added.send( sender=SocialLogin, request=request, sociallogin=sociallogin, ) But, I can't set the avatar here due to the way my conditions are setup and this may never be hit. The alternative is in get_redirect_url from what I see, but this isn't called if I use sociallogin.get_redirect_url so it seems theres opportunity for both to be skipped. There's a signal user_logged_in = Signal(providing_args=["request", "user"]) under account app in allauth but what if they have multiple socials connected? How would I determine the proper avatar to get... -
Walrus is not indexing the words properly
In my Django project, I am using walrus to cache location names. eg: New Zealand, New York City, Newcastle e.t.c So, when I am searching for a key 'new', I am expecting it to return all the above locations but it is only giving me New Zealand. But I when I use 'n' or 'ne' as a key I am getting all of these. I tried changing the stopwords_file to a blank file on initializing the walrus autocomplete. Any help is appreciated. -
change button based on previously "liked" status by usr django
I am new to Django and am trying to create a favorite application. I would like to have the liked button change based on whether or not the user has already favorited the physician. I pass physicians and liked list to my template but not sure what to do next to extract liked from the array, and not sure if this the most elegant way to approach this. Any help would be much appreciated! models.py class Physician(models.Model): speciality = models.CharField(null=False, blank=False, max_length=30) first_name = models.CharField(null=False, blank=False, max_length=50) last_name = models.CharField(null=False, blank=False, max_length=50) title = models.CharField(null=False, blank=False, max_length=2) address1 = models.CharField(null=False, blank=True, max_length=50) address2 = models.CharField(null=True, blank=True, max_length=20) city = models.CharField(null=False, blank=False, max_length=50) state = models.CharField(null=False, blank=False, max_length=2) zip = models.CharField(null=False, blank=False, max_length=12) likes = models.IntegerField(default=1) def __str__(self): template = '{0.last_name} {0.first_name} {0.speciality}' return template.format(self) class Voter(models.Model): user = models.ForeignKey(User) physician = models.ForeignKey(Physician) My template is {% if physicians %} {% for physician in physicians %} <tr> <td> <a href="/getmd/{{physician.id}}/"> {{ physician.last_name }}, {{ physician.first_name }} </a> </td> <td>{{ physician.state }}</td> <td>{{ physician.speciality }}</td> <td>{{ physician.id}}</td> <td><strong id="like_count{{physician.id}}">{{ physician.likes }}</strong> </td> <td> {% if user.is_authenticated %} {% if likedalready.physician].liked %} <button id="alreadyvoted" data-catid="{{physician.id}}" class="likes btn btn-secondary" type="button" title="Already faved"> <span class="glyphicon … -
Sending data stream from python program to web app
I have a python program appending lines to a .csv file every few seconds. I also have a web app that was created using Django. My goal is to continuously read the data from the python program as it runs and display it on the website without having to refresh. My proposed solution is to send the python output to a server using requests.put(), and then read from the server using AJAX. 1.) Is this the best solution, or is there a better manner to connect the program and the site. 2.) If this is a good solution, what's the easiest way to get a server running to POST, PUT, and GET from? It can be local and will never expect heavy traffic. Thank you! -
Proper way to share temporary data between two users
Here is my case in django,i need to create a match between two users, users take turn, after one of them has finished, i need to send user1 score to user2 and vise versa. How can i create a match between two players? How do i store their data(scores) in a way that can be accessed for both users. Here is what i've tried : user1 sends GET request to get a user2 as a opponent by getting user2 id (i can say i made a match there), then after user1 finished he make another GET request with hes id and score to django. and here is where i stuck : I don't know how to send user1 score to user2. I don't know how to store the data so both users can access each other score. I'm quite new to django, so i did all that based on my basic knowledge of the framework, please correct me if i'm wrong and possibly suggest a better approach. -
TypeError: 'question_text' is an invalid keyword argument for this function in django 2.0 tutorial
I am fairly new to django and I am trying to follow the tutorial ( https://docs.djangoproject.com/en/2.0/intro/tutorial02/ ) but have encountered the above error. Here is my code for the models.py import datetime from django.db import models from django.utils import timezone # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200), pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE), choice_text = models.CharField(max_length=200), votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Also the question text and choice text is not appearing on the django-admin page enter image description here -
Youtube uploads
I am using Django/Python to create a project that allows users to automatically upload their youtube videos to my site. Is there a way to do this? Would using python-social-auth be the solution? Please advise. Many thanks! -
Django's sitemap framework giving error when using aggregate max function on lastmod
I'm trying to use Django's sitemap framework feature. I've implemented the code and it works with current article objects post_date. However I'm trying to get a more accurate last modification date using the following code and it gives me error. Traceback of error http://dpaste.com/3Z04VH8 Regards. Thanks for any help from django.contrib.sitemaps import Sitemap from django.db.models import Max from article.models import Article class ArticleSitemap(Sitemap): changefreq = 'hourly' priority = 0.5 def items(self): return Article.objects.all() def lastmod(self, obj): from post.models import Post return Post.objects.filter(article=obj).aggregate(Max('post_date')) #return obj.post_date -
Django arranging model foreign key attributes after delete()
I have a model like so: class RepairOrder(models.Model): user = models.ForeignKey(User) ro_number = models.IntegerField(validators=[MaxValueValidator(999999999999)]) service_writer = models.ForeignKey(ServiceWriter, null=True, blank=True) RO_STATUS_CHOICES = ( ('P', 'Pending'), ('O', 'Open'), ('C', 'Closed') ) ro_status = models.CharField(max_length=10, blank=False, choices=RO_STATUS_CHOICES) open_date = models.DateTimeField() closed_date = models.DateTimeField(null=True, blank=True) mileage = models.IntegerField(blank=False, validators=[MaxValueValidator(999999999999)]) line_number_1 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL, related_name='line_number_1') line_number_2 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL, related_name='line_number_2') line_number_3 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL, related_name='line_number_3') line_number_4 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL , related_name='line_number_4') line_number_5 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL, related_name='line_number_5') line_number_6 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL, related_name='line_number_6') line_number_7 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL, related_name='line_number_7') line_number_8 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL, related_name='line_number_8') line_number_9 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL, related_name='line_number_9') line_number_10 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL, related_name='line_number_10') vehicle = models.ForeignKey(Vehicle, blank=False, related_name='vehicle') def __str__(self): return str(self.ro_number) Some of these objects might have line_number_(1 through 5) assigned to a JobLine object and the remaining set as Null. Other RepairOrder objects may only have line_number_(1 through 3) assigned to a JobLine object while the remaining are set as Null. But during the creation of a RepairOrder object the line_number_(x) attributes are always assigned in ascending order starting from 1. Here is what I am trying to accomplish: Lets assume I have a RepairOrder … -
nginx redirect with authorization header
I configured django together with nginx. Static files get served directly using nginx. It's all working fine, but the problem is, now I need to proxy a download from another source. The other source requires authentication, at the moment I am using Django's StreamingHttpResponse, but I want to somehow directly serve it using nginx. I know it's possible to set the authorization header in nginx using proxy_set_header, but the problem is that the authorization header is different for every user. Would it work if I just (from django) return a redirect and modify the authorization header of the request object? Does nginx have a solution for such exotic cases? Do I need to write a module to make it work, or does it even make sense to write a module because maybe it's completely the wrong way of doing it? Thanks in avance. -
Sending a csv file via curl POST to Django REST Framework endpoint
I have a csv file that I want to send via curl to a Django Rest Framework API View I have developed. The csv file itself contains only foo,bar and this is the curl command I'm using: curl URL -H 'Accept: application/json' -H 'Referer: http://localhost:5011/ost:5011' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36' -H 'Authorization: JWT TOKEN -H 'Content-Type: multipart/form-data' -F upload=@testcsv.csv When it hits my API View in Django, and I run request.data.get('file').read() the output is some metadata around the file and not the file contents itself: (Pdb) b'--------------------------001ec735bfc1a929\r\nContent- Disposition: form-data; name="upload"; filename="testcsv.csv"\r\nContent-Type: application/octet- stream\r\n\r\n\r\n--------------------------001ec735bfc1a929--\r\n' How can I access the actual file itself through this method? My APIview is using class FileUploadView(APIView): parser_classes = (MultiPartParser,) Thanks! -
Django Timezone Awareness - Data to be stored in UTC
This is my first time developing a timezone aware web app. I'm using Django 1.11.7. I have looked through many posts regarding timezones and honestly, I'm starting to feel like I just don't understand the concept of timezones... 0_o I'm making a booking app with start_time and end_time for each reservations. I expect the user to be able to enter dates and times as he experiences them in his timezone. On the otherhand, I want these dates and times stored in a postgresql database in UTC format. My Timezone VS UTC If I was choosing to reserve, for example, between Noon and 2pm (today), the result in the database should show between 5pm and 7pm (today). Right? Django Internationalization settings: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_TZ = True USE_L10N = True USE_I18N = True During database creation: start_time TIMESTAMP WITH TIME ZONE NOT NULL, end_time TIMESTAMP WITH TIME ZONE NOT NULL Using Django's built in admin page feature, I enter the following information: admin page form But when I look up the results in the database, here's what I get: 2017-12-05 19:00:00-05 | 2017-12-05 20:59:59-05 The stored result changed in the opposite direction of what I was expecting. I … -
Why there is another post request after submiting a form in Django?
I am using Django to create a form where users will have to enter their email to get notified in the future. The problem is after successfuly submiting the form I get a post call, that refreshes the page that the form is in: [07/Dec/2017 01:22:41] "POST /notify-email/add/ HTTP/1.1" 200 21 [07/Dec/2017 01:22:42] "POST / HTTP/1.1" 200 23030 Below is the relevant code: views.py def add_notify_email(request): if request.method == "POST": form = NotifyEmailForm(request.POST) if form.is_valid(): form.save(commit=True) return JsonResponse({"status": "success"}) else: return JsonResponse({"status": "error"}) else: form = NotifyEmailForm() return render(request, "landing/home.html", {"form": form}) html <form class="form" onsubmit="addNotifyEmailInHero()" method="POST" id="notify_email_form_in_hero"> {% csrf_token %} <div class="form-group row"> <div class="col-sm-10 input-group" id="email_input_in_hero"> <div class="input-group-addon" id="coming_soon_email_icon_in_hero"><i class="fa fa-envelope fa fa-2x" aria-hidden="true" id="email_icon_in_hero"></i></div> <input class="form-control" type="email" name="email" onkeypress="if(event.keyCode === 13){addNotifyEmailInHero()}" placeholder="If you want to get notified when we go live, please enter your email...." maxlength="255" required id="id_email"/> </div> <div class="col-sm-2" id="notify_email_button_in_hero"> <button type="submit" class="btn btn-block btn-primary" id="submit_notify_email_in_hero"><i class="fa fa-bell nav-icon" aria-hidden="true"></i>Notify Me</button> </div> </div> </form> <script src="coming_soon.js"></script> coming_soon.js function addNotifyEmailInHero(e){ var notifyEmailForm = $("#notify_email_form_in_hero"); var thanksModal = $("#thanks"); $.ajax({ type: 'POST', url: '/notify-email/add/', data: notifyEmailForm.serialize(), success: function(res){ alert(res.status); if(res.status === "success") { thanksModal.modal('show'); } else {$("#id_email").val(""); $("#id_email").attr("placeholder", "Please Enter A Valid Email Address"); } } })} -
Sum averages over date ranges in Django
I'm trying to construct a query in Django that sums averages that were taken (i.e. averaged) over a range of times. Here is the relevant Django model: class Data(models.Model): class Meta: verbose_name_plural = "Data" site = models.ForeignKey(Site) created_on = models.DateTimeField(auto_created=True) reported_on = models.DateTimeField(null=True, blank=True) baseline_power_kw = models.FloatField('Baseline Power (kw)', blank=True, null=True) measured_power_kw = models.FloatField('Measured Power (kw)', blank=True, null=True) In my query, I'm trying to average sites' data over a range of times, and then sum those averages for each range of time. Here is the query I have so far, which I believe just gets the average of all sites' data over a range of times. t_data = Data.objects.filter(site__in=sites) \ .filter(created_on__range=(start, end)) \ .extra(select={'date_slice': "trunc(extract(epoch from created_on) / '60' )"}) \ .values('date_slice') \ .annotate(avg_baseline_power_kw=Avg('baseline_power_kw'), avg_measured_power_kw=Avg('measured_power_kw'), time=Min('created_on')) \ .order_by('-created_on') Do you know how I can proceed? I am using Django with Postgres. Thanks! -
Update django model from background task
I am trying to update a django model from a task using django-background-tasks. Here's what I've got: @background(schedule=0) def difficult_work(): for i in range(0,100): time.sleep(1) with transaction.atomic(): workProgress = WorkProgress.objects.filter(id="fixed_work_id_for_testing").select_for_update().get() print("updating work progress to " + str(i)) workProgress.progress = i workProgress.currentJobInfo = "test work" # if we've finished then make sure to set the status if i == 100: workProgress.status = "success" transfer.save(force_update=True) Additionally, I have an API view to get the progress of a work task. class WorkDetail(APIView): def get(self, request, workId, format=None): with transaction.atomic(): work = Work.objects.filter(id=workId).select_for_update().get() data = WorkSerializer(transfer).data return Response(data) The problem is, I'm not seeing any updates to the database while executing a task. I've got python manage.py dbshell running, monitoring the database tables and they aren't updating as the task progresses. I'm making sure to run python manage.py process_tasks, and it's outputting the correct print statements, indicating progress, but the database doesn't update until the task exits. How do I make sure the table is updated while the task is running? -
Trying to prevent multiple form entries with identical field data (only allow first user to take timeslot)
I am trying to have users enter data in a django form and only allow ONE entry into the database per each time slot and day slot. Example: User fills out form to "sign up" to speak during 8:00am - 9:00am on Day 1 for schedule id 2. If a database entry already exists with the same TIMESLOT and DAYSLOT, I want to raise an error and prevent entry. Here is what I have so far, but the filter is spanning across the entire table rather than just filtering per schedule ID... models.py from django.db import models import datetime class Schedule(models.Model): title = models.CharField(max_length=250) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title class Agenda(models.Model): dayChoice = ( ('d1', "Day 1"), ('d2', "Day 2"), ('d3', "Day 3"), ('d4', "Day 4") ) fullName = models.CharField(max_length=250) startTime = models.TimeField(auto_now=False, blank=True, null=True) endTime = models.TimeField(auto_now=False, blank=True, null=True) approved = models.BooleanField(blank=True) daySlot = models.CharField(max_length=2, choices=dayChoice) sub_date = models.DateTimeField(auto_now=True) scheduler = models.ForeignKey(Schedule, on_delete=models.CASCADE) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.fullName views.py from django.shortcuts import render, redirect from django.utils import timezone from django.shortcuts import render, get_object_or_404 from .models import Schedule, Agenda from .forms import AgendaForm # Create your views here. def schedule_list(request): … -
Django filter icontains - find matches going the other way
In the code below, Django's icontains filter finds matches where the user_input is contained within the name. How do I find matches where the name is contained within the user_input? names = "Jim", "Bob", "James" user_input = "Jimbo" Names.objects.filter(names__icontains=user_input) #returns empty queryset Names.objects.filter(???=user_input) #returns queryset with "Jim"