Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fill detail of Foriegn key used in other models of Python class
I have the following user and order class: class User(models.Model): id = models.AutoField(db_column='id', primary_key=True) password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.IntegerField() Order table class Order(models.Model): orderid = models.AutoField(db_column='orderId', primary_key=True) orderuserid = models.ForeignKey('User', models.DO_NOTHING,related_name='users', db_column='orderUserId') orderamount = models.IntegerField(db_column='orderAmount', blank=True, null=True) Now my question is that I want to create a new order from existing user , so how can I auto fill the orderuserid field in the Order table when create a order by the user. I am confused how the serializer will work now. -
Django REST Framework get list view by FK
class Project(models.Model): user = models.ForeignKey(USER) status = models.CharField(max_length=100, choices=(('NEW', 'NEW'), ('CLOSE', 'CLOSE'), ('CANCEL', 'CANCEL'))) class Investment(models.Model): project = models.ForeignKey(Project) status = models.CharField(max_length=100, choices=(('BOOKED', 'BOOKED'), ('FAIL', 'FAIL'), ('CANCEL', 'CANCEL'))) class ProjectSerializer(serializers.ModelSerializer): investment = InvestmentSerializer(many=True) class Meta: model = Project fields = ('id', 'status', 'investment') class ProjectView(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): serializer_class = ProjectSerializer def get_queryset(self): return Project.objects.filter(user=self.request.user, status__in= ['CLOSE', 'CANCEL'], investment__status__in=["FAIL", "CANCEL"])) I want a project view, only investment's status is 'FAIL' or 'CANCEL', but above code all investment in the result not only status is 'FAIL' or 'CANCEL', how to do this? -
Storing user specific documents in user folder
I am using django as backend technology and has hosted my server on aws ec2 instance. I want to store user specific data like profile picture, invoice etc. I thought of creating different folders with user id as the name of those folders and putting the content in them. I thought of using S3 for storage. But S3 doesn't support folder structure. I want to know best practices of storing user specific documents on server. I do not want to store them on the same server as it will cause problem when I will be scaling. -
Why are the templates requiring that I import jQuery in every template page, despite having it once in base.html?
My base.html already includes jQuery. And my templates extend base, but won't allow the jquery to work unless I re-insert the script tag in each template. What's going on? base.html: ... {% block javascript %} <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> {% endblock javascript %} detail.html: {% extends 'base.html' %} {% load static %} {% block content %} ... {% endblock content %} {% block javascript %} <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> I am required to place the script tag here again, despite having it in base. {% endblock javascript %} -
Design pattern for dynamic forms in Django
I have a set of models which are similar logically to the ones below. The models are the structure of a form with groups of elements that we can add to and change as required. The elements are HTML form elements like radio buttons, checkboxes and textareas that a user can fill out. class Form(models.Model): name = models.CharField(max_length=50) class FormGroup(models.Model): name = models.CharField(max_length=50) form = models.ForeignKey('forms.Form', related_name="groups") class FormGroupElements(models.Model): name = models.CharField(max_length=50) type = models.CharField(max_length=50, choices=['checkbox', 'radio', 'textarea']) group = models.ForeignKey('forms.FormGroup', related_name="elements") For this example, we are working on a "Dining Survey" with just the Entree section. When serialized, it looks like this. { 'form-id': '6be0ac8, 'name': "Entree Survey", 'groups':[ { 'id': '9cba9e2', 'name': "I enjoyed my entree", 'elements':[ { 'id': '009c8a2', 'name': "Yes", 'type': "radio", }, { 'id': 'c02da91', 'name': "No", 'type': "radio", } ] }, { 'id': '0f91c10', 'name': "The meal I had for my entree was", 'elements':[ { 'id': 3, 'name': "Meal", 'type': "textarea", }, ] }, ] } This renders out into HTML which looks like this: <input type="radio" name="9cba9e2-i-enjoyed-my-entree" value="Yes" /> <input type="radio" name="9cba9e2-i-enjoyed-my-entree" value="No" /> <input type="text" name="0f91c10-the-meal-i-had-for-my-entree-was" value="" /> I would like to save their response in a format that allows them to … -
What function can be used instread of CASCADE
I created books app, It has Publisher and Books models. In books Model i assigned a foreignkey for Publisher using on_delete = models.CASCADE. Actually i don't want to use this on_delete function. because if i delete data from parent table it will delete data on child table also. But I am getting TypeError: __init__() missing 1 required positional argument: 'on_delete' if i don't use on_delete = models.CASCADE. -
Django: `unique_together` doens't work properly when the number of unique field sets over 2?
models.py class Symbol(BaseModel): currency = models.CharField(max_length=10) class Tick(BaseModel) symbol = models.ForeignKey("Symbol") trade_datetime = models.DateTimeField() trade_coin_volume = models.DecimalField(max_digits=15, decimal_places=8) trade_price = models.DecimalField(max_digits=15, decimal_places=8) is_ask = models.BooleanField("is_ask?") class Meta: unique_together = (('symbol', 'trade_coin_volume', 'trade_price', 'is_ask', 'trade_datetime'), ) As you can see above code, I set unique_together with 4 fields. And I test Tick-model generate code like below: # the dictionary variable that i want to store in DB In [10]: tick_dict Out[10]: { 'askBid': 'BID', 'changePrice': 908000.0, 'tradeTimeKst': '15:21:59', 'tradeDateKst': '2018-02-06', 'tradePrice': 6924000.0, 'tradeVolume': 0.0143 } Try to save (date_time is properly preprocessed): Tick.objects.create( symbol=symbol, trade_datetime=date_time, trade_coin_volume=tick_dict['tradeVolume'], trade_price=tick_dict['tradePrice'], is_ask=tick_dict['askBid']=="ASK", ) It occured IntegrityError: IntegrityError: duplicate key value violates unique constraint "tick_symbol_id_trade_coin_vol_a7999e46_uniq" DETAIL: Key (symbol_id, trade_coin_volume, trade_price, is_ask, trade_datetime)=(3388, 0.01430000, 6924000.00000000, f, 2018-02-06 06:21:59+00) already exists. So, I looked up which data row has same fields (total 4 fields): In [11]: Tick.objects.filter(is_ask=False, trade_coin_volume=Decimal(0.01430000)) Out[11]: <QuerySet []> Nothing with same data exists in my database! What's wrong with it? The strange thing that I found out is the name of unique constraint: tick_symbol_id_trade_coin_vol_a7999e46_uniq, which seems to indicate only symbol_id and trade_coin_vol...? Need your advices -
Using Checkbox in django admin
I'm implementing project in django. I have two models that Studio and Template. class Studio(models.Model): studio_id = models.IntegerField() class Template(models.Model): template_id = models.IntegerField() Now I want to map templates with Studios. One Studio can have multiple templates. so I created model that StudioTemplateMapping. class StudioTemplateMapping(models.Model): studio = models.ForeignKey(Studio) template = models.ForeignKey(Template) in admin.py class StudioAdmin(admin.ModelAdmin): list_display = ('studio_id', ) class TemplateAdmin(admin.ModelAdmin): list_display = ('template_id', ) class StudioTemplateMappingAdmin(admin.ModelAdmin): list_display = ('studio', 'template) admin.studio.register(Studio, StudioAdmin) admin.studio.register(Template, TemplateAdmin) admin.studio.register(StudioTemplateMapping, StudioTemplateMappingAdmin) when I allocate studio with template, it should display all existing templates in checkbox. I could not displayed in checkbox view. could anyone suggest any way to display all templates in checkbox view and allocate with studio. -
Wagtail Feedback form in homepage
Tell me how to get the Wagtail form not in its separate template but on the homepage, since I do not need lending and another page. I can not find how to specify it in the get_context of the Home model -
can I create progressive web app in django framework or wagtail which one is best?
I am trying to build for website so I need to know that.what is progressive web app? and all devices or only moniter. -
Ckeditor/ django 2.0 admin body input disappeared
Hi I recently installed Ckeditor on django 2.0, turns out some of the css and js files are not loading properly, I manage to get Ck read the files but now my admin body input was disappeared. missing-admin-body As I am pretty new to django, I was wondering if I were doing anything wrong in the setting. (try to make a blog, url + generic view set up) setting.py > INSTALLED_APPS = [ 'personal', 'blog', 'contact', 'widget_tweaks', 'ckeditor', 'ckeditor_uploader', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], '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', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'EST' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' STATIC_DIR … -
How do I redirect errors like 404 or 500 or 403 to a custom error page in apache httpd?
I have created a Django project but I am using Apache as the webserver. Can anyone tell me how can I redirect an error code like 404 or 500 or 400 to a custom error html page instead of getting a standard error message on page in case an error was to occur ? I've tried the solutions available on the web but none seems to work -
Empty routes in DRF(Django Rest Framework)
I'm trying to register a simple method into a DRF and I'm having some problems. The route is not showing in API Explorer. It's probably something simple that I'm missing.. How can I get the register route to show in the API? Resuts (empty) GET /api/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept {} Urls from django.conf.urls import url, include from django.contrib import admin from rest_framework import routers from rest_framework_jwt.views import obtain_jwt_token from reservations.views.homepage import HomepageView from users.views import UserViewSet """ API routes """ router = routers.DefaultRouter() router.register(r'test', UserViewSet, base_name='users') """ Route patterns """ urlpatterns = [ url(r'^$', HomepageView.as_view(), name='homepage'), url(r'^api/', include(router.urls)), url(r'^api-token-auth/', obtain_jwt_token), url(r'^admin/', admin.site.urls), ] Viewset # -*- coding: utf-8 -*- from __future__ import unicode_literals from rest_framework import viewsets from rest_framework.response import Response class UserViewSet(viewsets.ViewSet): def register(self, request): return Response({ 'status': 'User registered' }) -
Django: BootstrapCDN or
I am trying to make my first website. I am using Django for it. I have a question related to inclusion of css/js from Bootstrap. What is the difference between installing it and linking it using BootstrapCDN? What happens if that link is no longer accessible ? Will it affect the website? Can't I just include those files in statics directory? I have this in base.hml file of my app: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <link rel="stylesheet" href="{% static 'flatly.css' %}"> <link rel="stylesheet" href="{% static 'main.css' %}"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"> <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script> I am a beginner, sorry if it is too naive to ask such a question. Thank you. -
Django: filtering on `DecimalField` doesn't work well?
This is my model: class Tick(BaseModel): . . trade_coin_volume = models.DecimalField( max_digits=15, decimal_places=8, ) trade_price = models.DecimalField( max_digits=15, decimal_places=8, ) . . I print out trade_coin_volume of all Tick objects: In [9]: for tick in Tick.objects.all(): ...: print(tick.trade_coin_volume) ...: 0.02120853 0.05000000 0.26628998 0.19354556 0.32299392 0.72599405 0.05955935 0.05354201 0.00767441 0.05101970 0.20967645 0.10000001 0.00500000 0.00899999 0.15274410 0.32104315 0.00300000 0.22695384 0.05000000 0.13894616 0.00631414 0.07967759 0.28592241 0.23765636 0.05777923 0.08883787 0.05000000 0.14535185 As you can see above, there are some 0.05000000 values. But when I filter Tick objects based on this field, In [11]: Tick.objects.filter(trade_coin_volume=0.05) Out[11]: <QuerySet []> In [12]: Tick.objects.filter(trade_coin_volume=0.05000000) Out[12]: <QuerySet []> It doesn't show anything! Why does it happen? -
How to test get_success_url in CreateView in Django
I am trying to write a test for the get_success_url method in a CreateView, to make sure it redirects to the newly created page. But the response status code is 405 instead of 302 as I expected. def get_success_url(self): return reverse_lazy('blog:blog-detail', kwargs={'slug': self.object.slug}) -
How to make django login_required decorator raise HTTP401 exception
I use Django login_required decorator, but i don't need login_required redirect to login url instead of raising HTTP401 Unauthorized exception. -
Is there a way to see in the console what objects the queries retrieved by implementing a middleware?
I managed to print out in the console the number of queries, the time it took to complete them and the raw SQL itself by using a middleware and connection.queries. How can I also see in the console what objects the queries retrieved? -
Error in Django 2.0 tutorial, part 7 -- is this a bug
When I follow the 2.0 tutorial, on part 7, I noticed there is an error symbol under "PUBLISHED RECENTLY" in this screenshot: The "was_published_attribute" was set to True in the tutorial. But if set it to False, it can show "False" correctly. Is this a bug? Any suggestion of fixing or workaround? Many thanks! I apologize that I describe this question poorly in the title. I appreciate it if anyone can suggest me a better title. -
Why is Django's authenticate taking too long to resolve?
I have a Django project that uses Django Rest Framework and its @list_route among others to make api calls from my front-end. The very first api call I make is: website.com/api/staffs/authenticate The endpoint code that catches that is: @list_route(permission_classes=(AllowAny,)) def authenticate(self, request): if request.user.is_authenticated: if is_staff_or_admin(request.user): return Response(StaffSerializer(request.user).data) data = {'detail': AuthenticationFailed.default_detail} return Response(status=status.HTTP_401_UNAUTHORIZED, data=data) That block of code takes a whopping 30-42 seconds to resolve! Any idea what might be causing this slowdown? -
django registration form does not save information
I am new to django . here I want to register user and I have a problem whenever the user hit signup button in registration.html nothing happens and when I go to the admin section no user saved so here are my codes note : all functions and templates works as expected , I think the problem in UserFormView or urls.py views.py : from django.http import Http404 from .models import Category, Item , Order from django.shortcuts import render, redirect from django.core.urlresolvers import reverse_lazy from django.contrib.auth import authenticate , login from django.views import generic from django.views.generic import View from .forms import UsrForm class IndexView(generic.ListView) : template_name = 'res/home.html' context_object_name = 'all_categories' def get_queryset(self): return Category.objects.all() def detail(request, category_name): try: category = Category.objects.get(category_title = category_name) all_categories = Category.objects.all() items = category.items.all() except Category.DoesNotExist: raise Http404("Category does not exist") return render(request, 'res/menu.html', {'items': items,'all_categories': all_categories}) class UserFormView(View): form_class = UsrForm template_name = 'res/registration.html' def get(self, request): form = self.form_class(None) return render(request , self.template_name, {'form' : form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() user = authenticate(username=username , password=password) if user is not None: if user.is_active: login(request , user) return redirect('res') return … -
What is the advantage of using a Django bootstrap module over linking to bootstrap files directly?
I see there are Django bootstrap modules (e.g. crispy_forms, django_bootstrap). I am trying to decide whether to use a module or link directly to bootstrap files in a base html file like the following: <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script I have an understanding that with the modules I would do the styling in the code. With using bootstrap directly, I am thinking I have to style it in the template files. I am trying to see reasons why I should be using a module. Also, with the bootstrap modules would I be able to use all bootstrap features? -
What's the difference between Django ModelForm and models.Model?
I am learning Django but cannot understand ModelForm ans models.Model, could anyone explain the difference between them? Thanks! -
No module named 'social_django' when creating superuser
I'm running a django project and I get this error when I try to add a superuser with the command python manage.py createsuperuser the error I get is >File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) >File "/home/boidot/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() >File "/home/boidot/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() >File "/home/boidot/anaconda3/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) >File "/home/boidot/anaconda3/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) >File "/home/boidot/anaconda3/lib/python3.6/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) >File "/home/boidot/anaconda3/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) >File "<frozen importlib._bootstrap>", line 994, in _gcd_import >File "<frozen importlib._bootstrap>", line 971, in _find_and_load >File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'social_django' howerever I think I installed all the required packages in a virtual environment. the result of pip freeze certifi==2018.1.18 chardet==3.0.4 click==6.7 dash==0.19.0 dash-core-components==0.14.0 dash-html-components==0.8.0 dash-renderer==0.11.1 dash-table-experiments==0.5.4 decorator==4.2.1 defusedxml==0.5.0 Django==2.0.2 django-admin==1.1.1 django-excel-response2==2.0.8 django-six==1.0.4 django-social-auth==0.7.28 Flask==0.12.2 Flask-Compress==1.4.0 httplib2==0.10.3 idna==2.6 ipython-genutils==0.2.0 itsdangerous==0.24 Jinja2==2.10 jsonschema==2.6.0 jupyter-core==4.4.0 MarkupSafe==1.0 nbformat==4.4.0 numpy==1.14.0 oauth2==1.9.0.post1 oauthlib==2.0.6 panda==0.3.1 pandas==0.22.0 plotly==2.3.0 PyJWT==1.5.3 python-dateutil==2.6.1 python-openid==2.2.5 python-social-auth==0.3.6 python3-openid==3.1.0 pytz==2017.3 requests==2.18.4 requests-oauthlib==0.8.0 screen==1.0.1 six==1.11.0 social-auth-app-django==2.1.0 social-auth-core==1.6.0 traitlets==4.3.2 urllib3==1.22 Werkzeug==0.14.1 xlwt==1.3.0 I don't have the social_django in the pip freeze result, however when I run pip3 install social_django I get Could not find a version … -
Publish Messages to Exchanges in RabbitMQ with Celery
I have written a Django-Project which cues different tasks async via my_task.delay(). The problem is as the project is getting bigger it is really difficult to route the tasks properly - I started to write tasks which only purpose is to combine different tasks, which makes the code messy after some time. As I was reading some RabbitMQ documentation I came around a solution which could structure my project a lot better which relies on Exchanges. Exchanges can publish messages to multiple queues on which a Cosumer can consume it, in short: The RabbitMQ-Documentation describes a solution with Pika, which is a more low-level Client for RabbitMQ than Celery. The Celery-Documentation describes this scenario in its Documentation but doesn't describe how to create a Producer which produces Messages which are sent to an Exchange which distributes it to various Queues as seen in the Picture above. It only describes how to message Queues and send tasks - but I want this handeled by the Exchange. I found that Kombu, on which celery relies under the hood, has a function to send messages to an Exchange via a Producer but I can't find any documentation how to use this in celery-django. …