Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does uploading images to S3 with JS+Django always yield a 400-error?
I've tried with code from several tutorials that teach me how to upload images to S3 using XHR's. The Ajax-call to get the signature from my webserver goes fine, but when I try to upload the form + image to AWS I always get that 400-error with no further details. Could anyone please help me diagnose this issue? I'm using a Chrome browser. Let me know if you need further details. Backend code (in views.py): def sign_s3(request): S3_BUCKET = 'my-bucket' folder_name = request.GET.get('folder_name', '') file_name = request.GET.get('file_name', '') file_type = request.GET.get('file_type', '') upload_start_path = "static/img/{}".format(folder_name) filename_final = "{}.{}".format(file_name, file_type) policy_expires = int(time.time()+5000) policy_document_context = { "expire": policy_expires, "bucket_name": S3_BUCKET, "key_name": "", "acl_name": "public-read", "content_name": "", "content_length": 524288000, "upload_start_path": upload_start_path } policy_document = """ {"expiration": "2019-01-01T00:00:00Z", "conditions": [ {"bucket": "%(bucket_name)s"}, ["starts-with", "$key", "%(upload_start_path)s"], {"acl": "%(acl_name)s"}, ["starts-with", "$Content-Type", "%(content_name)s"], ["starts-with", "$filename", ""], ["content-length-range", 0, %(content_length)d] ] } """ % policy_document_context aws_secret = str.encode(os.environ.get('AWS_SECRET_ACCESS_KEY')) policy_document_str_encoded = str.encode(policy_document.replace(" ", "")) url = 'https://{bucket}.s3.{region}.amazonaws.com/'.format( bucket=S3_BUCKET, region='eu-central-1' ) policy = base64.b64encode(policy_document_str_encoded) signature = base64.b64encode(hmac.new(aws_secret, policy, hashlib.sha1).digest()) data = { "policy": bytes.decode(policy), "signature": bytes.decode(signature), "key": os.environ.get('AWS_ACCESS_KEY_ID'), "file_bucket_path": upload_start_path, "file_id": 1, "filename": filename_final, "url": url, } return JsonResponse(data) Frontend code: var fileItemList = []; document.getElementById("button").onclick = function(){ var … -
TLS1.2 not supported with my python/django site
I'm hoping someone might be able to help me. I have a client that has a website running Python 2.7.5+ (according to python -V). It's an ecommerce site that also uses the eWay payment gateway. They recently made some changes to only support TLS1.2 https://www.eway.com.au/tls-updates. However, when a customer goes through the checkout it shows a denied message from the eWay payment gateway. eWay say that this is because the transaction is still not coming through as TLS1.2. I have upgraded the Amazon EC2 instance and modified the apache .conf file so that it only supports TLS1.2 and i have verified this by checking the site through an SSL test with https://www.ssllabs.com/ssltest/. Therefore, I believe the issue may be due to the pyOpenSSL package being on a version that doesn't support TLS1.2. It's apparently on version 0.13: pyOpenSSL==0.13. I was wondering if someone might be able to help confirm or disprove my theory (I know this may be difficult with not having access to the server) and perhaps provide some pointers. I have tried upgrading pyOpenSSL using the command pip install –upgrade pyopenssl==0.15.1 but I got the following error; Exception: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/pip-1.5.2-py2.7.egg/pip/basecommand.py", line 122, in … -
Django: Custom Profile Picture To New User
In Registration form before saving the User I wants to give the Profile picture of First user to every new user until they change it. This is what I tried, def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): new_form = form.save(commit=False) new_form.user.userprofile.profile = UserProfile.objects.profile(id=1) new_form.save() This code is showing me the error "'Manager' object has no attribute 'profile'". How can I do that ? -
How to use an es6 file with django?
I would like to implement this answer: https://stackoverflow.com/a/31669706 but I dont have an idea how to integrate it with Django. Would appreciate any guidance. Thank you. -
Get the selected radio button in django template
In my template I have for loop. As you can see the id for each radiobutton is reprsented by {{stud.id}} . {{stud.nameAndSurname}} shows the name and the surname of the student(in browser I can see name and surname of the corresponding student). <form method="POST" class="post-form"> {% csrf_token %} {% for stud in students %} <input type="radio" id={{ stud.id }} name="student">{{ stud.nameAndSurname }} {% endfor %} <button type="submit" class="save btn btn-default">GO!</button> </form> In my view.py I have: class MyClass(View): def get(...): ... def post(self,request, pk): myVar = request.POST.get("student") return HttpResponse(myVar) If I click submit button i want to go to another page that shows me name and surname of the selected student. Now the issue is that instead of the student's name and surname it's showing me simply written "on" -
How to insert multiple images into a blog post not File field upload (Django blog)
I am a semi-noob to Django web development. I've managed to add a File field that actually allows me to upload an image into the post (The image is displayed in post-list and post-detail) but what if I wanted to add several images in a post? I am currently writing a tutorial post and would like to insert images under each instruction for the benefit of the user. I don't want the tutorials to be purely text, how do I go about doing this? Below is my models.py from __future__ import unicode_literals from django.db import models from django.core.urlresolvers import reverse from django.utils import timezone #from taggit.managers import TaggableManager class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) image = models.FileField(null=True, blank=True) #tags = TaggableManager() def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title def approved_comments(self): return self.comments.filter(approved_comment=True) class Meta: ordering = ["-pk"] class Comment(models.Model): post = models.ForeignKey('blog.Post', related_name='comments') author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def approved_comments(self): return self.comments.filter(approved_comment=True) def __str__(self): return self.text And here's my forms.py from django import forms from .models import Post, Comment class PostForm(forms.ModelForm): class … -
How do you store general site settings in the database with django?
I am trying to decide whether I should use the settings file or store settings in the database so that other tools that hook into the database can be used. At its most basic the model will be called Setting from django.db import models class Setting(models.Model): name = models.Charfield(max_length=255, blank=False) value = models.Charfield(max_length=255) So no datatype nothing just text, which is pretty much how it is in the config file. Then getting a setting is just a matter of: my_setting = Setting.objects.get(name='my_setting') Would this way be suitable? -
Django, having Q object filter by function in model
Inside my Profile model I have the following function: It serves to return the fullname of the user (or a alternative if some data is missing). def full_name(self): first_name = self.user.first_name.strip() if first_name and self.user.last_name: if not self.middle_name: full_name = u'%s %s' % (first_name, self.user.last_name) else: full_name = u'%s %s %s' % (first_name, self.middle_name, self.user.last_name) return full_name.strip() elif first_name: return first_name return self.user.username Now for my question: I have a view where I filter a queryset based on the variable 'q' (that is returned from a searchbox in the template) Like so: qs = qs.filter(tenant_demo_purchase=True).order_by('-id') #Search users within results q = self.request.GET.get('q', None) if q: qs = qs.filter(Q(user__username__icontains=q) | Q(user__first_name__icontains=q) Q(user__last_name__icontains=q) | Q(arrangement_period__arrangement__title__icontains=q) | ).filter(tenant_demo_purchase=True).order_by('-id') else: pass return qs This filter works fine if I give it a firstname, username, or a last name. But if I give it a firstname + lastname (example: "John Doe") it returns no results. Most of my users tend to submit the fullname, so as a solution I tried to have it acces the Profile.full_name function. By adding the following line Q(user__profile__fullname__icontains=q) However, this crashes with the following error message: raise FieldError('Related Field got invalid lookup: {}'.format(lookups[0])) FieldError: Related Field got invalid lookup: fullname … -
ImportError: No module named allauth. Django
in a project with django, when I do "python manage.py runserver" I get this error traceback : Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Python27\lib\site-packages\django\apps\config.py", line 94, in create module = import_module(entry) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) ImportError: No module named allauth I installed allauth using pip3 install allauth. And this is my INSTALLED_APPS : INSTALLED_APPS = [ 'music.apps.MusicConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', ] -
Limiting QuerySets in Django is not working
I just get no answer what is not working from Django. Django says everything is okay. I want to limit the results I get from my database. In the documentation is said that the first parameter is the offset and the second how much results I get beginning with the offset + 1. What I am doing wrong here ? When I do not limit the queries everything works fine. So the mistake should be by using the limitation. views.py def ajax_more(request): categoryid = request.GET.get('categoryid', None) query = request.GET.get('query', None) offset = request.GET.get('offset', None) if query: if categoryid == "6": advertisements = Advertisement.objects.filter(title__contains=query)[int(offset): 2] else: advertisements = Advertisement.objects.filter(category__id=categoryid, title__contains=query)[int(offset): 2] else: if categoryid == "6": advertisements = Advertisement.objects.all()[int(offset): 2] else: advertisements = Advertisement.objects.filter(category__id=categoryid)[int(offset): 2] advertisements_list = [] for advertisement in advertisements: advertisements_list.append({ 'id': advertisement.id, 'description': advertisement.description, 'title': advertisement.title, 'picture_url': advertisement.image.url, 'date': advertisement.date }) data = { 'advertisements_list': advertisements_list } return JsonResponse(data) -
Django self.cleaned_data.get("field") is None when field value is 0 : why?
I have a field : models.py class MyClass(models.Model) : myfield = models.FloatField(blank=True, null=True) and a form validation that handles conditionals controls on multiple fields and must raise an error if self.cleaned_data.get("myfield") is None. My problem is : I want to accept the value "0" as correct. but when a user inputs 0 for the field myfield, the self.cleaned_data.get("myfield") is None : Why ? and the form validation raises an error. -
How to iterate for loop with range using django template
I WANT TO USE i inside the loop means {{ posts.0.title|capfirst }} {{ posts.i.title|capfirst }} value of i is 0 to 12 but its not working with {{ posts.i.title|capfirst }} {% for i in TotalCountRange %} <tr class="even pointer"> <td class="a-center "> <input type="checkbox" class="flat" name="table_records"> </td> <td class=" "><a href="{{ post.get_absolute_url }}">{{ posts.0.title|capfirst }}</a></td> <td class=" ">{{ post.pub_date|date:"d M y h:i a" }} </td> <td class=" "><a href="{{ post.category.get_absolute_url }}">{{ post.catname }} <i class="success fa fa-long-arrow-up"></i></a></td> <td class=" ">{{ post.username }}</td> <td class=" "> <!--{% for tag in post.tags.all %}--> <!--{% with b=',' %}--> <!--{% if forloop.counter >= 2 %}--> <!--<a href="{{ tag.get_absolute_url }}">{{b}}{{ tag }}</a>--> <!--{% else %}--> <!--<a href="{{ tag.get_absolute_url }}">{{ tag }}</a>--> <!--{% endif %}--> <!--{%endwith%}--> <!--{% empty %}--> <!--<a href="">None</a>--> <!--{% endfor %}--> </td> <td class=" "><a href="#">Edit</a></td> </tr> {% endfor %} -
Annotate Custom SQL Function (similar to date_trunc) to Django ORM Queryset
I am using timescaledb which is basically just an extension for postgres. It comes with a SQL function called time_bucket. I want to use this function in combination with the ORM to generate a query as follows: SELECT time_bucket('1 minute', time) AS tb, device_id, AVG(s0) FROM measurements WHERE device_id=1 AND time >= to_timestamp(1) AND time <= to_timestamp(2) GROUP BY device_id, tb ORDER BY tb ASC; models.py: class Measurement(models.Model): device_id = models.IntegerField(primary_key=True) time = models.DateTimeField() s0 = models.FloatField(blank=True, null=True) My try so far: (Measurement.objects .values('time') # .annotate(tb=Func('time_bucket')) .annotate(s_desc=Avg('s0')) .filter( time__gte=datetime.fromtimestamp(start), time__lte=datetime.fromtimestamp(end)) .order_by('time') ) I am wondering if I would need to look into the source code of Trunc or is there an easy option I am missing? -
django+docker to elastic beanstalk
I created a super simple django app in docker, following these instructions: https://docs.docker.com/compose/django/ Everything works locally. When I try to upload the folder that includes Dockerfile and docker-compose.yml to AWS Elastic Beanstalk as a multicontainer docker, it does not work. Should I also provide Dockerrun.aws.json? here is what I have in Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ and in docker-compose.yml: version: '3' services: db: image: postgres web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db -
Django multiple values in single form field
How can I add multiple values in a single form field just like the image below -
Can't get field value in Ajax call - Django
Here is my ajax call: $.ajax({ type: 'POST', url: '{% url "userprofile:follow" %}', data: { user_to_follow: $("#follow_form").serialize(), csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function showAlertLike() { $("#success_follow").show().delay(2000).fadeOut(); }, error: function showAlertLike() { $("#error_follow").show().delay(2000).fadeOut(); } }); and my view: def post(self, request): if request.method == 'POST': user = request.user user_to_follow = request.POST.get('user_to_follow') print('USER: ', user_to_follow) user_to_follow = User.objects.get(username=user_to_follow) Following.objects.create( user_followed=user_to_follow, follower=user, ) return HttpResponse('') What is being printed on my terminal: ('USER: ', u'csrfmiddlewaretoken=wxWNjebUftJ88ekmCrIwNjJFFMoiO8l1RM2RKqZpeIvtCmIsFKtPDFBlOLUxE0BV') How can I retrieve the input entered in the form field and not the csrftoken? I tried .val() instead of .serialize() but it returns an empty string... Thanks -
Custom User Profile for New Users
{% if user.userprofile.profile %} <img src="{{ user.userprofile.profile.url }}" /> {% else %} <img src="something" /> {% endif %} If user don't have a profile picture then I wants to give them the Profile picture of very First user (means id=1). How can I do that? -
AttributeError at / 'tuple' object has no attribute '_meta'
I'm getting the above error in Django on the second line this code: survey = Survey.objects.get_or_create(organisation=organisation) form = SurveyForm(instance=survey) This is my form: class SurveyForm(forms.ModelForm): class Meta: model = Survey exclude = ['id'] widgets = { 'user' : forms.HiddenInput(), 'organisation' : forms.HiddenInput(), 'responsibleSecurityOfficer' : forms.TextInput(attrs={'class' : 'form-control'}), 'responsibleSecurityOfficerJobTitle' : forms.TextInput(attrs={'class' : 'form-control'}), 'size' : forms.Select(attrs={'class' : 'form-control'}, choices=SIZE_CHOICES), 'baseInfoSecurity' : forms.Select(attrs={'class' : 'form-control'}), 'pciCompliance' : forms.Select(attrs={'class' : 'form-control'}), 'hipaaCompliance' : forms.Select(attrs={'class' : 'form-control'}), 'internationalCompliance' : forms.Select(attrs={'class' : 'form-control'}), 'country' : forms.TextInput(attrs={'class' : 'form-control'}), 'drPlan' : forms.Select(attrs={'class' : 'form-control'}), } I really don't understand why it is not working and I do not see any erroneous commas (which seems to be the general issue based on similar posts). Any help most welcome. -
Django Websockets / Several Users on the Website
I try to get started with Django Channels. I actually have some questions: 1. I use web sockets with channels. I want to have for each frontend user which opens the website his own websocket channel without groups. I am not sure how does it works when several Users opens the website ? Has each frontend user his own consumer thread which handles the web socket messages ? How are the concept here? 2. How can I receive websocket messages in a separate task. I found in the FAQ on the Channels Site the hint to use receive_many() but I'm not sure how to use it exactly. 3. How can I start a separate task in the consumer.py after receive a message ('websocket.receive') ( for example: In Consumer I get a message via websocket from the frontend user, according to the message I start a process with some arguments, after execute the process, I get the results back and send it to the individual websocket channel client) -
Disable Fields from Editing in Django
I have a form with several fields that I would like to show to the user but prevent them from editing (should not be an edit box). My form class looks like this and I'm using the fields meta to have them automatically defined. I'm looking to prevent user from changing their username and email after registration. class UserEditForm(forms.ModelForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password') The question In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited? doesn't provide an answer to what to do if the fields are defined automatically using meta. I've tried disabled = ('username', 'email',) And a few other options but nothing seems to work. I'm looking to prevent someone from also changing the form and submitting it (and the data getting changed) as the previous question suggested can be done. [Edit]: Using Django 1.11 -
Django - leaving blank form when session doesn't exist
I have a noobie question about filling registration forms from sessions. I have 3 step registration form that saves data to session. I am trying to fill form data with previous answers when user goes step back. I managed to do that, but now I have problem when session is empty. Here is the problematic code: if request.session['form_data_page_1']: korisnik = Forma1(initial=request.session['form_data_page_1']) else: korisnik = Forma1() when I do that I keep getting 'KeyError at /start/dadilja/1/' - 'form_data_page_1'. I also tried to do something like this: if request.session['form_data_page_1'] is not Null: korisnik = Forma1(initial=request.session['form_data_page_1']) else: korisnik = Forma1() and something like this: try: korisnik = Forma1(initial=request.session['form_data_page_1']) except: korisnik = Forma1() but when I do that, I get blank page with submit button on it. How to do this correctly, to get blank form when session is empty, and filled form with session data when session exist? Thanks in advance. Renato -
how to combine ember.js with django together
I am new to this ember and django framework ,but i wanted to try how it work out , but i have problem combine them together , i have been look though the web and noting work out. can anyone guide me to combine them both ? so how do i get them work together and how i should start ? this is the website i am following. http://timothypoon.com/blog/2016/02/16/ember-and-django-get-friendly/ -
Accessing the json values on django template
I have finally got a way to access the various values from the facebook using django-allauth. The only issue that I am facing is in the accessing of the values on the template. Here is the views.py: from allauth.socialaccount.models import SocialToken import json import requests def fb_personality_traits(request): access_token = SocialToken.objects.get(account__user=request.user, account__provider='facebook') # print access_token.token requested_data = requests.get( 'https://graph.facebook.com/me?access_token=' + access_token.token + '&fields=id,name,email,posts,about') data_FB = json.loads(requested_data) return render(request, 'home/facebook_personality_traits.html', {'fb': data_FB}) Here is the template taht I am using to display the values: <html> <body> Welcome back {{ user.name }} {{fb.name}} <!-- <img src="" height="60" width="60"> --> <a href="/">Home</a> </body> </html> I am getting the following error: Please let me know what to improve. This is the json I am storing in the json variable: gist of the json -
Django shell_plus TypeError: invalid arguments (virtualenv)
My Django project runs under a virtualenv located at Envs\newenv and I am having trouble running shell_plus: python manage.py shell_plus Raises the following error: TypeError: invalid arguments This is the full trace: Traceback (most recent call last): File "manage_sched_dev.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\__init__.py", line 354, in execute_from_command_line utility.execute() File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\base.py", line 382, in run_from_argv parser = self.create_parser(argv[0], argv[1]) File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\base.py", line 316, in create_parser help='Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output') File "c:\python27\Lib\optparse.py", line 1018, in add_option raise TypeError, "invalid arguments" TypeError: invalid arguments The problem is happens at this point: File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\base.py", line 316, in create_parser help='Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output') The value of that help key argument is of type unicode, but the add_option function in the optparse module expects a str: def add_option(self, *args, **kwargs): """add_option(Option) add_option(opt_str, ..., kwarg=val, ...) """ if type(args[0]) is types.StringType: option = self.option_class(*args, **kwargs) elif len(args) == 1 and not kwargs: option = args[0] if not isinstance(option, Option): raise TypeError, "not an Option instance: %r" % option else: raise TypeError, "invalid arguments" types.StringType is defined as follows: StringType = str I have … -
Group by in django create wrong query
we have write down this query in django ManageInterview.objects.filter (post_id=request.data['job_id']) .order_by('-id') .annotate(total=Count('pitcher_id')) After print this we got this query SELECT *, COUNT(`pitcher_invitations`.`pitcher_id`) AS `total` FROM `pitcher_invitations` WHERE `pitcher_invitations`.`post_id` = 254555444 GROUP BY `pitcher_invitations`.`id` ORDER BY `pitcher_invitations`.`id` DESC We are doing group by pitcher_id but django query group by pitcher_invitations.id we want this query select * from `pitcher_invitations` where `post_id` =254555444 group by `pitcher_id` order by `id` desc