Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django translations not working?
I want to translate my website to other language , i've configured my settings.py as it should be but no changes are happens. I've create messages and i can see them inside my local folder, also i've compiled them successfully without any erors. Here is my settings : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # My apps 'main', # Third part apps 'captcha', 'jsonify' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) LOCAL_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) LANGUAGE_CODE = 'en' LANGUAGES = ( ('ru', _(u'RU')), ('en', _(u'EN')) ) My views: from django.utils.translation import gettext as _ def main(request): context = { 'title':_('Главная'), } return render(request, 'index.html', context) Also i've loaded the i18n above inside my template where the translations happens index.html: {% load static %} {% load i18n %} <title>{% block head_title %}{{title}}{% endblock %}</title> -
Unable to cv2.imwrite in django static folder from django views
Unable to save the image in static but can save in the same rekognition directory In views.py cap = cv2.VideoCapture(0) ret, img = cap.read() # Read the image from webcam cv2.imwrite('static/video_snapshot.jpg', img) -
Django Inlineformset: Loop through values of foreign key field
I am currently playing with inlineformset. I am lost if it's possible to loop through the value of a foreign key field in the form. for g_form in gradeupdate_form: form.fields['recipient'].queryset = SubjectGrade.objects.filter(recipient__id=self.kwargs.get('pk'), status='approved') This will return all subjects and final grade of pk via a drop down menu. Is it possible to loop these value in a table? Also I have 5 moldels which are all connected via Foreign Key. I am just wondering what's the best approach for this through inlineformset? -
Django serializer request JSON value
used django 2.0.2 MAC OS 10.13 views.py from rest_framework import viewsets from .serializers import RegisterSerializer from rest_framework.response import Response import json class RegisterViewSet(viewsets.ModelViewSet): queryset = '' serializer_class = RegisterSerializer def create(self,request, *args, **kwargs): print(json.loads(request.body)) serializer_class = RegisterSerializer(json.loads(request.body)) return Response(serializer_class) serializers.py from rest_framework import serializers from .models import register import uuid class RegisterSerializer(serializers.Serializer): UserEmail = serializers.EmailField(allow_blank=True,default=uuid.uuid4()) UserPassword = serializers.CharField(allow_blank=True,default=uuid.uuid4()) UserSex = serializers.IntegerField(default=0) UserAge = serializers.IntegerField(default=0) DeviceId = serializers.CharField(allow_blank=True,default=uuid.uuid4()) PushKey = serializers.CharField(allow_blank=True,default=uuid.uuid4()) OS = serializers.IntegerField(default=0) OSVersion = serializers.CharField(allow_blank=True,default=0) def create(self,validated_date): return True api test.html enter image description here i input this value succese print(json.loads(request.body)) how to use this value at serializer after raise this exception You passed a Serializer instance as data, but probably meant to pass serialized `.data` or `.error`. representation. -
How to prevent brute force attack in Django Rest + Using Django Rest Throttling
Block particular user for some specific time to using Django REST Throttling. I have seen Django REST Throttling. -
Django run windows command prompt
How i can show/run windows command prompt using django ? in my view. def run(request): cmd = '__batch.cmd Server.Tester.exe Config.xml' exitcode = str(subprocess.call(cmd, shell=False)) return render(request, "testy/lista.html", {"exitcode": exitcode}) i use subprocess.call but output see in pycharm terminal not in windows command prompt. Can someone help me ? -
How to prepare django migrations?
Migrating data in django involves two steps: python manage.py makemigrations python manage.py migrate The first step prepares the migrations which, as far as I know, are database specific; that is, depending on what database backend you are going to use, you will get different migrations. If in development I use sqlite, and in production postgres, does that mean that the migrations that I prepare in development will not work for the production machine? -
CSRF verification failed. Request aborted Angular 5 and Django
Getting an error while posting data in json from Angular 5 Frontend to Django Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. Django log Forbidden (CSRF token missing or incorrect.): /survey/creatDatabaseTable [20/Apr/2018 06:33:18] "POST /survey/creatDatabaseTable HTTP/1.1" 403 2513 Some of the solutions say you have to include a {% csrf_token %} tag in the frontend code and so how can I implement that in my angular5 code -
How to use a list inside values_list() in django?
I am new to python and django.I am having a list obtained dynamically containing database table fieldnames. How do I use this list within values_list() in django queryset while fetching results from database? fieldList=['field1','field2'] #list containing table fields obj=sampletable.objects.filter(somecondition).values_list(fieldlist) #--->want like this I came to know that we can't use lists simply as it is inside values_list().So I converted it into a string like this and then tried it but in vain. fieldListstr=','.join(repr(e) for e in fieldList) This is the error which I got Cannot resolve keyword "'field1','field2'" into field. Choices are: field1, field2 Please help me with your solutions. And thanks in advance -
Regarding GIL in python
I know GIL blocks python from running its threads across cores. If it does so, why python is being used in webservers, how are the companies like youtube, instagram handling it. PS: I know alternatives like multiprocessing can solve it. But it would be great if anyone can post it with a scenario that was handled by them. -
Using json.Encoder in django
i have done following things def handle_json(obj): # i want to make sure control goes here print(obj) return obj def test_json(): data= {datetime.date(2018, 12, 1): 160000.0, datetime.date(2019, 2, 1): 240000.0, datetime.date(2020, 9, 1): 1360000.0, datetime.date(2019, 3, 1): 280000.0} print(json.dumps(data, default=handle_json)) When i run test_json(), why i am not getting print() from handle_json() on console? -
how to read the request.payload contents in django?
I want to make some decision based on the contents of request.payload- XPKHmxbGVRRE9kUz5K6MtwL15NDedDHDb9IcTohZH7Vnrd0k5D4I0zjD4YR6yjhb ------WebKitFormBoundaryVL2R7CYuDDjkPX51 Content-Disposition: form-data; name="filename"; filename="abc.pdf" Content-Type: application/pdf Basically want to read if filename exists in this? How can I do this? if "filenanme" in request.POST seems incorrect. -
Django Cannot Resolve Related Model
I just added a new model called "Purchaser" into an app called "standard". I run the makemigrations and everything is hunky dory and then I try to run migrate and I get the following error: Running migrations: Applying tracking.0002_auto_20180418_1909...Traceback (most recent call last): File "manage.py", line 21, in <module> execute_from_command_line(sys.argv) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle fake_initial=fake_initial, File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\django\db\migrations\migration.py", line 122, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\django\db\migrations\operations\fields.py", line 216, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\django\db\backends\base\schema.py", line 481, in alter_field new_db_params = new_field.db_parameters(connection=self.connection) File "C:\Program Files (x86)\Microsoft … -
Using string as literal expression in function argument in Python
Let's say I have a function that can take various kinds of parameter values, but I don't want to (as a constraint) pass arguments explicitly. Instead, I want to pass them as a string.: def func(param) return param+param a = 'param=4' func(<do something to a>(a)) >>8 Is this possible in python? I want to use this idea in Django to create Query filters based on GET parameters in a dictionary and then just chain them using their keys. lookup_dic = {'user': 'author=user', 'draft': 'Q(publish_date_lte=timezone.now())| Q(publish_date_isnull=True)'} Based on whether the user and draft keywords are passed in the GET parameters, this would be read out like: queryset.objects.filter(author=user).filter(Q(publish_date_lte=timezone.now())| Q(publish_date_isnull=True)) I understand that I can do this by replacing the author=user by Q(author__name=user), but I wanted to know if this string comprehension feature is implemented in python in general? -
Want to use MongoDB instead of SQLite in django 2.0.4
I am having trouble in setting up the mongodb database for my django project. I am using mongoengine for this purpose. Cannot configure the settings file. Please help. And please be kind to share your settings.py file which is configured with mongodb. -
Django rendering template variables containing HTML as plaintext, but the source has styling
I'm having an odd issue with Django 2.0.4 (which maybe isn't so odd since I'm new to it). I have a template which I am rendering from a view, and the data passed in is a string containing HTML. My view renders the template as so: return render(request, 'template.html', { 'data' : data }) data.content contains HTML in the above. In my template, I am rendering it as so: template.html (what works): {{ data.content|safe }} This renders fine. However when I have this template include other templates, the HTML ceases to render correctly. template.html (what I want): {% include 'header.html' %} {{ data.content|safe }} {% include 'footer.html' %} The above renders header.html and footer.html fine, but the data.content|safe part in between actually becomes text with no styling. If I view source it's correct HTML (real tags, classes, etc. No & l t ; funny business.), but the browser doesn't apply rendering to it. It just winds up plaintext, e.g. strong tags around a word don't make it bold, lists are just linebreaks, etc. Even though the HTML in the top and bottom templates are included correctly with displayable HTML. The oddest part is the only HTML that is rendered correctly … -
Django Q function for search
My django version is 2.0.4, i want to use django ORM to make complex search, so i used Q function like below: if ',' in searchtitle: searchtitle = searchtitle.split(',') q = Q() q.connector = 'OR' for content in searchtitle: ### q.children.append((filtertitle + '__icontains',content.lstrip())) q.children.append((filtertitle, content.lstrip())) obj= models.Rules.objects.filter(q) If i use Q function without '__icontains', the search result is right, but if i use '__icontains', the obj only has one object which is the last in for, Can anybody help me for this? Thansk! -
setting width for flex containers to 100% is not working
I am trying to set width 100% for the flex containers. But it is not working. basically is like nav-bar or header for which I am trying to set 100% width. Please help me in resolving this issue. you can see the image that header home and search not occupying full width With Many Thanks, Bharath AK -
python for loop if data duplicate show only one
hello newbie python learner here. i got littlebit confused, i have data like this attendance = [ datetime.datetime(2018, 4, 1, 7, 01), datetime.datetime(2018, 4, 2, 7, 01), datetime.datetime(2018, 4, 3, 7, 01), datetime.datetime(2018, 4, 4, 7, 01), datetime.datetime(2018, 4, 5, 7, 01), datetime.datetime(2018, 4, 5, 7, 21), datetime.datetime(2018, 4, 6, 7, 01), datetime.datetime(2018, 4, 7, 7, 01), ] and i want to show it if day are duplicate or acidentally have twice it will ignore another and only show one that have hour & minutes below another. in this case i have 2 data that duplicate on datetime.datetime(2018, 4, 5, 7, 01), datetime.datetime(2018, 4, 5, 7, 21) i want its only show datetime.datetime(2018, 4, 5, 7, 01) since hours/minutes lower than other i do like this j = datetime.datetime(year,month,day,hour,minute) for i in attendance: if i == j: do nothing/skip else print the data j = j but its print all the data, not as i want. -
Save Many-To-Many Field Django Forms
I have a Many-To-Many relationship between a Course and Tutor model. I am trying to make it so that when you use a form to create a record for a new Tutor, you can select the courses they can teach. I tried using and modifying the code from this previous question as best I could, but I don't fully understand it so I'm sure I didn't do it right. When the form is submitted, it won't save the link between the Courses and Tutor. What do I need to change about the code to make it save? models.py class Tutor(models.Model): FirstName = models.CharField(max_length=50) LastName = models.CharField(max_length=50) Email = models.EmailField(max_length=100) PhoneNumber = models.CharField(max_length=10, ) RequestedHours = models.DecimalField(max_digits=3, decimal_places=1) class Course(models.Model): SubjectID = models.ForeignKey(Subject, related_name='subjectCourse') Department = models.CharField(max_length=4) Number = models.CharField(max_length=4) Name = models.CharField(max_length=200) TutorForCourse = models.ManyToManyField(Tutor) forms.py class TutorForm(forms.ModelForm): class Meta: model = Tutor fields = ('FirstName', 'LastName', 'Email', 'PhoneNumber', 'RequestedHours',) labels = { 'FirstName': 'First Name', 'LastName': 'Last Name', 'Email': 'Email', 'PhoneNumber': 'Phone Number', 'RequestedHours': 'Requested Hours', } courses = forms.ModelMultipleChoiceField(queryset=Course.objects.all()) def __init__(self, *args, **kwargs): # Only in case we build the form from an instance # (otherwise, 'toppings' list should be empty) if kwargs.get('instance'): # We get the 'initial' … -
How could I remove a strange header within an AJAX uploaded image with Django
I want to upload an image from JS/jQuery client to a Django server. For some reasons, I can't achieve to do this with a model. So I tried it the old way... Problem: when I upload the file, the produced file contains a part of the HTTP request(?!). Here is my Js code: data = new FormData($('#upform-' + target.getAttribute('data-store'))[0]); contentType = false [...] $.ajax({ type: "POST", scriptCharset: "utf-8", contentType: contentType, dataType: 'json', method: "POST", processData: false, cache: false, data: data, url: "api/" + url, beforeSend: function(request) { request.setRequestHeader("Authorization", 'Token ' + application.api.token); if( target ) { request.setRequestHeader("Content-Disposition", 'attachment; filename=' + target.files[0].name); request.overrideMimeType("multipart/form-data"); } console.log("Données envoyées : ", data); } }) ... Here is my Python view: myfile = request.FILES['file'] outputFile = open(myfile.name, 'wb+') rawContent = ContentFile(myfile.read()) for chunk in rawContent.chunks(): outputFile.write(chunk) outputFile.close() Here is the strange header at the beginning of my "new" file when I open it with Notepad: -----------------------------76672927332420 Content-Disposition: form-data; name="file"; filename="planning.jpg" Content-Type: image/jpeg ÿØÿà The end of the file also contains a "------------------------". Thanks for your help, it drives me crazy! Thank -
Compressing Files to Speed Up Website -- Django + Heroku + AWS
I recently set up AWS to store my static and media files for my Django site. I've run some speed tests which show that my site is running slower than competitors due to my files not being compressed. I'm used to plug and play plugins in Wordpress that handle compression and wonder what the best way to do this in Django might be with AWS. I can see that GZIP in Django has some security flaws? And I've heard some people mention Cloudflare, but I'm almost scared to touch anything at this point, as it took me a good week to get my AWS storage working properly. Is there an easy way to handle this? Here are my AWS storage settings: AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' AWS_QUERYSTRING_AUTH = False STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) #set S3 as the place to store your files. STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # Static files (CSS, JavaScript, Images) ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' #media storage settings MEDIA_URL = 'https://example-bucket.s3.amazonaws.com/media/' STATIC_URL = 'https://example-bucket.s3.amazonaws.com/static/' -
How to save audio file in Django by overriding save method?
I am trying to save audio file in my Django model by overriding save method. In my save method I am converting the text in audio using (Google Text to Speech) library. Here is the link to that Python Library GTTS Here is my code:- class Word(models.Model): word = models.CharField(max_length=200) audio = models.FileField(upload_to='audio/', blank=True) def save(self, *args, **kwargs): audio = gTTS(text=self.word_vocab, lang='en', slow=True) audio.save(self.word_vocab + ".mp3") self.audio.save(self.word_vocab + ".mp3", audio) super(Word, self).save(*args, **kwargs) I can see that my audio file is getting created in Project's root folder but while saving it on the models audio field it's giving me the following error. AttributeError: 'gTTS' object has no attribute 'read' I have also tried using ContentFile like this from django.core.files.base import ContentFile In models save method:- self.audio.save(self.word_vocab + ".mp3", ContentFile(audio) But over here also I get the error:- TypeError: a bytes-like object is required, not 'gTTS' So I tried to convert it into bytes object:- self.audio.save(self.word_vocab + ".mp3", ContentFile(bytes(audio))) But still I ran into the following Error:- TypeError: 'gTTS' object is not iterable Also I would like to know if there is any other method to save the audio file for the corresponding text value like in our case "word" without … -
Update model value
I need suggestions on how to approach this problem. Basically I have 3 models class SGrade(TimeStampedModel): final_grade = models.DecimalField(max_digit=5) class Comp(models.Model): subj_sched = models.ForeignKey(SubjectSched) name = models.Charfield(max_length=150) percentage = models.DecimalField(max_digit=5) class Grade(TimeStampedModel): sgrade = models.ForeignKey(SGrade) component = models.ForeignKey(Component) grade = models.Decimal(max_digits=5) I would like to make an updateview with form for each student's grades. I can access the final grade from SGrade model while the subject name is in Subject model. Grades per component is in Grade model and component (e.g. 1st, 2nd, 3rd, 4th quarters ) are in Component. I am currently ready about Formset but still getting the grasp of it. Any suggestions will be highly appreciated. -
Django self.get_object() crashes my application
@detail_route(methods=['POST', 'DELETE'], permission_classes=[BubbleIsMember]) @parser_classes((FormParser, MultiPartParser,)) def rsvp(self, request, *args, **kwargs): response_data = {'message' : 'Error'} try: post_data = request.data except: response_data['message'] = 'Malformed json. We received:' + json.dumps(request.data) return Response(response_data, status=HTTP_400_BAD_REQUEST) if 'meeting' not in request.data: response_data['message'] = "'meeting' field is required" return Response(response_data, status=HTTP_400_BAD_REQUEST) try: meeting = Meeting.objects.get(pk=post_data['meeting'], bubble=self.get_object()) print("self", self) rsvp, created = MeetingRSVP.objects.get_or_create(user=request.user, meeting=meeting) self.get_object() after that line; code doesn't get processed. Below is what my only 'self' looks like, I'm trying to get bubble object from it. <arrowapi.views.bubble.BubbleViewSet object at 0x1067728d0> My queryset within that View looks like this: def get_queryset(self): if self.request.user.is_superuser: return Bubble.objects.all() elif self.request.user.is_authenticated: memberships = BubbleMembership.objects.filter(user=self.request.user).values_list('bubble', flat=True) return Bubble.objects.filter(pk__in=memberships) else: return Bubble.objects.none()