Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
mongoengine.errors.LookUpError: Cannot resolve field "$question_title"
Am working on a django project using mongodb's mongoengine. I want to create a text index on my models, This is what i have models.py from mongoengine import * class Questions(Document): question_title = StringField(max_length=100) question_text = StringField(max_length=500, required=True) authors = ReferenceField(Users, required=True, reverse_delete_rule=CASCADE) creation_date = DateTimeField() votes = IntField(default=0) #.. more fields definitions meta = { 'indexes' : [ { 'fields' : ['$question_title', '$question_text'], 'default_language' : 'english', 'weight' : { '$question_title': 10, '$question_text' : 5 } } ] } But then django raises that error. What am i supposed to do to create text indexes in my documents. Any help is greatly appreciated -
Django 1.10 pass form object into template
I would like to pass my custom form into a template file. Template: {{ form }} # prints nothing Views: class EntertainerDisplay(FormView): form_class = EntertainerCheckboxForm template_name = 'entertaining/custom_form.html' Form: class EntertainerCheckboxForm(forms.Form): class Meta: model = Entertainer fields = ['first_name', 'second_name', 'last_name' ] No matter what I do, form variable is never in View context, and therefore not sent into a template file. How can I pass form and its fields into form variable in a template file? -
View returns 404 when including a queryset despite the object being valid
I'm using the following URL pattern to pass a primary key for a model to the view class detailed below it. The primary key of the related model, "Host", is either a valid IP address or FQDN. URL Pattern: ValidIpAddressRegex = "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])" ValidHostnameRegex = "(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])" url(r"^host/(?P<pk>({}|{}))/$".format(ValidIpAddressRegex, ValidHostnameRegex), views.HostView.as_view(), name="host") View class: class HostView(generic.DetailView): model = Host template_name = 'report_viewer/host.html' context_object_name = 'related_findings' def get_queryset(self): """Return all related findings""" host = get_object_or_404(Host, name=self.kwargs["pk"]) return host.get_findings() # A function on the model to return related records from another model Relevant template: <ul> {% for finding in related_findings %} <li><a href="{% url 'report_viewer:finding' finding.plugin_id %}"><strong>{{ finding.plugin_id }}</strong> {{ finding.plugin_name }}</a></li> {% empty %} <li>No findings!</li> {% endfor %} </ul> The result of a valid URL is "No finding found matching the query", raised by views.HostView. The view below works successfully, invoking the {% empty %} condition, which suggests that I'm either constructing the get_object_or_404 request incorrectly, or perhaps the "pk" variable is being mangled and is not a valid key. I'd appreciate any thoughts on a solution. Or indeed an alternative method to achieve the same outcome. -
django instance.id=None when uploading image
instance.id is returning None when upload images through the admin page. The idea was to upload all the images of each Residence to a different folder. Here's my code: models.py from django.db import models import os def get_image_path(instance, filename): return os.path.join('photos', "residence_%s" % instance.id, filename) # Create your models here. class Residence(models.Model): big_image = models.ImageField("Main Image",upload_to=get_image_path) small_images = models.ImageField("Small Images",upload_to=get_image_path, blank=True, null=True) settings.py MEDIA_URL = '/media/' -
Nested serializer with optional field raising KeyError
I have two serializers, first one (a bit simplified): class FilterSerializer(serializers.Serializer): brand = serializers.PrimaryKeyRelatedField( queryset=org_models.Brand.objects, many=False, error_messages={'does_not_exist': org_consts.BRAND_NOT_EXIST} ) country = serializers.PrimaryKeyRelatedField( queryset=org_models.Country.objects, many=False, error_messages={'does_not_exist': org_consts.COUNTRY_NOT_EXIST} ) level = serializers.PrimaryKeyRelatedField( queryset=org_models.Level.objects, many=False, required=False, error_messages={'does_not_exist': org_consts.DISTRICT_NOT_EXIST} ) class Meta: fields = ('brand', 'country', 'level') and second: class PeopleReportSerializer(serializers.Serializer): filters = FilterSerializer(many=True) start_date = serializers.DateField(required=False) end_date = serializers.DateField(required=False) class Meta: fields = ('filters', 'start_date', 'end_date') def validate(self, data): """Check if end_date occurs after start_date. """ if data.get('start_date') and data.get('end_date'): if data['start_date'] > data['end_date']: raise serializers.ValidationError(constants.INVALID_START_DATE) return data I've removed some fields for clarity. So basically all I want from this serializer is validation if objects with posted ID exist in the database. On GET I would like it to return some data depending on request.user but that's another case. So now in my view I'm doing something like this: class PeopleReportView(ReportsPermissionMixin, views.APIView): serializer_class = PeopleReportSerializer task = staticmethod(people_report) # celery task, creates reports def get(self, request): # TODO: depending on request.user return initial data such as: # country / brand / district and so on return Response() def post(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(raise_exception=True): task = self.task.apply_async(kwargs=serializer.data) return Response({'task_id': task.id}) my problem is that when I post data without level field … -
Why doesn't the following jquery code work?
Hi i am trying to query the database to find if the username typed by the user is already in the database if yes then it should display message "already exist!" but instead of that displaying the message i get the following error in my browser : i have stored the username "ahti" in my database. urls.py from django.conf.urls import url from .import views urlpatterns = [ url(r'^$', views.index, name="Index"), url(r'^validate/$',views.validateForm), ] views.py from django.shortcuts import render from librarysystem.models import Users from django.http import JsonResponse def validateForm(request): username = request.GET.get('username',None) data = { 'is_taken' : Users.objects.filter(username__iexact=username) } return JsonResponse(data) my jquery code : <script type="text/javascript"> function validateForm() { var username = $('#username').val() ; $.ajax({ url: '/librarysystem/validate/', data: { 'username': username }, dataType: 'json', success: function(data){ if (data.is_taken){ alert("already taken!"); } } }) ; } $(document).ready(function() { $("#username").keyup(validateForm); }); </script> -
Django won't serve static files from Amazon S3 with custom domain
I did setup my Django project, DNS and bucket on Amazon S3 but python manage.py collectstatic and therefore also files uploaded manually won't works. AWS S3 Settings: Bucket name: files.domain.com Bucket policy: { "Id": "Policy1483363850641", "Version": "2012-10-17", "Statement": [ { "Sid": "Stmt1483363848944", "Action": "s3:*", "Effect": "Allow", "Resource": "arn:aws:s3:::files.domain.com/*", "Principal": "*" } ] } DNS Settings: files.domain.com -> CNAME -> files.domain.com.s3.amazonaws.com Django Settings: DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' AWS_ACCESS_KEY_ID = 'XXXXXXXXXXXXXXXXXXXX' AWS_SECRET_ACCESS_KEY = 'XxXxXXxXXXXXxxxXxxXXXxXxxXXXXXXXXxxxXxxx' AWS_STORAGE_BUCKET_NAME = 'files.domain.com' AWS_AUTO_CREATE_BUCKET = False AWS_QUERYSTRING_AUTH = False AWS_S3_SECURE_URLS = False AWS_EXPIRY = 60 * 60 * 24 * 7 AWS_HEADERS = { 'Cache-Control': six.b('max-age=%d, s-maxage=%d, must-revalidate' % ( AWS_EXPIRY, AWS_EXPIRY)) } MEDIA_URL = 'http://%s/' % AWS_STORAGE_BUCKET_NAME STATICFILES_STORAGE = DEFAULT_FILE_STORAGE STATIC_URL = MEDIA_URL -
Django Python - select column from related_object in a template
I just started with Django, and trying to figure out how stuff works. I'm stuck with the following problem. I have a models.py: class Station(models.Model): code = models.CharField(max_length=10, default='') land = models.CharField(max_length=10, default='') def __str__(self): return self.code class Naam(models.Model): kort = models.CharField(max_length=255, default='') middel = models.CharField(max_length=255, default='') lang = models.CharField(max_length=255, default='') station = models.ForeignKey(Station, default='', on_delete=models.CASCADE, related_name='namen') def __str__(self): return self.lang I have a view.py: def index(request): all_stations = Station.objects.all() return render(request,'stations/index.html', {'all_stations' : all_stations}) def detail(request, station_id): try: station = Station.objects.get(id=station_id) stationnamen = station.namen.values() except Station.DoesNotExist: raise Http404("station does not exist") return render(request, 'stations/detail.html', {'stationnamen' : stationnamen.values()}) In a template html I'm trying to show some details about a station (kort,middel,lang) names. Is it possible to show a particular field in the queryset like: <h1>{{ stationnamen.kort }}</h1> In the shell I'm able to do this as follows: station1.namen.values('kort') How this work in template files? Thanks! -
Nested queryset update
Due to some file uploading features I have denormalized db. Users could post one EventComment per Event and few Images. Images were stored separately from comments. Now I need to connect them and set a task that will do this once per day. class EventComment(models.Model): author = models.ForeignKey('user') event = models.ForeignKey('event') class Image(models.Model): author = models.ForeignKey('user') event = models.ForeignKey('event') foo = models.ForeignKey('foo', null=True, blank=True) I very much don't want to do this that way: for i in Image.objects.filter(eventcomment__isnull=True): i.eventcomment = EventComment.objects.get(event=i.event, author=i.author) i.save() What is a correct way to write nested queryset? I tried this way, but I get DataError: invalid input syntax for integer: "event" Image.objects.filter(eventcomment__isnull=True).update(eventcomment=EventComment.objects.get(event=Value('event'), author=Value('author'))) -
How to change DateTimeField to dd-mm-yyyy format in Django
By default Django takes datetimefield as yyyy-mm-dd format. How to make it into dd-mm-yyyy format? Will Culture format en-IN help? -
Django - How to store scalar value (for adding) or percentage value(for multiply) in one column?
I have a problem in django - I would like to store "provision" value. But sometimes its value is scalar, e.g. 2.10$, and sometime its value is percentage, e.g. 10%. When I have value 2.10 in database, I should add this value to base price. When I have value 0.10 in database, I should add 10% of base to have final price. For example: 10.0 + 2.10 = 12.10 10.0 + 10.0 * 0.10 = 11.0 (or 10.0 * 1.10 = 11.0) To avoid having multiple columns (for storing scalar or percentage) and confusion: what to do, if two value are filled, I decided to store string value: "+2.10" or "*0.10". So it looks like, I need some kind of symbolic arithmetic in django. Questions: Does anyone have seen such package in django? If not 1, durring development I should create: model field form field form widget -
Django, I am getting "Permission Denied" when trying to access a directory that is given to an ftp user
My django application (v1.8) is using a directory for exporting some csv files. This directory is something like: "/home/username/django_project/csv_out". I have intentionally chmod the "csv_out" dir to 777. My partner wanted to access this directory in order to download and inspect those csv files. I created an FTP user like this: useradd ftp_user -p somepassword -d /home/username/django_project/csv_out/ -s /bin/false Since then I get a "Permission Denied" error from Django (was not getting that error before): IOError: [Errno 13] Permission denied: '/home/username/django_project/csv_out/weights_1.csv' Am I doing something wrong? -
django + mysql, storing ip address including ranges
I need an efficient way to store IP address. The query I would like to do is if IP is in the table (or in range). I need to store ranges like, 192.168.0.1 - 192.168.1.255 And also individual IPs. Since there are many records I think it will be a waste to store them one by one. But I would go for that if that would be the best. Django does have GenericIP field, but it does not meant for ranges. So what is my best solution? -
Nginx 403 Forbidden Even After Setting The Permission
I want to get Letsencrpyt SSL for my domain. Part of the process is, the site needs to be authorized before getting the certificate. I created the folder ./well-known and ran the command I was asked to and I got; Nginx 403 forbidden. I'm on nginx/1.10.0 (Ubuntu) I chown the directory and granted it 755 yet still the same. Check out the permissions in my directory below. namei -l /var/www/example.com/.well-known f: /var/www/example.com/.well-known drwxr-xr-x root root / drwxr-xr-x root root var drwxr-xr-x root root www drwxr-xr-x cman sudo example.com drwxr-xr-x cman sudo .well-known I also created a working.html file in the /.well-known folder and I load example.com/.well-known/working.html, I got the same 403 Forbidden. Nginx.conf upstream kip_app_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Gunicorn master nukes a # single worker for timing out). server unix:/var/www/example.com/src/run/trav.sock fail_timeout=0; } server { listen 80; server_name example.com www.example.com; location = /favicon.ico { access_log off; log_not_found off; } access_log /var/www/example.com/logs/access.log; error_log /var/www/example.com/logs/nerror.log; charset utf-8; client_max_body_size 75M; location /static/ { alias /var/www/example.com/src/static/; } location /media/ { alias var/www/example.com/src/media/; } location ~ /\.well-known { allow all; alias /var/www/example.com/.well-known/; } location / { … -
AWS.SimpleQueueService.PurgeQueueInProgress error when using celery flower
Currently I'm working on a project which uses following config: Language: Python Framework: Django Celery broker url: Amazon SQS I need to integrate 'flower' (real-time celery web monitoring) to monitor multiple celery in my project. I have followed the steps mentioned in the doc. But when I launch flower from my celery I'm getting the following error File "/home/ubuntu/tutorial/new_environment/local/lib/python2.7/site-packages/kombu/transport/SQS.py", line 305, in _delete super(Channel, self)._delete(queue) File "/home/ubuntu/tutorial/new_environment/local/lib/python2.7/site-packages/kombu/transport/virtual/__init__.py", line 306, in _delete self._purge(queue) File "/home/ubuntu/tutorial/new_environment/local/lib/python2.7/site-packages/kombu/transport/SQS.py", line 446, in _purge q.clear() File "/home/ubuntu/tutorial/new_environment/local/lib/python2.7/site-packages/boto/sqs/queue.py", line 400, in clear return self.purge() File "/home/ubuntu/tutorial/new_environment/local/lib/python2.7/site-packages/boto/sqs/queue.py", line 396, in purge return self.connection.purge_queue(self) File "/home/ubuntu/tutorial/new_environment/local/lib/python2.7/site-packages/boto/sqs/connection.py", line 124, in purge_queue return self.get_status('PurgeQueue', None, queue.id) File "/home/ubuntu/tutorial/new_environment/local/lib/python2.7/site-packages/boto/connection.py", line 1227, in get_status raise self.ResponseError(response.status, response.reason, body) SQSError: SQSError: 403 Forbidden <?xml version="1.0"?><ErrorResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"><Error><Type>Sender</Type><Code>AWS.SimpleQueueService.PurgeQueueInProgress</Code><Message>Only one PurgeQueue operation on 41a3f5aa-1647-39d6-957f-fe6dch61247d-reply-celery-pidbox is allowed every 60 seconds.</Message><Detail/></Error><RequestId>d1121c15-99fc-5d26-a150-0ce1234fd9fa</RequestId></ErrorResponse> Thanks in advance!! -
Codemirror editor set multiple line value
Here is code of to create codemirror object var myCodeMirror = CodeMirror(document.getElementById('text_area'), { mode: "text/x-c++src", lineNumbers: true, indentUnit: 4, }); After i submit code, i get the code but i also want it to retain it in code editor after post, This dosent work when code is of multiple lines myCodeMirror.setValue("{{submitted_code}}") -
Update django storages to work with private files
I have been using django-storages with AWS, using just public files (AWS_QUERYSTRING_AUTH = False) for the media and static folders. Now I want to change the behaviour to make just the media folder private. I have been able to make django-storages to use authentication query string, defining the settings like: MediaRootS3BotoStorage = lambda: S3BotoStorage(location='media', querystring_auth=True) However, the files are still directly accessible from the previous URL. I would like to (1) make all the old files private (2) make the new uploaded files private as well. Is there any way to accomplish this using django-sotrages? I have not been able to find it in the documentation. -
Reference related objects in template to get url
I want to reference a url in my template which is generated with the pk/id from the object. Normally I do this with action="{% url 'member:patient-delete' patient.id %}" in my template But I have some issues to figure out how I can reference the right id when my model is related to another model. So I have this classes: class Patient(models.Model): patientID = models.CharField(max_length=200 , default='Enter PatientID') birth_date = models.DateField(auto_now_add=False, auto_now=False, default='MM/DD/YYYY') gender = models.CharField(max_length=200,choices=Gender_Choice, default='UNDEFINED') class GeneralData(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) examination = models.CharField(max_length=100, choices=Examination_Choice, default='notchosenyet') height = models.FloatField(default='') weight = models.FloatField(default='') and the url I want to add to my template is: # /member/generaldata/2/ url(r'generaldata/(?P<pk>[0-9]+)/$', views.GeneralDataUpdate.as_view(), name='generaldata-update'), Now I must reference the right id. I must get the ID of the generaldata object which is connected to my patient. I had a OnetoOne Relation before (must change it because of reasons) and with that I solve my problem with a related name. But now it does not work anymore. -
Django filter "contained in"
A simple model: class Article: category = models.CharField(max_length=8) Now, if I want to filter all articles whose category contain the string "green", I would use: .filter(category__contains='green') This would filter articles with the categories 'blue and green', 'green car', et.c. My question is, how would i filter all articles whose category are contained in a string. E.g: .filter(category__contained_in='1green2') Would filter all articles whose category are '1green', 'green', 'green2', '1green2', et.c. The problem is that I, as you might have guessed, have a large database with objects sorted in categories which have irrelevant prefixes and suffixes. The category '1green2', for example. All previous posts on the subject I have found have discussed filtering based on whether the filed is contained in a list of strings, not a singular string. -
I want to upload to S3 with django model filefield without django-storages
I am trying to create a REST API with Django Rest Framework which includes upload files. I want to upload files to S3 with some dynamically created key(which I create based on some data I receive). However, Django FileField in my models needs a path to upload. If I do not provide a path it holds in memory and later uploads them to the main folder of the server. I want the default file storage to be S3. All the results I searched I got results using django-storages library only. Is it possible to implement this using boto3 only? -
Using Multiple users for smtp with django
I am using smtp to send email from my server. Since i have too many mails to shoot, i want use more than one account, i.e when submission quota of one account is reached i switch to another account. with this in mind.. i wrote a method to get connections, like this def get_smtp_connection(self): config = SMTPConfiguration.objects.get(is_default=True) connection = get_connection( host=config.smtp_host, port=config.smtp_port, username=config.smtp_username, password=config.smtp_password, user_tls=config.user_tls ) return connection but i want to test if the connection i return from this method can correctly send emails, is there any method to test this connection.. dir(connection) did not gave anything useful. -
getting error in Django setup in pip install
Install all the requirements in your environment. pip install -r requirements After that, run the app using Django manage.py. python manage.py runserver -
HTTP request editor for Django
My main AIM is to have a editor for Django admin where he can save his API's. With each API he can mention what authentication, Headers, Method, Body it requires. So that when you actually curl or hit that API it can be validated before actually validating at API server. I don't know if there is any lib available for the same. But yes there are many API gateways available. I have tried using Kong but doesn't fit my requirements completely. So I was just wondering if their any such package available for django, If if that doesn't match 100% requirement. -
Is HTML supported in subject line of email
I'm sending emails, using Django framework. And I wonder is it possible to make subject line red, using <span style="color:red">Some subject line</span> -
Add custom page to django admin without a model
I'm trying to add a custom page to the admin without a model association. This is what I achieved so far. https://gist.github.com/gpietro/7d6f17f95ced52f24dbacd78d1d49bb6 This is actually working but the problem is that with this solution I loose form apps from the django (account, auth, socialaccounts, sites)