Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access a function of view.py in from.py
How do I access a result of a view.py function inside form.py? I am trying to use the results of a function of view as input of a form field -
Django rest framework writable nested relations: data in list and unactive fields
this is my first project in Django Rest Framework and I stucked. I try to do writable nest relations to achieve this type of data: data = { 'name': 'Tom', 'Surname': 'DangerMouse', 'skills' : ['Python', 'Django'], 'employment_history' : [ {'copmany' : 'Jemset', 'role' : 'developer', 'from' : '12:06:2017', 'to' : '24:07:2017'} ], 'education' : [ {'university': 'CSbGU', 'year_of_graduation': '12:06:2017'}, ], } but in local host page data is in lists and arise "Lists are not currently supported in HTML input" problem. my models class Developers(models.Model): name = models.CharField(max_length=50) surname = models.CharField(max_length=30) class Education(models.Model): university = models.CharField(max_length=50) year_of_graduation = models.IntegerField() developers = models.ManyToManyField(Developers, related_name='education') class Empl_history(models.Model): company = models.CharField(max_length=50) role = models.CharField(max_length=30) fr = models.DateField(verbose_name='from') to = models.DateField() developers = models.ManyToManyField(Developers, related_name='employment_history') class Skills(models.Model): skills = models.CharField(max_length=100) developers = models.ManyToManyField(Developers, related_name='skills') my serializers class EmpSerializer(serializers.ModelSerializer): class Meta: model = Empl_history fields = ('company', 'role', 'from', 'to') class EduSerializer(serializers.ModelSerializer): class Meta: model = Education fields = ('university', 'year of graduation') class SkSerializer(serializers.ModelSerializer): class Meta: model = Skills fields = ('skills_choices', 'other skills') class DevSerializer(serializers.ModelSerializer): skills = SkSerializer(many=True) employment_history = EmpSerializer(many=True) education = EduSerializer(many=True) class Meta: model = Developers fields = ('name', 'surname', 'skills', 'education', 'employment_history') def create(self, validated_data): employment_history_data = validated_data.pop('employment_history') sk_data … -
Trying to learn inline formsets, not going well
I'm trying to get a very minimal inline formset added to a existing form. Basically I have the model Builing and Gallery with a foreign key to Building. I have already set up a basic BuildingCreateView that specifies the form building_form via form_class. I have created a simple GalleryFormSet but I can't get it show in the template. Is it really "necessary" to overwrite the view? # views.py from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import CreateView from .forms import BuildingForm from buildings.models import Building class BuildingCreateView(LoginRequiredMixin, CreateView): form_class = BuildingForm template_name = 'cms/building_form.html' # forms.py from django.contrib.gis.forms import OSMWidget, ModelForm, inlineformset_factory from buildings.models import Building, Gallery class BuildingForm(ModelForm): class Meta: model = Building fields = ['field', 'point', ...] widgets = { 'point': OSMWidget( attrs={ 'default_lat': 56, 'default_lon': 10, 'default_zoom': 7, } ) } class Media: css = { 'all': ( 'https://cdnjs.cloudflare.com/ajax/libs/ol3/3.20.1/ol.css', 'gis/css/ol3.css', ) } js = ( 'https://cdnjs.cloudflare.com/ajax/libs/ol3/3.20.1/ol.js', 'gis/js/OLMapWidget.js', ) GalleryFormSet = inlineformset_factory(Building, Gallery, fields=('image',)) # building_form.html {% extends "base.html" %} {% block head %} {{ block.super }} {{ form.media }} {% endblock %} {% block content %} <form enctype="multipart/form-data" method="post" action=""> {% csrf_token %} <ul> {{ form.as_ul }} </ul> <input type="submit" value="Submit"/> </form> <form method="post" action=""> {{ gallery_form.management_form }} … -
Google Chrome opens empty new window when clicking Django dev server link
I had a Django project running perfectly using Python 2.7. Now I switched to Python 3 and whenever I click the link shown when I start the Django development server, google chrome opens a new, empty window where previously it opened a new tab in the existing window (which also contained the web application I was trying to run). I'm not sure this has anything to do with switching Python versions because I remember seeing this issue before when I wasn't doing anything with Python. Does anybody have clue? It's probably something very simple. Cheers -
What is a modern approach to deploy Django app?
I am developing a django application and reached the stage where the app has to be deployed to the production. I do not have too much DevOps experience and hence was doing some research. However, most of the proposed methods were 6-7 years old. Therefore I was wondering if anyone could suggest the modern approach to ship the django-based product given my requirements: The application will be used by companies with 1-1000 employees. Each company will store sensitive data. There should be no more than 100 different companies. We have a scheduler to execute a few machine learning tasks in the background. Business logic is quite trivial, no fancy algorithms. More specifically: Should every company have its own instance running with separate database? If I run everything on a single server and DB, is it okay to store sensitive data of all companies on the same DB? If I run everything on a single server and DB, will the server be able to cope with the traffic given my requirements? Who would provide the best service? Which one is the easiest to set up and run? I have deployed a few apps on AWS, but it was quite clumsy and … -
Django 2, python 3.4 cannot decode urlsafe_base64_decode(uidb64)
i am trying to activate a user by email, email works, encoding works, i used an approach from django1.11 which was working successfully. In Django 1.11 the following decodes successfully to 28, where uidb64 = b'Mjg' force_text(urlsafe_base64_decode(uidb64)) In django 2 (2, 0, 0, 'final', 0) the above code decode does not work and results in an error django.utils.encoding.DjangoUnicodeDecodeError: 'utf-8' codec can't decode byte 0xc8 in position 1: invalid continuation byte. You passed in b'l\xc8\xe0' (<class 'bytes'>) I am also posting my views just in case from django.utils.encoding import force_bytes, force_text from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() # auth_login(request, user) message = render_to_string('user_activate_email.html', { 'user': user, 'domain': Site.objects.get_current().domain, 'uidb64': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) mail_subject = 'Activate your blog account.' to_email = form.cleaned_data.get('email') email = EmailMessage(mail_subject, message, to=[to_email]) email.send() messages.info( request, 'Activation link has been sent to your email!') # return redirect('home') return render(request, 'index.html') else: form = SignUpForm() return render(request, 'user_action.html', {'form': form}) def activate(request, uidb64, token): try: import pdb;pdb.set_trace() print('uidb64={}'.format(uidb64)) uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.refresh_from_db() user.is_active … -
Dependencies reference nonexistent parent node
I was advised to delete the migration files as I am trying to run 'makemigrations' and 'migrations' as I have a new model. I deleted only the last migration file and now it is throwing an error: Migration core.0099_book dependencies reference nonexistent parent node ('incentives', '0012_auto_20171214_1059') -
Obtain the username of a logged user in Django, inside a Form
I would like to obtain the name of the logged user inside a form of a Django App. I know how to do this in the views.py user_name = request.user.username How can I do the same inside the forms.py? Or there is a way to pass this information to access it in the forms.py? -
File Upload Handler gives chunk with size less than specified
A very unusual thing is happening with Django file upload handler. I followed the documentation to write a custom handler so I could encrypt raw_data as I received it and write it to the file object. I didn't change the default chunk_size which is 64KB. My code worked fine with small files. But when I send files greater than the chunk size, the raw_data I receive does not have a length of 65536 as it should be for 64 KB chunk size, rather it is somewhere between 64000 to 65000. This hurdle is preventing me from being able to encrypt large files. Help. -
Nose does not creating test databases
I am trying to run unittests using nose framework (command test specific desktop -x), but after starting I'm getting this: [14/Dec/2017 14:36:14 +0000] settings DEBUG DESKTOP_DB_TEST_NAME SET: hue_test [14/Dec/2017 14:36:14 +0000] settings DEBUG DESKTOP_DB_TEST_USER SET: hue_test [14/Dec/2017 14:36:14 +0000] manager DEBUG DefaultPluginManager load plugin flaky = flaky.flaky_nose_plugin:FlakyPlugin [14/Dec/2017 14:36:14 +0000] manager DEBUG DefaultPluginManager load plugin windmill = windmill.authoring.nose_plugin:WindmillNosePlugin nosetests desktop -x --cover-package=about,beeswax,filebrowser,hbase,help,impala,jobbrowser,jobsub,metastore,oozie,pig,proxy,query_history,rdbms,schema,search,security,spark,sqoop,useradmin,zookeeper,indexer,metadata,notebook,aws,hadoop,liboauth,liboozie,libopenid,librdbms,libsaml,libsentry,libsolr,libzookeeper --no-path-adjustment --traverse-namespace -x --verbosity=1 [14/Dec/2017 14:36:14 +0000] manager DEBUG DefaultPluginManager load plugin flaky = flaky.flaky_nose_plugin:FlakyPlugin [14/Dec/2017 14:36:14 +0000] manager DEBUG DefaultPluginManager load plugin windmill = windmill.authoring.nose_plugin:WindmillNosePlugin Creating test database for alias 'default'... Traceback (most recent call last): File "/home/bdemydov/Projects/roku/roku-hue-3-12/hue-3.12.0/build/env/bin/hue", line 9, in <module> load_entry_point('desktop==3.12.0', 'console_scripts', 'hue')() File "/home/bdemydov/Projects/roku/roku-hue-3-12/hue-3.12.0/desktop/core/src/desktop/manage_entry.py", line 59, in entry execute_from_command_line(sys.argv) File "/home/bdemydov/Projects/roku/roku-hue-3-12/hue-3.12.0/build/env/local/lib/python2.7/site-packages/Django-1.6.10-py2.7.egg/django/core/management/__init__.py", line 399, in execute_from_command_line utility.execute() File "/home/bdemydov/Projects/roku/roku-hue-3-12/hue-3.12.0/build/env/local/lib/python2.7/site-packages/Django-1.6.10-py2.7.egg/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/bdemydov/Projects/roku/roku-hue-3-12/hue-3.12.0/desktop/core/src/desktop/management/commands/test.py", line 108, in run_from_argv ret = test_runner.run_tests(nose_args) File "/home/bdemydov/Projects/roku/roku-hue-3-12/hue-3.12.0/desktop/core/src/desktop/lib/test_runners.py", line 102, in run_tests result = self.run_suite(nose_argv) File "/home/bdemydov/Projects/roku/roku-hue-3-12/hue-3.12.0/build/env/local/lib/python2.7/site-packages/django_nose-1.3-py2.7.egg/django_nose/runner.py", line 165, in run_suite addplugins=plugins_to_add) File "/home/bdemydov/Projects/roku/roku-hue-3-12/hue-3.12.0/build/env/local/lib/python2.7/site-packages/nose/core.py", line 121, in __init__ **extra_args) File "/usr/lib/python2.7/unittest/main.py", line 95, in __init__ self.runTests() ... I skipped part of traceback... File "/home/bdemydov/Projects/roku/roku-hue-3-12/hue-3.12.0/apps/useradmin/src/useradmin/models.py", line 244, in get_default_user_group return _get_user_group(useradmin.conf.DEFAULT_USER_GROUP.get(), is_add_permission, **kwargs) File "/home/bdemydov/Projects/roku/roku-hue-3-12/hue-3.12.0/build/env/local/lib/python2.7/site-packages/Django-1.6.10-py2.7.egg/django/db/backends/util.py", line 53, in execute return self.cursor.execute(sql, params) File "/home/bdemydov/Projects/roku/roku-hue-3-12/hue-3.12.0/build/env/local/lib/python2.7/site-packages/Django-1.6.10-py2.7.egg/django/db/backends/mysql/base.py", line 124, in execute return … -
Django: How to set a property in a model using @property
I'm trying to assign two properties to my User class. The first assigned property will be used in assigning the second property. Is this correct? I'm using the @property decorator but should I be using @my_attr.setter (like, @apps.setter) after I use @property? class User(n): group = models.ForeignKey(Brand, null=True, blank=True) is_admin = models.BooleanField(default=True) # assign the apps property (User.apps) @property def assign_apps(self): self.apps = get_user_apps(self.group, self.is_admin) # do I need to now assign the property? @apps.setter self.apps = get_user_apps(self.group, self.is_admin) # with User.apps, assign the apps_meta property (User.apps_meta) @property def assign_apps_meta(self): self.apps_meta = get_user_apps_meta(self.apps) # do I need to now assign the property? @apps_meta.setter ... -
Find field name that matches the passed string and set its value
In Django how can i find a field name in a model? Here's what i mean : my_field = 'message' MyTable.objects.filter(pk=user_id).update(my_field='new message') The MyTable model has a field named message. -
Django redirect with non-URL parameter
I have a view class FooDetailView(View): def get(request, *args): foo_id = int(args[0]) foo = Foo.objects.get(pk=foo_id) // do something and render the page And now I would like to add some message into this page. For example class FooFuncView(View): def get(request): // do something return redirect('foo-detail', foo_id, 'call Func successfully') Since my urls.py is simply url(r'^foo-detail/([1-9][0-9]*)/', FooDetailView.as_view(), name='foo-detail'), I get the error message becuase no reverse match Reverse for 'foo-detail' with arguments '(<id>, 'call Func successfully')' not found. 1 pattern(s) tried: ['tournament-detail/contestant/([1-9][0-9]*)/'] But I dont want the message shown in the url because it could be too long. I just want to simply render the page as FooDetailView does, and add extra message after different operation. It there any good way to achieve this? If not, any explantions for that? -
Django Foreign Key. Remove connection after one exact date
For example i have 2 models products.py class Product(models.Model): name = models.CharField(max_length=255) clients.py class Client(models.Model): name = models.CharField(max_length=255) client_product = models.ForeignKey(Product) client_product_expiry_date = models.DateTimeField() Now: Product name = Chocolate Client name = John client_product = Chocolate client_product_expiry_date = 2017.12.17 (after 3 days) After certain days (which was set in field client_product_expiry_date) This connection between client and product should be removed Is there any way how to realize it? -
How to gather data from cx_oracle and shown as bar chart in djangi
I have application use cx_oracle for connect to db Data fetched but i have problem in shown multiline barchart with data gather from sql My sample data : Day hour value 20171228 0 43645 20171228 1 674436 20171227 0 464556 20171227 1 466744 Bar chart must draw one line for each day I works with highchart but cannot sent data with this format -
ForeignKey object has no attribute model?
I am running the code below and get back an error saying 'ForengKey object has no attribute model'. What is wrong with this? I thought it only takes one argument, the foreignkey model? from django.db import models from incentives.models import Incentive slug = models.CharField(max_length=150) incentive = models.ForeignKey(Incentive) print(incentive) '''incentive = models.ForeignKey( Incentive, on_delete=models.CASCADE, verbose_name=__('')) -
Registration using e-mail, Django 2.0
I'm just a beginner, so i got some questions making my first project. I've got code in views: def signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Активация' message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) print(message) # здесь я смотрю какое сообщение отправляю to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Пожалуйста, подтвердите адрес электронной почты') else: form = SignupForm() return render(request, 'signup.html', {'form': form}) def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) # return redirect('home') return HttpResponse('Thank you for your email confirmation. Now you can login your account.') else: return HttpResponse('Activation link is invalid!') This code is from urls: from . import views from django.urls import path urlpatterns = [ path('', views.signup, name='signup'), path('activate/?P<uidb64>[0-9A-Za-z_\-]+/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'), ] The problem is that i always get invalid URL in my email. I think it is about new 'path' function, which may be used is <int:uidb64> but not really sure. Thank for your help! -
The custom page 404 is not showing but the page 500 is showing
When I load an inexistent url the page 404 does not show instead the page 500 is shown. Below my setups. Could you please guide me to turn Django on to show 404 page? Thanks Ubuntu Server 16.04 ; Python 3.5.2 ; Django 2.0 cat contatoproj/urls.py from django.contrib import admin from django.urls import path from django.conf.urls import url from django.conf.urls import include from django.conf.urls import handler404, handler500 from contatoapp import views from contatoapp import views as myapp_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index, name='index'), url(r'^contato', views.contato, name='contato'), ] handler404 = myapp_views.error_404 handler500 = myapp_views.error_500 cat contatoapp/views.py from django.shortcuts import render from django.http import HttpResponse from django.template import RequestContext from django.contrib import messages from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.conf import settings from contatoapp.forms import ContatoForm def error_404(request): data = {} return render(request, 'ops404.html', data) def error_500(request): data = {} return render(request, 'ops500.html', data) $ ls -la templates/ops* -rwxr-xr-x 1 admweb admweb 614 Dec 13 15:31 templates/ops404.html -rwxr-xr-x 1 admweb admweb 614 Dec 13 15:29 templates/ops500.html cat contatoproj/settings.py DEBUG = False ALLOWED_HOSTS = ['*'] -
Authentication with django-rest-framework-social-oauth2
I apologize in advance for my English, i try use django-rest-framework-social-oauth2 for api Authentication. I followed the steps in this tutorial https://github.com/PhilipGarnero/django-rest-framework-social-oauth2 if go to http://127.0.0.1:8000/auth/login/facebook/ after that djangoadmin does not ask login and password, but if go to other my api route, then i get an error saying "detail": "Authentication credentials were not provided." my settings REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'rest_framework_social_oauth2.authentication.SocialAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] } TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] thanks in advance -
reach object detail in template using Listview class django 2
im following a totorial and im tying to show each object peroperty (that are saved in db) in my template html file like this {% for obj in objects_list %} <p>{{ obj.name }} => {{ obj.location }} <b>timecreated</b>==> {{ obj.timestamp }} <b>time updated</b>==> {{ obj.updated }}</p> {% endfor %} i should get slug in url and this url http://localhost:8000/restaurants/shomal/ /shomal/ is our slug and we must watch object detail where category is equl to = shomal but i cant see for loop result in template but when in print queryset i can see object detail in terminal why cant i reach object detail in template for loop in my app view file i have from django.shortcuts import render from django.shortcuts import HttpResponse from django.views import View from django.views.generic import TemplateView, ListView from .models import Restaurant from django.db.models import Q def restaurants_listview(request,): template_name = 'restaurants/restaurants_list.html' query_set = Restaurant.objects.all() context = { "objects_list": query_set } return render(request, template_name, context) class RestaurantListView(ListView): template_name = 'restaurants/restaurants_list.html' def get_queryset(self): print(self.kwargs) slug = self.kwargs.get("slug") if slug: queryset = Restaurant.objects.filter( Q(category__iexact=slug)| Q(category__icontains=slug) ) print(queryset) # return queryset else: queryset = Restaurant.objects.all() return queryset and in django url.py file i have from django.contrib import admin from django.urls import … -
Querying Binary data using Django and PostgreSQL
I am trying to print out to the console the actual content value (which is html) of the field 'htmlfile': 16543. (See below) So far I am able to print out the whole row using .values() method Here is what I am getting in my python shell: >>> >>> Htmlfiles.objects.values()[0] {'id': 1, 'name': 'error.html', 'htmlfile': 16543} >>> I want to print out the content of 16543.. I have scanned through the Django QuerySet docs so many times and still cannot find the right method.. Any assistance would be greatly appreciated. -
When I attempt to insert data to my connected database it shows another database and raises an error
In Django, when I attempt to insert data to my connected database it shows another database and raises an error. I connect to database 'test'. Then I create tables using Python. Then I drop all tables in Navicat. Then I change connection to database 'books'. Then I do the same action. I get this error: OperationalError: (1049, "Unknown database 'test'") My settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'books', 'USER':'root', 'PASSWORD':'1234', 'HOST':'localhost', 'PORT':'3306' } } from books.models import Publisher p1 = Publisher(name='Apress', address='2855 Telegraph Avenue', ... city='Berkeley', state_province='CA', country='U.S.A.', ... website='http://www.apress.com/') p1.save() -
Getting a validation error on filtering inlines on Django Admin
There are an Invoice model and two Pricing models to calculate billing amount. I want detail pages of Invoice item on Django admin to show the only one inline determined by the attribute of Invoice model (pricing_type). To achieve above, I wrote the code below but it raised an error(django.core.exceptions.ValidationError: ['ManagementForm data is missing or has been tampered with']) when I saved Invoice item on Django admin with the modified pricing_type. How can I make inlines on detail pages switchable? class PricingAInline(admin.TabularInline): model = PricingA class PricingBInline(admin.TabularInline): model = PricingB @admin.register(Invoice) class InvoiceAdmin(admin.ModelAdmin): inlines = [PricingAInline, PricingBInline] def get_formsets_with_inlines(self, request, obj=None): if isinstance(inline, PricingAInline) and obj.pricing_type.name == 'basic': yield inline.get_formset(request, obj), inline elif isinstance(inline, PricingBInline) and obj.pricing_type.name == 'advanced': yield inline.get_formset(request, obj), inline continue -
How to connect your social media account to your profile in django-allauth?
I let the registration on the site via email and password. When i login I want to connect to my creating django profile, my social account in facebook. Can someone faced with this? -
I would like to add condition to Django DetailView
I am using Django Generic view, DetailView. But I'd like to block users to access to detail post who did not email_confirmed yet. I have a email_confirmed field in User model. My code is : @method_decorator(login_required(login_url='/login/'), name='dispatch') class RecruitView(generic.DetailView): model = Recruit template_name = 'recruit.html' and I want to add : if not request.user.email_confirmed: error_message = "you did not confirmed yet. please check your email." return render(request, 'info.html', {'error_message': error_message}) else: pass How can I add this condition to DetailView? (I tried to override 'as_view' but I don't know how to do it)