Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - Updating a model using model.ModelViewSet
How do I update a model using using the Django Rest Framework? I have the following model/serializer/view definitions: foo/models.py class FooBar (models.Model): title = models.CharField(max_length=255,null=False) def __unicode__(self): return self.title foo/serializers.py from rest_framework import serializers from foo.models import FooBar class FooBarSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() class Meta: model = FooBar fields = ('id','title') read_only_fields = ['id'] foo/views.py from rest_framework import viewsets from foo.models import FooBar from foo.serializers import FooBarSerializer class FooViewSet(viewsets.ModelViewSet): queryset = FooBar.objects.order_by('id') serializer_class = FooBarSerializer I am using angular in this project and I am able to create a new record by saying: data = {'title':'New Foo Item'} $http.post(/api/v1/foo/, data ); How do I update a record? The following code results in a new record being created. data = {'title':'New Foo Item', 'id':1} $http.post(`/api/v1/foo/`, data ); I have tried using $http.post and $http.push and both result in a 405 "Method not allowed" error. I have also tried using this object id in the url with no luck: $http.post(`/api/v1/foo/${data.id}/`, data ); -
django DJA with swagger setting content-type
I want to use the JSON API format for our API and django-rest-framework-json-api seems to work perfectly for that. However, I also use swagger. Now DJA follows content-negotiation-clients Loading the swagger docs goes fine however when I want to try something it does not follows the JSON API content negotiation. When I change the curl command and run it in the shell it goes fine. How can I change Django swagger to add the Content-Type: 'application/vdn.api+json' ? ( it is basically this first problem django-rest-framework-json-api/issues , however, she does not state how she solved that issue only the second issue) -
Django: best way to convert data from model to view
My django app displays the objects from database in table view. The problem is that these objects (models) are pretty complex: the have 50+ fields. Nearly for each field I have to do some formatting: conver phone numbers from int 71234567689 to "+7 (123) 456789" display long prices with spaces: "7 000 000" instead of "7000000" construct full address from several fields like "street", "house" and so on (logic if pretty complex with several if-else-s) and so on Django templating language has several useful tags for simple cases but I guess is not suitable in general case (like mine) for serious formatting. Create the @property-s in model class is also not an option because the question is about rendering and is not related to model. So I guess I should do my conversions in view: create dict for each obj, fill with converted data and pass to template. But! The model has a lot of fields and I don't want to copy them all :) Moreover, it would be great to preserve model structure to use it in django template (say, regroup) and query set laziness. So the greatest way would be to instruct django "how to render". Is it … -
Django authentication not working in production, but works locally. Model doesn't use OnetoOnefield
Super user creation works fine and i can access them in the admin pannel. When users however create an account they are added as users but are not propagated into the FacebookProfile model (therefore i cant add their id, webpull etc..) (they propagate fine in development with sqllite3) I'm using mysql on azure. models.py from django.db import models from django.forms import ModelForm from django.contrib.auth.models import User from django import forms class FacebookProfile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) id = models.PositiveIntegerField(primary_key = True) webpull= models.CharField(max_length =1000, null = True) score = models.PositiveIntegerField(default = 0, editable = True) times_called = models.PositiveIntegerField(default = 0, editable = True) level = models.FloatField(default = 0, editable =True) my forms for facebook user forms.py from django import forms from django.contrib.auth.models import User from .models import FacebookProfile #facebook api linkage class FacebookUserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'first_name', 'last_name',) class FacebookProfileForm(forms.ModelForm): class Meta: model = FacebookProfile fields = ('id', 'year_formed', 'webpull',) my custom authentication system auth_backend.py from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User class PasswordlessAuthBackend(ModelBackend): def authenticate(self, username = None): try: return User.objects.get(username = username) except: return None my views from where I'm processing the entered parameters from Facebook API and storing them … -
IIS Windows Authentication working for Domain Admins only
I have a site developed in Python 2.7 (Django 1.9.6) deployed on IIS 7.5 Windows 7. I have configured Windows Authentication on site level which is working locally on the server, but from intranet site is keep prompting for User credentials, here if I enter Domain User account it will give me 401 - Unauthorized: Access is denied due to invalid credentials. And if I enter Domain Admin account I am able to browse the site successfully. Below is my site level configuration, on server level I have enabled Anonymous Authentication enabled. Site Authentication Authentication Providers -
Calculate the sum of model properties in Django
I have a model Order which has a property that calculates an order_total based on OrderItems linked by foreign key. I would like to calculate the sum of a number of Order instances' order_total properties. Is there a way of doing this? class Order(models.Model): customer = models.ForeignKey(Customer) placed = models.DateField() ... def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) order_total = property(get_total_cost) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name="items") product = models.ForeignKey(Product, related_name="order_items") quantity = models.PositiveIntegerField(default=1) ... def get_cost(self): return self.product.price * self.quantity This is my query: >>> Order.objects.all().aggregate(Sum("order_total")) Which returns this error: django.core.exceptions.FieldError: Cannot resolve keyword 'order_total' into field. Choices are: created, customer, customer_id, id, items, paid -
How to modify a boolean field model in Django?
I'm learning django about one month, and I'm trying to apply an activate/deactivate feature for my posts on a blog app. Here is my model. My desire is be able to activate the post to show it in a template but how can I change(set) the value of is_activate field through the view.py? Here is how I did my model: class Post(models.Model): title = models.CharField(max_length=250) slug = models.SlugField(max_length=250) body = models.TextField() is_activate = models.BooleanField(default=False) Summarizing: I need click in a buttom and activate a post and then show it in a template with another activate posts -
Reference field's default function in Django model's method
There is a model with a field that should be auto-populated with a fixed-length random identifier: from django.db import models from django.utils.crypto import get_random_string def get_random_string_fixed(): return get_random_string(length=20) class Post(models.Model): identifier = models.CharField(unique=True, default=get_random_string_fixed) In order to unsure that the generate value is indeed unique, I want regenerate it in the save method, if such value already exists: def save(self, *args, **kwargs): if not self.pk: while Post.objects.filter(identifier=self.identifier).exists(): self.identifier = get_random_string_fixed() super().save(*args, **kwargs) The problem with this implementation is that get_random_string_fixed is hardcoded in the save() method. If at some point I decide to choose a different default function for this field, I'll have to change it in several places, which is a bad practice. Is there a way of referencing the function assigned to the default attribute of a field in a model's method, without hardcoding the name of the function? -
Double save records tp database when "save as new" in django admin
I have a folowing problem when using django admin interface: When someone click for new article 'Save as new' not once, but for example made double click, or even a triple click(!), it creates 2 or 3 records in database. So my question is how to prevent this behavior in django admin? -
Django models -> what is the best approach to access 2 seprated models
i am developing a small app for sharing . to reduce database hit i need a relationship between 2 models (Followers) and (Share) these are my models class Follow(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, models.DO_NOTHING, blank=True, null=True , related_name="user_follower") class Shared(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, models.DO_NOTHING, blank=True, null=True , related_name="user_shared") class Profile(models.Model): id = models.AutoField(primary_key=True) follow = models.ManyToManyField(Follow) user = models.OneToOneField(User, models.DO_NOTHING, blank=True,null=True , related_name="profile") class Notes(models.Model): id = models.AutoField(primary_key=True) shared = models.ManyToManyField(Shared) now i wanna do something like this in my django view def return_users_note_shared_with(request): followers = request.user.profile.follow.all() return render(request , 'note.html',{ 'followers':followers}) in note.html how can i check if this note has been share with other users . i know there is some relationship required in models but i can not figure this out any help will be appropriated :D -
Pycharm 2016.3.2 debugger not working. django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I've a Django (version 1.10.5) application running with python 3.6 and i'm using Virtualenv. Running the application with ./manage.py runserver i've no error, but when i try to run in debug i got django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Here it is the pycharm debugging configuration: I am using win7. I try to add import django and after that django.setup() but no efect. I got this error in debugger. Traceback (most recent call last): File "C:\Program Files (x86)\JetBrains\PyCharm 2016.3.2\helpers\pydev\pydevd.py", line 1596, in globals = debugger.run(setup['file'], None, None, is_module) File "C:\Program Files (x86)\JetBrains\PyCharm 2016.3.2\helpers\pydev\pydevd.py", line 974, in run pydev_imports.execfile(file, globals, locals) # execute the script File "C:\Program Files (x86)\JetBrains\PyCharm 2016.3.2\helpers\pydev_pydev_imps_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "C:/mira_website/manageDb/permissions.py", line 3, in from rest_framework import permissions File "C:\Python36-32\lib\site-packages\rest_framework\permissions.py", line 8, in from rest_framework.compat import is_authenticated File "C:\Python36-32\lib\site-packages\rest_framework\compat.py", line 210, in import guardian.shortcuts # Fixes #1624 File "C:\Python36-32\lib\site-packages\guardian\shortcuts.py", line 6, in from django.contrib.auth.models import Group, Permission File "C:\Python36-32\lib\site-packages\django\contrib\auth\models.py", line 4, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Python36-32\lib\site-packages\django\contrib\auth\base_user.py", line 52, in class AbstractBaseUser(models.Model): File "C:\Python36-32\lib\site-packages\django\db\models\base.py", line 105, in new app_config = apps.get_containing_app_config(module) File "C:\Python36-32\lib\site-packages\django\apps\registry.py", line 237, in get_containing_app_config self.check_apps_ready() File "C:\Python36-32\lib\site-packages\django\apps\registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: … -
No Access to Django Admin on Pythonanywhere
I did Django Girls blog tutorial, and it worked perfectly on my local machine, including signing into Admin and adding blog posts. I uploaded to pythonanywhere, set up properly with mysql, did migrations which worked, the html all works for multiple apps, even Admin login html, BUT I cannot login even though I registered a superuser on pythonanywhere. I need some help with this, folks. I've exhausted all options. Here is my site with apps: miller2082.pythonanywhere.com/admin and other apps: miller2082.pythonanywhere.com/pronunciation_training -
working with form in Django
This is page that designed to submit the answers of my MCQ(multiple choice question) App in Django. {% extends 'quiz/base.html' %} {% block content%} <h1>You are at quiz page</h1> <form action="{% url 'quiz:process_data' %}" method="post"> {% csrf_token %} {% for question in question_set %} <h3>{{question.id}}.{{question.question_text }}</h3> {% for option in question.options_set.all %} <input type="radio" name="choice" value="{{ option.options}}" > {{option.options}}<br> {% endfor %} {% endfor %} <input type="Submit" name="Submit"> </form> {% endblock%} The problem is that it can only select the answer of one question. There is something wrong with my form. Thank you -
Possibility to upload Wagtail documents to a subfolder of /documents/
I am serving my Django-Wagtail media files trough Amazon S3 and now I reached a point where I need to define a customized Document Class which creates "restricted" documents (only accesible if you are logged). This documents will have a special access that will say to my S3 bucket "hey! just deliver this files If they are requested from this "foo_url" but not from anywhere else", since they will be shown to logged users only. I thought of this to prevent restricted urls to spread out. That's why I am trying to define this Wagtail Document class to be stored in a subfolder of /documents/ and just tell Amazon what to do with that subfolder. dummy_code_that_doesnt_work: class RestrictedDocument(Document): def get_upload_to(self, filename): folder_name = 'restricted' filename = self.file.field.storage.get_valid_name(filename) return os.path.join(folder_name, filename) """ Snippet containing restricted documents """ @register_snippet @python_2_unicode_compatible # provide equivalent __unicode__ and __str__ methods on Python 2 class FooSnipet(models.Model): rectricted_document_1 = models.ForeignKey( 'RestrictedDocument', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) rectricted_document_2 = models.ForeignKey( 'RestrictedDocument', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) .... and many more .... Maybe I am overcomplicating all this and there is another way of doing. Any suggestion will be super welcome! Thank you veeery much :) -
Django always tries to establish SSL connection with localhost
After setting DEBUG = False, and SECURE_SSL_REDIRECT = True and deploying a version on my app to the server, I wish now to develop further locally. The problem is, I think at one point I forgot to remove the SECURE_SSL_REDIRECT = True from settings.py, and I ran the local dev server with heroku local. My local browser always tries not to connect to localhost with SSL, so it just hangs. I tried removing the site-specific cookies for localhost in the browser settings (Chrome) but localhost now still always tries to establish an SSL connection. I am trying just to get back to using a non-SSL local connection for development. Any Ideas? Django version 1.10.2 Heroku Thanks -
What is the best way for implementing API using Django? Also the issue of cleaning temporary files
As title, I would like to know what is the best way to implement an API through Django. In my application, users will input some string or a file with some details configuration through a HTML form. In backhand, I would temporarily save some input information and intermediate files, and response the result. However, I don't know if I need to handle the file names. That is, whether I need to encode these input files into different file names or Django will automatically handle this. At the same time, I want to know how to handle removing these temporary files. Thank you ! -
Foreign key to Abstract Base Class in Django
I'm trying to have a foreign key to an Abstract Base Class. I know it is not possible and one way to work around this would be to use a GenericForeignKey. I would like to avoid that and find a simpler way, maybe by redesigning my models but can't find any. class Country(models.Model): name = models.CharField(max_length=50) class City(models.Model): name = models.CharField(max_length=50) class Meta: abstract = True class Capital(City): country = models.OneToOneField(Country) class OtherCity(City): country = models.ForeignKey(Country) class Citizen(models.Model): name = models.CharField(max_length=50) lives_in = models.ForeignKey(City) I used an ABC for City in the first place because I need to ensure there is only one capital per country with the OneToOneField. Maybe I could use a different implementation and still be sure of that ? -
select django orm columns dynamically
I have a report table with 10 fields/columns. I want to allow the user to dynamically select which columns he wants in the report. Can this be done in Django ORM Example If user wants column1 and column2 then it should be like this obj = ReportTable.objects.values('column1', 'column2') If user wants column5, column6, column9, column10 then it should be like this obj = ReportTable.objects.values('column5', 'column6', 'column9', 'column10') Is this doable in django orm or should I use cursor or raw queries -
Django rest-framework-csv and d3 to serve up process data
Background So I have process data which I have collected from industrial plants, which is stored in csv format. I created a Django model to emulate the data structure and then imported this data in the created django database. Now the amount of data is massive, when plotting I need to extract useful amounts of the data. At current I am using rest-framework-csv to serve up this data to d3 by dynamically generated csv files, which is the easy part. I created a group model such that I can select groups of data, such that I can select a relevant group of data for each graph. class Group(models.Model): GroupName = models.TextField() TagName = models.TextField() The data imported from the process is described by a model like below, although there are 100s of tags. Generally which process plants, we would like to see these 3 parameters (PV, SP & CV) on a graph to evaluate the control. class Data(models.Model): Time = models.DateTimeField() Tag1PV = models.FloatField() Tag1SP = models.FloatField() Tag1CV = models.FloatField() and so on.... Questions Q1, My Serializer is hardcoded at the moment, but I need to generate many csv files, one for each graph. My current thinking is that I … -
Django Haystack autocomplete jquery formatting
I'm a bit confused with the formatting of the data, I tried the documentation, both JQuery and Haystack with no luck. I have already setup autocomplete, and when I type: autocomplete/?search=foo The result is: {"results": ["foo1", "foo2", "foo3", "foo4", "foo5"]} When I try to retrieve this and use it as source for JQuery autocomplete like so: $('#autocomplete').autocomplete({ source: function (request, response) { $.getJSON("/autocomplete/?search=" + request.term, function (data) { response(data); }); } }); No result is shown. If I create a variable like so: x = ["foo1", "foo2", "foo3", "foo4", "foo5"]; and then call it like so: $("#autocomplete").autocomplete({ source: x, }); It works perfectly fine. To be clear, I understand that results from Haystack is the variable name, just like x. The problem is, I can't seem to get it to work with JQuery. I looked at many questions in SO but couldn't find a solution. Looking for some direction. -
TypeError at /comments/post/ get_comment_create_data() got an unexpected keyword argument 'site_id'
I have a problem with django-comments-xtd when I try to work with django 1.9. I'm following this tutorial. When I work with Django 1.8 everything is fine. But if I use Django 1.9 I get the error when I send a message. TypeError at /comments/post/ get_comment_create_data() got an unexpected keyword argument 'site_id' Traceback: File "/home/olga/.virtualenvs/my_site/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/home/olga/.virtualenvs/my_site/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/olga/.virtualenvs/my_site/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/home/olga/.virtualenvs/my_site/lib/python3.4/site-packages/django/views/decorators/http.py" in inner 42. return func(request, *args, **kwargs) File "/home/olga/.virtualenvs/my_site/lib/python3.4/site-packages/django_comments/views/comments.py" in post_comment 108. comment = form.get_comment_object(site_id=get_current_site(request).id) File "/home/olga/.virtualenvs/my_site/lib/python3.4/site-packages/django_comments/forms.py" in get_comment_object 121. new = CommentModel(**self.get_comment_create_data(site_id=site_id)) Exception Type: TypeError at /comments/post/ Exception Value: get_comment_create_data() got an unexpected keyword argument 'site_id' I set the SITE_ID in settings.py In theory django-comments-xtd is compatible with django 1.9 I've got the same issue when I work with my own project (dj 1.9). And even when I run the example (dj 1.9) for tutorial. Everything is fine until I send a message. -
'form_filters' is not a registered tag library. Must be one of: (error in production)
I have this error when i try to run my site. The app is registered in my settings.py and the venv is set correctly. In local it works perfectly... I used apache 2.4.7 and django 1.10.5. -
django, pyenv, uwsgi - ModuleNotFoundError: No module named 'django'
I have the following vassal configuration in /etc/uwsgi/vassals/gsd.ini: [uwsgi] plugins = python env = DJANGO_SETTINGS_MODULE=%n.settings virtualenv = /home/toogy/.pyenv/versions/%n chdir = /home/webapps/%n module = %n.wsgi:application master = true vacuum = true pidfile = /tmp/uwsgi-%n.pid socket = /tmp/uwsgi-%n.sock daemonize = /var/log/uwsgi/%n.log chmod-socket = 666 uid = toogy gid = toogy Here is the uwsgi log I get Tue Feb 7 10:49:12 2017 - received message 1 from emperor ...gracefully killing workers... Gracefully killing worker 1 (pid: 31406)... worker 1 buried after 1 seconds binary reloading uWSGI... chdir() to /etc/uwsgi/vassals closing all non-uwsgi socket fds > 2 (max_fd = 1024)... found fd 3 mapped to socket 0 (/tmp/uwsgi-gsd.sock) running /usr/bin/uwsgi *** has_emperor mode detected (fd: 7) *** [uWSGI] getting INI configuration from gsd.ini *** Starting uWSGI 2.0.14 (64bit) on [Tue Feb 7 10:49:13 2017] *** compiled with version: 6.3.1 20170109 on 18 January 2017 00:35:47 os: Linux-3.14.32-xxxx-grs-ipv6-64 #7 SMP Wed Jan 27 18:05:09 CET 2016 nodename: renard machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 4 current working directory: /etc/uwsgi/vassals detected binary path: /usr/bin/uwsgi chdir() to /home/webapps/gsd your processes number limit is 15700 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: … -
python: return int(value) ValueError: invalid literal for int() with base 10: ''
Help, I keep getting ValueError: invalid literal for int() with base 10: '' when I try to migrate my models. this is my model from django.db import models from datetime import date class PoliceAssurance(models.Model): numPolice = models.AutoField(primary_key=True) raison = models.CharField(max_length=50) tel = models.CharField(max_length=20) email = models.CharField(max_length=50) interlocuteur = models.CharField(max_length=50) dateDebut = models.CharField(max_length=50) dateFin = models.CharField(max_length=50) tiers = models.CharField(max_length=50) formule = models.CharField(max_length=50) territoire = models.CharField(max_length=50) exclusions = models.CharField(max_length=50) complement = models.CharField(max_length=50) -
How do I change my queryset using AJAX?
I want to be able to change my comments queryset without page refresh. Here are the querysets: comment_list = Comment.objects.filter().order_by('-score__upvotes') new_comments_list = Comment.objects.filter().order_by('-timestamp') Then my template is {% for comment in comment_list %} {{ comment }} ... Is there any way to change {% for comment in comment_list %} to {% for comment in new_comments_list %} using AJAX (no page refresh)? Or possibly changing the value of comment_list to equal Comment.objects.filter().order_by('-timestamp')?