Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sending Data from Django view to model
I have JSON variable which I can get from Javascript.I want to save it in database.I am not able to write exact view function for it My models.py from django.db import models from django.utils import timezone from django.utils import simplejson as json class update_grid(models.Model): data = JSONField(null=True, blank=True) My View.py def save_grid(request): if request.method == 'POST': data = json.loads(request.body)# I want to send this variable to update_grid and save it return HttpResponse('success') # if everything is OK -
Type "unsigned" doesn't exist django
I am really new to Django, I have to query the database and have to take an average of a charfield (tday is charfield) so in order to cast the charfield to int I used extra() function as follows but it gave me an error. Following is my query and then the error: from django.db.models import Avg from django.db.models.functions import Cast tday=TableName.objects.filter(tday__contains="20090").extra({'tday_int':"CAST(tday as UNSIGNED)"}).order_by('-tday_int') The error: django.db.utils.ProgrammingError: type "unsigned" does not exist. Thanks in advance! -
Django: overriding insert, update, delete in a model
Sometimes you want to do something when there is an event for model (on create object, on update object, on delete object). There is a method you can override in Model called save. And it even has a parameter forced_insert which I first thought would always be set to a proper value meaning whether an object will be created or updated. But the parameter is optional and you cannot expect it to be right. Searching in source code of Model led me to methods _do_update and _do_insert, but the underscore at the beginning tells me that this method is not recommended for use. And it also have a lot of parameters which pollute code when you override it. The only solution left that I could find is using django.db.models.signals. But I believe they are meant to be used for external purposes like when you want to create a UserProfile on every User create. But I have some internal purposes like updating fields on update. Also using signals makes code look spreaded and harder to understand. -
Django dynamic localization of "translation strings"
a bit of background, I have a working project written in Django which is something like internet shop with a blog. For now, my customer needs an ability to add translations and new languages on the fly. The model related part can be easily done using one of many libraries (like django-modeltranslation, django-parler ...). The problem is with translatable strings and formatting. Updating translatable strings can be somehow covered by django-rosseta (works with .po, compiles them and reloads the server, but is it ok?). And how to handle adding new language without touching source code (settings.LANGUAGES section)? Ideally, all localization-related data should be stored in the database with some kind of caching. Any ideas? -
django authentification error
I am running into an error where I am logging in a user and it is supposed to redirect to details.html but instead the the url gets parsed but it stays at login.html. I believe there is a problem with the views.py. If there is a better way of doing this please let me know. Thanks views.py @login_required(login_url="http://127.0.0.1:8000/accounts/login/") def patientDetails(request, personalInfo_id): current_user = request.user if personalInfo_id == current_user.id: return render(request, 'personalInfo/details.html', {}) else: return render(request, 'personalInfo/login.html', {}) @login_required(login_url="http://127.0.0.1:8000/accounts/login/") def after_login(request): return HttpResponseRedirect('/personalInfo/details/%d/'%request.user.id) urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^details/$', views.after_login, name='patient'), url(r'^details/(?P<personalInfo_id>[0-9]+)/$', views.patientDetails), ] Picture of what is going wrong -
Django - KeyError when updating User within the Admin Panel
I've been following this tutorial and every time I attempt to save/update the user then I get the following error... KeyError at /admin/accounts/usermodel/1/change/ u'password' Full traceback here... Environment: Request Method: POST Request URL: http://localhost:8000/admin/accounts/usermodel/1/change/ Django Version: 1.11.7 Python Version: 2.7.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.gis', 'django.contrib.humanize', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.staticfiles', 'rest_framework', 'accounts', 'main', 'objects'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py" in wrapper 551. return self.admin_site.admin_view(view)(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/Library/Python/2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/Library/Python/2.7/site-packages/django/contrib/admin/sites.py" in inner 224. return view(request, *args, **kwargs) File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py" in change_view 1511. return self.changeform_view(request, object_id, form_url, extra_context) File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py" in changeform_view 1408. return self._changeform_view(request, object_id, form_url, extra_context) File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py" in _changeform_view 1440. if form.is_valid(): File "/Library/Python/2.7/site-packages/django/forms/forms.py" in is_valid 183. return self.is_bound and not self.errors File "/Library/Python/2.7/site-packages/django/forms/forms.py" in errors 175. self.full_clean() File "/Library/Python/2.7/site-packages/django/forms/forms.py" … -
PermissionError: [Errno 13] Permission denied in Django
I have encountered a very strange problem. I'm working with django, I create a directory on server, and try to save pickle file into it, this way: with open(path, 'wb') as output: pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL) And get: PermissionError: [Errno 13] Permission denied I tried to give all permissions to this directory, this way: os.chmod(save_full_path, stat.S_IWOTH | stat.S_IWUSR | stat.S_IWGRP) but this didn't help. Although directory seems to have all permissions(0o777), I still get this error. By the way, I have no problems with saving uploaded files to this directory. I'm very new to django, I would really appreciate if someone explained me what am I doing wrong. -
Can we automatically delete entry from database after specified time in Django?
I am not able to think the solution other than creating timer in one thread. Is there any more efficient than this one? -
Bug in production - A static file is corrupted for a specific user?
Sorry for the ambiguous title, I just couldn't find a better description of this bug. One of our users had problems with the site, and saw a Syntax Error in one of the Javascript files in the dev console. When he opened it, he saw it was corrupted: He sent me the contents of the file (went directly to the URL and saved with Ctrl+S) and when I opened it with Sublime it seemed to be nulled-out (the binary is all zeros). This only happened to him and it doesn't seem to go away, even after a full restart. I initially thought it was just a corrupted response and Chrome cached the file, but even with Shift+F5 he is still getting the problem. The user runs Chrome 64.0.3282.186 the server is running django on AWS. -
Django API and Front-End Separation
I am using Djnago for REST API. Currently, I am generating primitive web pages from the same Django project. I think it's in my interest to separate API logic and front end. What is a best way to do this? Should I create another Django app, that just calls this API and generates web pages from template or should I use some other framework for this? Thanks -
I'm new to geodjango. I run python manage.py makemigrations. The following error occurs:
(py35_64) E:\Ahas\GEODJANGO\geodjango>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Anaconda2\envs\py35_64\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 985, in _gcd_import File "<frozen importlib._bootstrap>", line 968, in _find_and_load File "<frozen importlib._bootstrap>", line 957, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 697, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\db\models\base.py", line 114, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\db\models\base.py", line 315, in add_to_class value.contribute_to_class(cls, name) File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\db\models\options.py", line 205, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\db\__init__.py", line 33, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\db\utils.py", line 202, in __getitem__ backend = load_backend(db['ENGINE']) File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\db\utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) File "C:\Anaconda2\envs\py35_64\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\contrib\gis\db\backends\postgis\base.py", line 6, in <module> from .features import DatabaseFeatures File … -
How to create function for an API function not belonging to any model class?
So I am using Django/DRF for my backend and I want the client (my web app) to be able to make an API call that looks up tags for an image using Google Cloud Vision API. Obviously, I don't want the client to have access to the API key, hence the server should perform the actual call to Google's API. What I'm struggling with currently is where to put this API function. Do I have to create a model for this (even though there is no db table) or is there some way around that? -
'to_field_name' argument on a ModelChoiceField() doesn't seem to be working
Well, pretty much what it says in the title. I'm creating a ModelChoiceField() in one of my Forms, like so: class FormCreatePlace(forms.ModelForm): (...) category = forms.ModelChoiceField(queryset=Category.objects.all(), to_field_name='name') (...) The Category model is defined like so: class Category(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=40) And yet the field itself on the HTML form insists on displaying the primary keys (a series of UUIDs) as the choices. What am I doing wrong? -
How Django stores emojis in mysql tables with utf8 charset?
I have a Django 1.4 app that was saving text in mysql database with utf8 charset. Everything worked fine, but I came across a problem when I wanted to read this data using ruby where strings with emojis were throwing invalid byte sequence in utf-8 exception. Quick search told me that I should've use utf8mb4 charset in mysql, but since these strings don't appear to be valid utf-8 at this moment, simple alter table changing the charset is not fixing the problem. How was Django saving these strings in the first place, making emojis work with utf8 (and not utf8mb4) charset work? -
Django filter choices by keywords
I am using django filter and I am having some issues. I have a filter for "colours" that I wish to have fixed choices for eg. blue, green, red. I would like to have a key, value pair that checks that if a keyword is in that colour, it matches. I am importing a product feed so the colour words may vary e.g blck, charcoal. I also have a filter for "brand" which shows all available brands, however I only want to render options available in that Category. filters.py import django_filters from .models import Product, Brand, Category, Colour, Size from django.forms import CheckboxSelectMultiple class ProductFilter(django_filters.FilterSet): search_price__gt = django_filters.NumberFilter(name='search_price', lookup_expr='gt') search_price__lt = django_filters.NumberFilter(name='search_price', lookup_expr='lt') brand_name = django_filters.filters.ModelMultipleChoiceFilter( label='Brand',widget=CheckboxSelectMultiple, queryset = Brand.objects.all()) colour = django_filters.filters.MultipleChoiceFilter(choices=Colour.COLOURS, label='Colour',widget=CheckboxSelectMultiple) size = django_filters.filters.ModelMultipleChoiceFilter( label='Size',widget=CheckboxSelectMultiple, queryset = Size.objects.all()) class Meta: model = Product fields = ['brand_name', 'colour', 'size'] models.py from django.db import models from mptt.models import MPTTModel, TreeForeignKey, TreeManager class Category(MPTTModel): regex = models.CharField(max_length=100, blank=True) name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.CASCADE) slug = models.SlugField() class MPTTMeta: order_insertion_by = ['name'] class Meta: unique_together = (('parent', 'slug',)) verbose_name_plural = 'categories' def get_slug_list(self): try: ancestors = self.get_ancestors(include_self=True) except: ancestors = [] else: ancestors = … -
Django - Serving statics with views and not with django.contrib.staticfiles
Im new in DJango and I need to change current static serving mode removing the /static Alias from Apache configuration (and relative STATIC_URL from default_settings) Alias /static/ /usr/local/app/static/ On django settings: STATIC_URL = '/static/' to a internal serving services using a local view. I have added a new constant in settings.py STATIC_WEB_ROOT = os.path.join(BASE_DIR, 'static/frontend/') urls.py from django.conf.urls.static import static url(r'^%sstatic/(?P<path>.*)$' % , static , {'document_root': STATIC_WEB_ROOT }, name='static.file.serve'), index.html <script type="text/javascript" src="{% url 'static.file.serve' 'frontend/js/jquery-3.2.1.min.js' %}" ></script> Unfortunally, I get a 404: "GET /static/frontend/js/jquery-3.2.1.min.js HTTP/1.1" 404 -
Add filename to formset for display purpose only
I have a model which contains a number of user uploaded files that other than the file itself also contain a description and some other meta information. class ArchiveFile(models.Model): archive_file = models.FileField(upload_to=grab_archive_folder, default=None, blank=False) description = models.CharField(max_length=255) What I want is for a user to (1) upload new files. And (2) be able to edit the descriptions of all files associated with the user, including the recently uploaded. The uploading of new files is done via AJAX / JQuery and new forms (as part of a formset) are generated dynamically. In order to do be able to edit the descriptions in an efficient matter, it would help for a user to know of what file it is changing the description, and so I would like the filename to be displayed. My initial solution was the following: forms.py class ArchiveDataForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['archive_file'].widget.attrs['disabled'] = True class Meta: model = ArchiveFile fields = ['archive_file','description'] template {% for archive_form in archive_formset %} {{ archive_form.archive_file.value }} {{ archive_form.description }} {% endfor %} My issue is that I am getting validation errors on the dynamically created forms, saying that no file is present. Which I suppose is correct since all I … -
Create post without model in django
Sorry for my english. I new in django, and i want create custom post. I have not model for this and i dont need create it. I cant understand how create normal post reqest in django. Bellow my try create it view: class CreateCustopPost(generics.GenericAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = CustomSerializer serializer: class CustomSerializer(serializers.ModelSerializer): type_report = serializers.CharField(max_length=23) client_token = serializers.CharField(max_length=128) year_p_start = serializers.DecimalField(max_digits=10, decimal_places=2) month_p_start = serializers.DecimalField(max_digits=10, decimal_places=2) day_p_start = serializers.DecimalField(max_digits=10, decimal_places=2) year_p_end = serializers.DecimalField(max_digits=10, decimal_places=2) month_p_end = serializers.DecimalField(max_digits=10, decimal_places=2) day_p_end = serializers.DecimalField(max_digits=10, decimal_places=2) class Meta: model = # i dont have model for this. fields = ('type_report', 'client_token', 'year_p_start', 'month_p_start', 'day_p_start', 'year_p_end', 'month_p_end', 'day_p_end') my qestion: what need typing in serializer class in model = ? -
Storing JSON variable in django database
In my app that uses Gridster I am changing the widget positions and then saving it as a json variable.I want to store this json variable in django database. For that I am not understanding how should I define a function in views.py and a class in models.py which can store the json variable My HTML/JS template is var URL = "{% url 'my_view_url' %}"; $('.js-seralize-update').on('click', function () { var s = gridster.serialize(); updated_grid=JSON.stringify(s); $('#log').val(updated_grid); function updategridster(){ var data = updated_grid; $.post(URL, data, function(response){ if(response === 'success'){ alert('Yay!'); } else{ alert('Error! :('); } }); } }); My views.py def save_grid(request): if request.method == 'POST': # Some code to get json variable and store it to model return HttpResponse('success') # if everything is OK I want to write some kind of class in models.py corresponding to view.py so that JSON variable can be saved -
Django : Waterfall method with spline display (no column)
I spent a lot of time on this problem: I notice that I am working on Django and Highcharts (chartit). I have a database that contains simulations results. I would like to cumulate these results on a chart in order to get : Simulation 1 -> Result Simulation 1 Simulation 2 -> Sum results simulation 1 + 2 Simulation 3 -> Sum results simulations 1 + 2 + 3 and so on... with the simulation number on the x axis. I have seen that the waterfall function exactly do that but is ploting column or brick. I would like to get a line or spline representation. Do you know an option or an other method to get this result ? Thank you very much !!! -
Django query latest()
I wan't to get the latest id of a table, and use this value as a filter Lastrun=Runid.objects.latest('id') query_hostinfo_results = HostinfoHist.objects.filter( runid = Lastrun ) if I enter the id manually, eg. runid = '1041' everything works fine, but I can't query for Lastrun I guess it's because I don't get a string or integer value back, but Runid object (1041) how I can get the value 1041 from this object cheers Funksen -
Two django project on the same ip address (server)
Is it possible to set two different django projects on the same IP address/server (Linode in this case)? For exmaple, django1_project running on www.example.com and django2_project on django2.example.com. This is preferable, but if this is not possible then how to make two djangos, i.e. one running on www.example.com/django1 and the second on www.example.com/django2? Do I need to adapt the settings.py, wsgi.py files or apache files (at /etc/apache2/sites-available) or something else? Thank you in advance for your help! -
Could not resolve URL for hyperlinked relationship using view name "profile-detail"
I am trying to customize django's User model and send one additional field while creating a new user through djsoer's create user end point. Here is my model.py from django.db import models from django.contrib.auth.models import PermissionsMixin, AbstractBaseUser, BaseUserManager class CustomAccountManager(BaseUserManager): def create_user(self, email, name, account_address, password): user = self.model(email=email, name=name, account_address=account_address, password=password) user.set_password(password) user.is_staff = False user.is_superuser = False user.save(using=self._db) return user def create_user(self, email,name, account_address, password): user = self.model(email=email, name=name, account_address=account_address, password=password) user.is_active = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user def get_by_natural_key(self, email_): print(email_) return self.get(email=email_) class Profile(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) account_address = models.CharField(max_length=30, blank=True) name = models.CharField(blank=True, null=True, max_length=150) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['account_address', 'password'] objects = CustomAccountManager() def get_short_name(self): return self.email def natural_key(self): return self.email def __str__(self): return self.email and my serializer.py is following from djoser.serializers import UserCreateSerializer as BaseUserRegistrationSerializer class UserRegistrationSerializer(BaseUserRegistrationSerializer): class Meta(BaseUserRegistrationSerializer.Meta): fields = ('url', 'id', 'email', 'name', 'account_address', 'password') and here is my urls.py from django.conf.urls import url, include from rest_framework.routers import DefaultRouter router = DefaultRouter() urlpatterns = [ url(r'^account/', include('djoser.urls')), ] But when I am trying to create a new user i am getting following error. any help is appreciated :) -
Which are some ways to grow strong Python programming skills and logic? [on hold]
I am not that good in programming, i want to upgrade my skills in python, Which are some ways to grow strong Python programming skills and logic? -
Django redirecting http -> https
I am running: python manage.py runserver localhost:44100 And this is redirecting me to https: » http http://localhost:44100/ HTTP/1.0 301 Moved Permanently Content-Type: text/html; charset=utf-8 Date: Mon, 05 Mar 2018 14:09:09 GMT Location: https://localhost:44100/ Server: WSGIServer/0.1 Python/2.7.14 X-Frame-Options: SAMEORIGIN Why / how is this happening? What setting does control whether Django accepts http / https?