Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wrong status code returned by Django Rest Framework
When adding the following code to the simple example here why isn't the correct status code returned? # ViewSets define the view behavior. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer @detail_route(methods=['get', 'post'], url_path='test') def test(self, request, pk=None): return Response(status=204) In both the Django server and in chrome the returned status code is 200, though in the rest framework UI the code is 204 as expected. -
Django slug is not an attribute of table
So i have this code: #admin.py class DocAdmin(admin.ModelAdmin): model = Doc prepopulated_fields = {"slug": ("title",)} list_display = ('title', 'get_category') #models.py class Doc(models.Model): title = models.CharField(max_length=50) text = RichTextField() slug = models.SlugField(max_length=50, unique=True) category = models.ForeignKey('juristdoc.Category') def __str__(self): return self.title class Category(models.Model): title = models.CharField(max_length=50, db_index=True) def __str__(self): return self.title And it's saying: The value of 'prepopulated_fields' refers to 'slug', which is not an attribute of 'juristdoc.Category', but i set the model to Doc in the admin.py. What am I doing wrong? -
Timepicker javascript validate one input date to be today or before?
I want to not accept that the date given be after RIGHT now, Im using django datepicker, I was trying the addmethod but i couldnt get to the success, i have some code: var fech = document.getElementById('datepicker').value; var a = new Date(); var aho = (d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getFullYear()); jQuery.validator.addMethod("greaterStart", function(value, element, aho) { return this.optional(fech) || new Date(fech) < new Date($(aho).val()); }, 'Ingrese una fecha de hoy o antes.'); The vars "fech" and "aho" throw me the dates that i want to compare. I have already checked some posts but no one helps me, i cant compare the dates with if, because i want to use the validator $("#miForm").validate({ errorClass: "claserror", validClass: "clasevalida", errorElement: 'erele', rules: { nacimiento: { required: true } } } -
Can't get username out of UserProfile instance Django 1.8
I create new notification in views.py . I save who_did attribute as Foreign Key of UserProfile, but later in template, where I transfer Notification object via ajax as serialized JSON object, I require username of that user. Therefore I tried to save username attribute via model method, but it doesn't work for me. I tried different stuff, in current variant I am getting name 'who_did' is not defined in log, despite when I print who_did in views.py notify function as below, it's printing user profile objects well. If I try who_did.profile.username or who_did.username it claims having no such attributes, thought such things work fine in other parts of code(well, second may be wrong for sure). Could you please explain what am I doing wrong? notification = Notification(whom=whom_user_profile_instance,who_did=who_liked_user_profile_instance,choice_afl="L",question_answered_object=question_is_liked, creation_date = timezone.now()) notification.save() Notification and UserProfile in models.py: class Notification(models.Model): whom = models.ForeignKey('UserProfile', related_name='whom_NOTIFICATION') NOTIFICATION_CHOICES = ( ('A', 'Answered'), ('F', 'Followed'), ('L', 'Liked'), ) who_did = models.ForeignKey('UserProfile', related_name='who_did_NOTIFICATION', blank=True) who_did_username = models.CharField(max_length=1000, blank=True, null=True) choice_afl = models.CharField(max_length=1, choices=NOTIFICATION_CHOICES) question_answered_object = models.ForeignKey('Question', related_name="question_answered_object_NOTIFICATION", blank=True, null=True) creation_date = models.DateTimeField(blank=True, null=True) def save_username(self): user = who_did self.who_did_username = user.profile.username UserProfile model: class UserProfile(models.Model): user = models.OneToOneField(User) there_are_new_notifications = models.BooleanField(default=False) how_much_new_notifications = models.IntegerField(null=True,blank=True,default=0) follows = models.ManyToManyField('self', … -
Curl link with django tastypie with ApiKey authorization and Django REST Framework
My goal si to read data via API that I have created with django tastypie. It is working great with and without authentication. I tested it with Postman. Problem that I am having is how to do CURL with authentication. If I do without authentication curl http://127.0.0.1:8000/api/v1/spaceship/?format=json I have 200 Successful response and I can see the JSON feed. But if I do with authentication resources.py from django.contrib.auth.models import User from tastypie.resources import ModelResource from main.models import Spaceship from tastypie.authentication import ApiKeyAuthentication from django.db.models import signals from tastypie.models import create_api_key signals.post_save.connect(create_api_key, sender=User) class SpaceshipResource(ModelResource): class Meta: queryset = Spaceship.objects.all() resource_name = 'spaceship' allowed_methods = ['get'] authentication = ApiKeyAuthentication() In postman if I add Authentication ApiKey user:343jh43k2j4h3k24h, it works. "343jh43k2j4h3k24h" is ApiKey created in Django Admin. What would be the proper CURL sentence to pass user with ApiKey that I got 200 Response and I can see the JSON data and parse it later? Something like this I am not sure how to write it properly: curl -H "Authorization: user 343jh43k2j4h3k24h" 'http://127.0.0.1:8000/api/v1/spaceship/?format=json' -
Nginx (403 forbidden) for media files
Deploying my web app (Nginx, Gunicorn, Django) on Ubuntu 16.10 I get a 403 error when clients try to load files to the server. Files are supposed to be saved in /var/www/annotator/media/dmitrybaranchuk/ I've read a lot of topics about the similar issue however nothing helped. I'm almost positive this is the problem with nginx / permissions / users. Maybe someone knows how I can fix it. The main information is described below. Error Logs Safari Web Inspector: [Error] Failed to load resource: the server responded with a status of 403 (Forbidden) (dmitrybaranchuk, line 0) nginx-error.log: [error] 10713#10713: *5 directory index of "/var/www/annotator/media/dmitrybaranchuk/" is forbidden, client: 31.173.80.174, server: 138.197.16.71, request: "POST /media/dmitrybaranchuk/ HTTP/1.1", host: "138.197.16.71", referrer: "http://138.197.16.71/" /var/log/nginx/error.log: empty Info Nginx processes: root - master process /usr/sbin/nginx -g daemon on; master_process on; www-data - worker process /var/www permissions: /var/www and every directory/file inside has permission: 777, user: www-data, group: www-data. SELinux: Disabled /etc/nginx/sites-enabled/annotator server { listen 80; server_name 138.197.16.71; access_log /home/dmitrybaranchuk/pose_annotator/logs/nginx-access.log; error_log /home/dmitrybaranchuk/pose_annotator/logs/nginx-error.log; location /static/ { alias /home/dmitrybaranchuk/pose_annotator/static/; expires 30d; } location /media/ { alias /var/www/annotator/media/; } location / { autoindex on; proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } /etc/nginx/nginx.conf user www-data; worker_processes auto; pid … -
JS files upload queue using Django block
I have a Django project, and a HTML template like this. {% extends "base.html" %} {% block content %} {% if user.is_authenticated %} <script type="text/javascript" src="/static/js/second.js"></script> <!-- ... Imagine I have a file named first.js in base.html. The question is that second.js seems to load BEFORE first.js which seems counter-intuitive to me. Do I have any control over the load queue of js files ? Besides, it seems strange to me that first.js loads after second.js, one reason being using libraries, like, say, jquery.js which I use in second.js. I am confused. Can anyone shed light on this ? -
Django templates: output float with all decimal places
how can I output this number in django templates x = 0.000015 1) {{x}} output is: 1,5e-05 2) {{x|stringformat:"f"}} output is: 0.000015 which is not localized, there should be comma! I need output to be localized and keep all decimal places. I can't believe that django can't handle such a simple task using built-in tools. -
set to call python function in Javascript
i'm developing a web-base chatbot application. i've developed it using Django Framework and the REST to create the API and a connection point between the java script and the python. indexs.js: $('.message-submit').click(function() { UserInput = $('.message-input').val(); var chatbot ={user_iput: UserInput}; $.ajax({ type: "POST", url: "http://127.0.0.1:8000/chat/api/", data: chatbot,}); insertMessage();}); function chatMessage() { if ($('.message-input').val() != '') { return false;} $('<div class="message loading new"><figure class="avatar"><img src="https://s13.postimg.org/whea1mgif/icon.png" /></figure><span></span> </div>').appendTo($('.mCSB_container')); updateScrollbar(); setTimeout(function() { Chat= #i want here to call the chatting function in the main_chatbot.py $('<div class="message new"><figure class="avatar"><img src="https://s13.postimg.org/whea1mgif/icon.png" /></figure>' + Chat + '</div>').appendTo($('.mCSB_container')).addClass('new'); setDate(); updateScrollbar(); }, 1000 + (Math.random() * 20) * 100); main_chatbot.py: def run_chatting(): H = ' '.join(cursor.execute('SELECT user_iput FROM chat_chat ORDER BY id DESC LIMIT 1').fetchone()) B = cursor.execute('SELECT Respond FROM Welcoming_Engine ORDER BY RANDOM()').fetchone() return B So, basically the javascript will post the user input, then the main_chatbot.py will generate the Chat value. so far the javascript can post the user input to the API and what my problem is i want to call the chatting function. PS: the two files are in the same folder. -
Django Rest Ordering custom
I'm using django rest framework and I would like order with custom method. So, when i call this url for example : http://127.0.0.1:8000/api/sets/?ordering=partMissing It's possible to call a custom method because I would like order with the number of part missing by snippet. I made count the sum of number of part in the many to many field. Thank you in advance for your answers. -
AttributeError: 'str' object has no attribute 'resolve'
I am trying to use Django-recurrence module. Without the javascript_catalog under "setting up internationalization" according to instruction : # If you already have a js_info_dict dictionary, just add # 'recurrence' to the existing 'packages' tuple. js_info_dict = { 'packages': ('recurrence', ), } # jsi18n can be anything you like here urlpatterns = patterns( '', (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict), ) All I see even before internationalization, is below: - The upper part of the reccurrence "javascript-image" is not showing. The green text part(Add Rule and Add date) is the only thing showing: +Add rule+Add date What I am expecting according to documentation is shown below: app/urls.py js_info_dict = { 'packages': ('recurrence', ), } urlpatterns = patterns(#'', (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict), url(r'^sms/$', CreateSMS_Sch.as_view(), name='CreateSMS_Sch'), app/forms.py class ScheduleConfRoom(ModelForm): class Meta: model = Schedule fields = ('name', 'room', 'message', 'recurrences',) widgets = { 'message': Textarea(attrs={'cols': 25, 'rows': 6}), } app/views.py class CreateConfRoom_Sch(CreateView): form_class = ScheduleConfRoom template_name = "schedule.html" success_url = '/' app/models.py class Schedule(models.Model): name = models.CharField(max_length=30, default='Example') room = models.ForeignKey(Room) # default='Empty') message = models.CharField(max_length=918) recurrences = RecurrenceField() schedule.html <form method="POST" action="{% url 'upload_file' %}" > {% csrf_token %} {{ form.media }} {{ form.as_p }} <button type="submit">Submit</button> </form> Please help!!! What did I do wrong? -
dockerized django: static tag in templates not detecting the present static files
I have a django project I am running using docker. My Dockerfile looks like this: FROM python:2-onbuild EXPOSE 80 CMD ["/bin/bash", "./run.sh"] The docker-compose.yml looks like: db: image: postgres:9.5 environment: - POSTGRES_DB=db_name - POSTGRES_PASSWORD=db_password web: build: . volumes: - ./:/usr/src/app ports: - '5000:80' links: - db environment: - 'DATABASE_URL=postgres://postgres:db_password@db:5432/db_name' and my run.sh script looks like: #!/usr/bin/env bash python manage.py migrate --fake-initial --noinput --settings=$DJANGO_SETTINGS_MODULE python manage.py collectstatic --noinput --settings=$DJANGO_SETTINGS_MODULE exec gunicorn --bind=0.0.0.0:80 project.wsgi \ --workers=3\ --log-level=info \ --log-file=-\ --access-logfile=-\ --error-logfile=-\ --timeout 30\ --reload My issue is, I can't get the static files. Even after executing the docker-compose run web ./manage.py collectstatic command the template still doesn't detect the static files despite docker-compose run web ls static showing the files are present. what could I be doing wrong? -
Does my Django view qualify as a web service?
Sorry if it is a silly question: I'm writing a Django view that returns a response in json format. One user can get the response by invoking the corresponding url. Does my API qualify as a web service? If no, what's missing? -
Django relating models directly
I'm not sure if I'm going the correct way about this but I am looking for a way to simply relate two models to each other (not specific instances of a model like a foreign key but the entire model). The Django app is for keeping track of an inventory of different pieces of equipment and service logs of when they were tested etc. This is my current setup: models.py class EquipmentBase(models.Model): common fields class Meta: abstract = True class EquipmentServiceBase(models.Model): common fields class Meta: abstract = True class EquipmentA(EquipmentBase): specific fields class EquipmentB(EquipmentBase): specific fields class EquipmentAService(EquipmentServiceBase): equipment_id = models.ForeignKey(EquipmentA) other fields class EquipmentBService(EquipmentServiceBase): equipment_id - models.ForeignKey(EquipmentB) other fields Only in my actual case there are lots more the 2 type of equipment. I want to be able to relate for example model EquipmentB to EquipmentBService in a generic way so that I can use the same views for all Equipment and all EquipmentService. Up to now I have been using a method for getting the __class__ and the appending or removing 'Service' before passing it as an argument to a url or view and this just feels wrong. I looked at generic relations and they seemed a bit … -
How to programmatically check status of celery beat process
I'm using some celery queues with my django (1.9) project. I'm building a "status" view which reflects the status of the various celery queues currently serving the project. This can be done nicely by using the inspect() function: status = celery_app.control.inspect().stats() The above gives me a detailed dictionary with great stats. In addition, I have a celery beat process running in the background serving some special queues. I would like to have a similar way to show the status of this process in the django "status" view I'm building. I haven't been able to find a way to do this and the worker process doesn't appear in the regular stats view as far as I can tell. Any help would be great. -
Get all the object that are referenced by the current ID in views attribute
My problem is that nothing is looping. -
How to capture highlighted text and pass the text to database in Django?
I am writing a Django app to analyze the sentiment of content. Below are aims I would like to achieve: At Template: I would like to highlight some text in the content and define the sentiment (e.g. positive / negative) nature of the text. Database: highlighted text and sentiment will be input. -
Error while creating form [on hold]
What is wrong? i created django form for add posts https://tutorial.djangogirls.org/en/django_forms/ Like doing everything on tutorial But all the errors come and go every time NoReverseMatch at /post/new/ Reverse for 'blog.views.post_new' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Request Method: GET Request URL: http://127.0.0.1:8000/post/new/ Django Version: 1.10.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'blog.views.post_new' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Exception Location: /home/arthur/develop/hb/myvenv/lib/python3.5/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 392 Python Executable: /home/arthur/develop/hb/myvenv/bin/python Python Version: 3.5.2 Python Path: ['/home/arthur/develop/lol', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/home/arthur/develop/hb/myvenv/lib/python3.5/site-packages'] Server time: Сб, 3 Дек 2016 18:12:44 +0300 Error during template rendering In template /home/arthur/develop/lol/blog/templates/blog/post_edit.html, error at line 0 Reverse for 'blog.views.post_new' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] 1 {% extends 'blog/base.html' %} 2 3 {% block content %} 4 <h1>New post</h1> 5 <form method="POST" class="post-form">{% csrf_token %} 6 {{ form.as_p }} 7 <button type="submit" class="save btn btn-default">Save</button> 8 </form> 9 {% endblock %} Traceback Switch to copy-and-paste view /home/arthur/develop/hb/myvenv/lib/python3.5/site-packages/django/core/handlers/exception.py in inner response = get_response(request) Please help me -
How can submit form with array fields and process on view?
I am trying to submit form with array fields and process on Django view. Also, I want to compare the submitted form data with correct answer table data. question.html: <form method="post" class="form-inline"> {% csrf_token %} {% for question in questions %} <h3>{{ question.title }}</h3> <div class="radio"> <label class="radio-inline"> <input type="radio" name="ans[{{ question.id }}]"> {{ question.option.0 }} </label> </div> <div class="radio"> <label class="radio-inline"> <input type="radio" name="ans[{{ question.id }}]"> {{ question.option.1 }} </label> </div> <div class="radio"> <label class="radio-inline"> <input type="radio" name="ans[{{ question.id }}]"> {{ question.option.2 }} </label> </div> {% endfor %} <button type="submit" class="btn btn-success" name="ans_submit">Submit</button> </form> view.py: if request.method == 'POST': if(request.POST.get('ans_submit')): temp_context["submitted_answers"] = request.POST.get("ans", "") # Receive as an array? Expecting to get expert advice. Thanks -
Django: 2 Foreign key in 1 table
i am new in Django, i want to create 1 table orders and make there 2 ForiegnKey (1 to User Model another to Product)It is posiible? Example: Class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) thx fo help -
django 1.10 password to be used with flask
I have a django project which i want to move to flask. The problem is to encrypt and decrypt password the same way django does. Will that be possible, to implement the same encryption and decryption as in django 1.10. That is i want to create and verify password in same manner in flask as it is done with django. Googling gave me passlib but the doc is not clear about the django version(1.10).Thanks. -
Docker with Django/PostgreSQL
I'm a novice on Docker and I actually try this tutorial: https://docs.docker.com/compose/django/ There are several things that I don't understand: The "code" folder is never created. Once the container is launched with the "docker-compose up" command, how can I access to the postgreSQL command line ? In the tutorial, at the "Create a Django project" part, the first point is "Change to the root of your project directory." But if I understand correctly the tutorial, I'm already in this folder. Someone can help me ? thanks by advance. -
Using ElasticSearch as Database/Storage with Django
I am trying to use ElasticSearch as a NoSQL database in my Django project. The end goal is to plug Kibana on the other side and be able to visualize my data there. I do not have a choice of adding another database and using ElasticSearch only for indexing as my project is plugging to an existing infrastructure. So I installed: django-haystack elasticsearch I was expecting to not need SQLite (or any other database) for storage and to use ElasticSearch as a NoSQL storage (is that wrong?) I added the Haystack connections settings to my project settings and then, looked at getting rid of "DATABASES" or replacing it with values pointing to my ElasticSearch with no success :( Here is what I'm stuck with: settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'haystack' }, } On all the answers I could find on StackOverflow and code snippets I would never see these DATABASES settings changed, so I assume people were using a database for storage and ElasticSearch only for their search engine / indexing which is not what I am looking for. Is there a … -
django-autocomplete-light, choice form is not allowed
I'm trying to make a django project with django-autocomplete-light app and I'm stuck on creating objects. I've added such form field to my model form: members = forms.ModelChoiceField( queryset=User.objects.all(), widget=autocomplete.ModelSelect2Multiple( url='users-autocomplete', ), ) The model looks like: class UserGroup(models.Model): group_name = models.CharField(max_length=50, blank=True) members = models.ManyToManyField(User, related_name="members", blank=True) create_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) teacher = models.ForeignKey(User, related_name="teacher", blank=True) related_groups = models.ManyToManyField("self", blank=True) def save(self, *args, **kwargs): self.media_path = "/media/"+slugify(self.group_name) super(UserGroup, self).save(*args, **kwargs) def get_media_file(self): return self.media_path def __str__(self): return self.group_name + " UserGroup" And when I'm trying to submit the data, I'm getting some erros after validating this form on server side - Select a valid choice. That choice is not one of the available choices. Suggesting and autocompleting works fine, I can mark the models that are created already. I've printed the submitted data of related_groups: https://codeshare.io/5PlAw5 XXX UserGroup is generated by str method in UserGroup as I suppose. Maybe there shoud be something else passed, like id? How i can specify these available choices? -
GeoDjango & SpatiaLite - filtering nearby objects
models.py has User and Business model that have this field: location = PointField(geography=True) I'm getting via Geocode service of Google Maps coordinates (in EPSG 4326) from address which user specified, and then I'm saving it in that field above (also EPSG 4326). That applies for both User and Business object. Now, what I want is to get all Business objects within specified radius (of 1km), based on location of user: Business.gis.filter(location__distance_lt=(request.user.location, D(km=1))) But it doesn't work, it returns me this error: ValueError: SpatiaLite does not support distance queries on geometry fields with a geodetic coordinate system. Distance objects; use a numeric value of your distance in degrees instead. So, does anyone know how to properly solve this? Thanks in advance!