Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
linux terminal error while installing
Traceback (most recent call last): File "netattack2.py", line 47, in <module> from scapy.all import * File "/usr/local/lib/python2.7/dist-packages/scapy/all.py", line 10, in <module>`dtytyty` from .config import * File "/usr/local/lib/python2.7/dist-packages/scapy/config.py", line 11, in <module> from .data import * File "/usr/local/lib/python2.7/dist-packages/scapy/data.py", line 184, in <module> TCP_SERVICES,UDP_SERVICES=load_services("/etc/services") File "/usr/local/lib/python2.7/dist-packages/scapy/data.py", line 109, in load_services f=open(filename, errors='ignore') TypeError: 'errors' is an invalid keyword argument for this function -
is that really not possible in the Django ORM?
In my 10 years playing with Django i found a few bugs, but i never had to fall back to a raw SQL query. Fiddling with Django for almost a full day now im out of ideas except of asking for help here: I have an organizer app with days containing shifts and people working those shifts (M2M). There also are supervisors for each day that are directly stored on the day (M2M). For the user stats i want to see who has how many shifts. For speed reasons i WANT to handle this with only one query. Here is the query i ended up with: assigned_to = self.shifts.filter(day_id=OuterRef('id')).order_by() days = Day.data.filter(date__range=(start, end)).distinct().annotate( assigned_shifts=Count( Subquery(assigned_to.values('id')) )).annotate( assigned_pl=Max(Case( When(production_managers=self, then=1), default=0, output_field=models.IntegerField(), distinct=True ))).annotate( assigned_tl=Max(Case( When(day_managers=self, then=1), default=0, output_field=models.IntegerField(), distinct=True ))).annotate( assigned_al=Max(Case( When(managers=self, then=1), default=0, output_field=models.IntegerField(), distinct=True ))).annotate( assigned_cash=Max(Case( When(cash_managers=self, then=1), default=0, output_field=models.IntegerField(), distinct=True ))).order_by() This is giving me an SQL error "more than one row returned by a subquery used as an expression", tho. Without the subquery i was getting false values - probably because the grouping didnt work out as its supposed to. Turns out there is a warning in the docs and a very old ticket (https://code.djangoproject.com/ticket/10060) warning … -
Django get value from JSON data
I am trying to play with an open fda API. So far everything works well. Issue is coming for nested JSON data. Here is my Json data: { "seriousnessother": "1", "reportduplicate": { "duplicatenumb": "US-BRISTOL-MYERS SQUIBB COMPANY-BMS-2017-086135", "duplicatesource": "BRISTOL MYERS SQUIBB" }, "safetyreportversion": "1", "receiptdate": "20170927", "duplicate": "1", "seriousnessdeath": "1", "receivedate": "20170927", "patient": { "reaction": [ { "reactionmeddrapt": "Death", "reactionmeddraversionpt": "20.1", "reactionoutcome": "5" }, { "reactionmeddrapt": "Product use in unapproved indication", "reactionmeddraversionpt": "20.1", "reactionoutcome": "6" } ], "patientsex": "1", "drug": [ { "drugstartdateformat": "102", "medicinalproduct": "OPDIVO", "drugindication": "COLORECTAL CANCER", "drugcharacterization": "1", "drugadministrationroute": "065", "drugenddateformat": "102", "drugseparatedosagenumb": "1", "drugstructuredosageunit": "032", "openfda": { "manufacturer_name": [ "E.R. Squibb & Sons, L.L.C." ], "unii": [ "31YO63LBSN" ], "product_type": [ "HUMAN PRESCRIPTION DRUG" ], "spl_set_id": [ "f570b9c4-6846-4de2-abfa-4d0a4ae4e394" ], "route": [ "INTRAVENOUS" ], "generic_name": [ "NIVOLUMAB" ], "brand_name": [ "OPDIVO" ], "product_ndc": [ "0003-3772", "0003-3734", "0003-3774" ], "pharm_class_epc": [ "Programmed Death Receptor-1 Blocking Antibody [EPC]" ], "substance_name": [ "NIVOLUMAB" ], "spl_id": [ "2d33126d-5115-459e-bcaf-d0ace4fbe94e" ], "pharm_class_moa": [ "Programmed Death Receptor-1-directed Antibody Interactions [MoA]" ], "application_number": [ "BLA125554" ], "nui": [ "N0000191259", "N0000191260" ], "package_ndc": [ "0003-3734-13", "0003-3772-11", "0003-3774-12" ] }, "drugstructuredosagenumb": "1", "drugintervaldosageunitnumb": "2", "drugstartdate": "20160907", "actiondrug": "5", "activesubstance": { "activesubstancename": "NIVOLUMAB" }, "drugintervaldosagedefinition": "803", "drugauthorizationnumb": "125554", "drugrecurreadministration": … -
Unable to import model in my celery task
I'm running Celery/Django on my remote Ubuntu server via supervisor. My system can successfully receive and execute my 2 tasks from my tasks.py. @periodic_task(run_every=timedelta(minutes=1)) def test_job(): from polls.models import Question from post.models import Post #when I add this line, it fires the error for i in Question.objects.all(): if i.question_text == "test": i.question_text = "not_test" i.save() return HttpResponseRedirect('/') @periodic_task(name='run_scheduled_jobs', run_every=timedelta(seconds=30)) def run_scheduled_jobs(): return True However, when I use: from post.models import Post in my task, the task fails: I've tried importing models from all my other modules and it works fine; e.g. from Comment.models import Comment and from poll.models import Question works fine. For some reason it's not letting me import from post.models import Post. Here is the post.models file: from django.db import models from django.contrib.auth.models import AbstractUser, User from django.conf import settings #from django.contrib.humanize import naturaltime from django.apps import apps from draft1.choices import CATEGORY_CHOICES from django.utils import timezone import requests import tempfile from django.core import files from django.core.files import File as FileWrapper from datetime import datetime, timedelta from math import log10 from urllib import parse from urllib.parse import urlparse import boto3 # import uuid from functions.helper_functions import random_string from math import log, exp from draft1.choices import DURATION_CHOICES class Post(models.Model): hash … -
Error while parsing date using custom date filter in django
{% for obj in Users %} <p>{{ obj.active_date | date_filters : obj.id }}</p> {% endfor %} i am using date_filters by passing object id dynamically,obj.active_date= datetime.date(2018,4,27) in date_filters file is from django import template register = template.Library() from app import models as user_models import datetime @register.filter(name='date_filters') def date_filters(value,arg): # user_models.home.objects.get(id=arg) return value.strftime("%m/%d/%Y") i am getting exception like (u"Could not parse the remainder: ' :obj.id' from 'obj.active_date | date_filters : obj.id'",) -
Django (REST FRAMEWORK) Foreign Key Serializer for Creating and Updating Model
MODELS.PY from django.db import models import datetime # Create your models here. #User Profile Data is Stored Here class Users(models.Model): Users_userId = models.AutoField(primary_key=True) Users_userName = models.CharField(max_length=60) Users_userGender = models.CharField(max_length=10) Users_userPhone = models.CharField(max_length=15) Users_userEmail = models.CharField(max_length=60) Users_userCreateDate = models.DateTimeField(default=datetime.datetime.now()) Users_userUpdateDate = models.DateTimeField(default=datetime.datetime.now()) Users_userIsActive = models.BooleanField(default=True) Users_userIsEmailVerified = models.BooleanField(default=False) Users_userIsPhoneVerified = models.BooleanField(default=False) class Users_Password(models.Model): Users_Password_userpasswordId = models.AutoField(primary_key=True) Fk_Users_Users_Password_userId = models.ForeignKey(to=Users, on_delete=models.DO_NOTHING) Users_Password_userpasswordPassword = models.CharField(max_length=100) Users_Password_userpasswordCreateDate = models.DateTimeField(default=datetime.datetime.now()) Users_Password_userpasswordUpdateDate = models.DateTimeField(default=datetime.datetime.now()) Users_Password_userpasswordIsActive = models.BooleanField(default=True) #Static Table for User Types class User_Type(models.Model): User_Type_usertypeId = models.AutoField(primary_key=True) User_Type_usertypeName = models.CharField(max_length=20) Users_userCreatDate = models.DateTimeField(default=datetime.datetime.now()) Users_userUpdateDate = models.DateTimeField(default=datetime.datetime.now()) Users_userIsActive = models.BooleanField(default=True) #Resolving Many to Many Relationships class Users_User_Type_Reference(models.Model): ReferenceId = models.AutoField(primary_key=True) Fk_User_Type_Reference_usertypeId = models.ForeignKey(User_Type, on_delete=models.DO_NOTHING) Fk_Users_Reference_userId = models.ForeignKey(Users, on_delete=models.DO_NOTHING) SERIALIZERS.PY from rest_framework import serializers from api.models import Users,User_Type as UserType,Users_User_Type_Reference as User_Type_Bridge, Users_Password import datetime # class SignUp_Serializer(serializers.Serializer): # first_name = serializers.CharField(max_length=20) # last_name = serializers.CharField(max_length=20) # phone = serializers.CharField(max_length=15) # # email = serializers.EmailField() # # password = serializers.CharField(max_length=20) # # def create(self, validated_data): # return Users.objects.create(**validated_data) # # # class LoginSerializer(serializers.Serializer): # email = serializers.EmailField() # password = serializers.CharField(max_length=20) # # def create(self, validated_data): # return UserLogin.objects.create(**validated_data) # # """user = UserLogin.objects.create(**validated_data) # user.save() # return user""" class Password_Serializer(serializers.Serializer): Users_Password_userpasswordPassword = serializers.CharField(max_length=100) Users_Password_userpasswordCreateDate = serializers.DateTimeField(default=datetime.datetime.now()) Users_Password_userpasswordUpdateDate … -
python django pip update problems: how to get compatible versions?
I tried to run a django demo project on a hosted server (Ubuntu 16.04): it worked fine. Then I tried to run the same code on a local machine: Unhandled exception in thread started by <function wrapper at 0x7fc0c4403f50> Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 116, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 127, in create import_module(entry) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named about Therefore I tried to update the django installation (which probably has an older version than the server). So I tried the pip django update: sudo pip install -U django which led to this error: The directory '/home/lxuser/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/home/lxuser/.cache/pip' or its parent directory is not owned by the current user and caching wheels … -
filtering your database
i have a model which gives me the details of some cheese, now i use it in a list view, i have also implemented a search function,which works all fine. now i want to add filter tabs on the html. eg: the origin of cheese is only from 5 countries, i want to display the flags icons of 5 countries which when clicked should only display the cheeses from that particular countries, just like mixitup, im ok if there is no animation thing. how can i acheive this???? note: the models and views and html is written the normal way incase if you want see my code. -
Map custom defined url path to included url path
I would like to map a url path /register to an included url path, rest-auth/registration. For example, if I type in localhost:3000/register, it would map to localhost:3000/rest-auth/registration. Currently I am simply using: url(r'^rest-auth/registration/', include('rest_auth.registration.urls')) where rest_auth.registration.urls is from the rest_auth framework I am using. Woulda anyone know how I could achieve this? Thank you. -
shell_plus installed with Django giving error - ImportError: cannot import name 'Type
I am getting the following error when trying to launch shell_plus after installing django_extensions. Here are the steps i followed 1-Installed django_extensions using pip install django_extensions 2-Added django_extensions to installed apps Then I get the following error $ ./manage.py shell_plus Traceback (most recent call last): File "./manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/admin/Development/project/virtual/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/admin/Development/project/virtual/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/admin/Development/project/virtual/lib/python3.5/site-packages/django/core/management/__init__.py", line 216, in fetch_command klass = load_command_class(app_name, subcommand) File "/Users/admin/Development/project/virtual/lib/python3.5/site-packages/django/core/management/__init__.py", line 36, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 662, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/Users/admin/Development/project/virtual/lib/python3.5/site-packages/django_extensions/management/commands/shell_plus.py", line 14, in <module> from django_extensions.management.shells import import_objects File "/Users/admin/Development/project/virtual/lib/python3.5/site-packages/django_extensions/management/shells.py", line 5, in <module> from typing import ( # NOQA ImportError: cannot import name 'Type' -
Django createsuperuser created admin account with wrong password
I am using django 1.11 and DRF to create an app. When I use manage.py createsuperuser command to create a superuser, it successfully created an account for me. But when I am trying to log in to the account. The login screen prompts me a login error. When I use manage.py changepassword admin command to change the password, I can log in to the account. This is really annoying, and I can't figure out what happened, for days Are there any reason that can cause the command creating a wrong password? :/ Anybody can help? -
redirect causes Page not found error
redirect causes Page not found error.I wrote in html <form method="POST" action="/app/save/"> <p>name:<input id="name" type="text" name="NAME"></p> <p>email:<input id="email" type="text" name="email"></p> <p><input type="submit" value="SEND"></p> </form> in views.py def top(request): return render(request, 'top.html') def save(request): save_form = SaveForm(request.POST or None) if request.method == "POST" and save_form.is_valid(): save= save_form.save(commit=False) name = request.POST.get("name", "") email = request.POST.get("email", "") save.name = name save.email = email save.save() return redirect("polls:top") in urls.py from django.urls import include, path from . import views urlpatterns = [ path('top', views.top,name='top'), path('save', views.save,name='save'), ] I really cannot understand why such a error happens.I wrote save's url in urls.py so I think urls&views' connection is OK.Furthermore,i think the way of writing redirect is not wrong.How should I fix this?What is wrong in my codes? -
How should I configure Redis for Django Channels 2.0?
I'm getting an error sometimes when I run a Worker of Django Channels as Background Task. The task consumes an open third-party WebSocket with a library called Pysher, processes that data and then sends the resulting data through the Channel Layer to a group of Websockets listening to our application using Redis (the Message Broker). I know that the problem does not have to do with the Pysher library, since if I comment the code to send the message through the Channel Layer runs whitout problems. The problem occurs due to the sending of the message in the Channel Layer and only happens sometimes, many times the sending occurs successfully and other times it throws the error, the last behaviour makes me think that it may have to do with Redis or the Channel Layer and its configuration or something like that, maybe Redis is getting some limit. Error message error from callback bound method Connection._on_message of Connection(Thread-2, started daemon 140614612023040): [Errno 99] Cannot assign requested address SO and Redis version Ubuntu 16 + Redis 3.2 Pip Dependencies aiodns==1.1.1 aiohttp==2.3.10 aioredis==1.0.0 amqp==2.2.2 asgiref==2.1.6 asn1crypto==0.24.0 astroid==1.6.1 async-timeout==2.0.0 attrs==17.4.0 autobahn==17.10.1 Automat==0.6.0 Babel==2.5.3 billiard==3.5.0.3 biopython==1.69 cchardet==2.1.1 celery==4.1.0 certifi==2018.1.18 cffi==1.11.4 channels==2.0.2 channels-redis==2.1.0 chardet==3.0.4 click==6.7 … -
Pandas create month end holding from activity
I am trying to find the month-end balance amounts based on the "issues" held from the df_td list of activity. Actually I am just looking to find the count of "issues" with a positive balance at the end of each month. To do this I need to create the month-end balance based on each "issues" "action" and "shares" on activity less than the month-end date. So the total count of issues with a balance > 0 for each period. The "action" is used to know if it is a buy or a sell, "+" or "-". So the balance is "+ shares" less "- shares" per each "issue." Previously I used sql to do this but that seems like a serious waste. What is best way to do this with Pandas? df_td action code comm credit date \ 0 + P 0.00 0.00 2013-03-27 1 + P 0.00 0.00 2013-03-27 2 - S 19.00 86751.01 2013-04-08 3 + Z 2000.00 0.00 2013-04-09 4 - S 18.71 730.49 2013-04-10 issue \ FIDELITY REAL ESTATE INVESTMENT PORTFOLIO FUND FIDELITY NJ MUNICIPAL INCOME FUND FIDELITY REAL ESTATE INVESTMENT PORTFOLIO FUND AMERICAN RLTY CAP HEALTHCARE TR INC FIDELITY NJ MUNICIPAL INCOME FUND price shares … -
My template breaks when i turn off debug mode in python django
When I turn off debug mode in settings.py, one of my templates breaks. The template references a header.html and a footer.html. The header.html renders to the page, but the footer.html does not. Is there something with the staticfiles settings that I'm not taking care of? Since the templates don't reside with the other staticfiles, I didn't think it would be related to this issue but perhaps it is. I am using the django-heroku package to auto-configure the staticfiles. -
SyntaxError: unexpected EOF while parsing in Django
I'm using Python 3 and Django 2, and I'm having this error I have no idea why: def save(self, commit=True): # Save the provided password in hashed format user = super(UserAdminCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user -
How can I get superuser's information?
I am making Django app.I want to use superuser's data in the codes. I registered name&email&password.Usually User's data can be gotten like user = User.objects.get(id=1) name = user.name but how can I get superuser's data? -
How to write query with multiple models in Django
how to write a query for student who logged in(student = self.request.user.id) to view his assignments titles (belong to his intake) class intake(models.Model): intakecode = models.CharField(max_length=100) modules = models.ManyToManyField(Module, through='IntakeDetails') class Student(models.Model): user = models.OneToOneField(UserType, on_delete=models.CASCADE, primary_key=True) intakecode = models.ForeignKey(intake, on_delete=models.CASCADE) student belong to a intake and each intake many modules. class IntakeDetails(models.Model): intake = models.ForeignKey(intake, on_delete=models.CASCADE) lecturer = models.ForeignKey(Lecturer, on_delete=models.CASCADE) module= models.ForeignKey(Module, on_delete=models.CASCADE) class AssignAssignment(models.Model): title=models.CharField(max_length=30) duedate=models.DateField() intakedetails=models.ForeignKey(IntakeDetails,on_delete=models.CASCADE,null=True) i tried this one but if there are more than one intakedetails it pops up an error. @login_required class ModelIndexView(ListView): template_name= 'accounts/students/students.html' context_object_name= 'students' def get_queryset(self): student = self.request.user.id student_det = Student.objects.get(user_id=student) assignment=IntakeDetails.objects.get(intake_id=student_det.intakecode) queryset=AssignAssignment.objects.filter(intakedetails_id=assignment.id) return queryset -
Pagination with URL path or the query parameters
I am working on writing a blog and came across two different alternatives on the internet for making pagination. I couldn't decide which to use. Url types are like ; blog/page/2 blog/?page=2 Does one of these have an advantage over the other? -
how to fix? AttributeError: 'module' object has no attribute
I am getting an error in urls.py file (line 6)... am I missing anything? this is the error in the command line (python manage.py runserver) line 6, in <module> url(r'^$', views.cart_detail, name='cart_detail'), AttributeError: 'module' object has no attribute 'cart_detail' this is the urls.py file from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.cart_detail, name='cart_detail'), this is the views.py file # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render, redirect, get_object_or_404 from django.views.decorators.http import require_POST from vpn.models import Product from .cart import Cart from .forms import CartAddProductForm # Create your views here. @require_POST def cart_add(require, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail') def cart_remove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('cart:cart_detail') def cart_detail(request): cart = Cart(request) # for item in cart: # item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'], # 'update': True}) return render(request, 'cart/detail.html', {'cart': cart}) -
Django sending wrong filename with UUID based download
Folks, I'm having an issue that I can work around, but I'd prefer not to. I just rewrote my gallery application, to use a UUID based database index for the download. Eg. url(r'^(?i)download/(?P<d_uuid>.+)/', frontend.views.new_download, name="downloads"), So download/ will lookup the file by searching for the UUID, and then serve it out. def new_download(request, d_uuid=None): download = index_data.objects.filter(uuid=d_uuid, ignore=False, delete_pending=False)[0] print ("\tDownloading - %s, %s" % (download.fqpndirectory.lower(), download.name)) return serve(request, download.name, download.fqpndirectory.lower()) This was working properly before I switched to using the UUID search. It appears that the browsers (firefox, Safari, etc), are grabbing the filename from the GET. Now, I've tried using, this instead of serve: respond_as_attachment(request, download.fqpndirectory, download.name) def respond_as_attachment(request, file_path, original_filename): # https://www.djangosnippets.org/snippets/1710/ # print ("original filename: ", original_filename) fp = open(file_path + os.sep + original_filename, 'rb') response = HttpResponse(fp.read()) fp.close() type, encoding = mimetypes.guess_type(original_filename) if type is None: type = 'application/octet-stream' response['Content-Type'] = type print (response['Content-Type']) response['Content-Length'] = str(os.stat(file_path).st_size) if encoding is not None: response['Content-Encoding'] = encoding filename_header='filename="%s"' % original_filename response['Content-Disposition'] = 'attachment; ' + filename_header return response Without any change in behavior. I'm stumped... The UUID switch has allowed me to simplify the code quite a bit. Now I could write the incoming request, along this … -
How to send request body for DELETE in Django Rest Framework
So I am trying to send a request body for DELETE in DRF. I know by default,DRF doesn't support bulk operations so I am using django-rest-framework-bulk. Now as per the tutorial, I am making sure the bulk deletes are allowed only when the query is filtered.I am using BulkModelViewset. Consider this json array: [{ "id": "1", "first_name": "bruce", "second_name": "banner", "team": "avengers" }, { "id": "2", "first_name": "clark", "second_name": "kent", "team": "Justice League" } { "id": "3", "first_name": "dead", "second_name": "pool", "team": "x force" }] Now the I could delete in bulk by passing a filter like : DELETE /api_name/?first_name=bruce,clark But my frontend people want to send a request body because if there are 100 objects which are needed to be deleted, they are not expected to send 100 ids as comma separated string in query parameter. I am new to REST principles so there could be fault in my entire logic. I tried to find answers online but couldn't find something specific.Thanks Sample Viewset: class TeamViewSet(BulkModelViewSet): serializer_class = TeamViewSerializer queryset = TeamView.objects.all() filter_backends = (DjangoFilterBackend,filters.OrderingFilter,) filter_class =TeamViewFilter ordering = ('id','second_name','first_name','team') def allow_bulk_destroy(self, qs, filtered): return filtered -
Django: What's the best way to save Integer Bins in a Model?
What's the best way to save data to a model that is collected in bins. For example if the question was "Which of the following best describes you: I eat" 1) 1-4 apples a month. 2) 5-9 apples a month. 3) 10+ apples a month. Would this option work? class MyForm(forms.ModelForm): a_little= 1 some= 2 a_lot= 3 na = 4 CHOICES = ( (a_little, '1-4'), (some, '5-9'), (a_lot, '10+'), (na, 'Does not apply'), ) forms.PositiveSmallIntegerField(choices=CHOICES) Is there a better way to do this? -
Django Bootstrap Modal fields not clickable
I'm trying to create a basic modal using bootstrap to provide a login. The page has a button: <nav class="navbar navbar-light bg-light"> ... <button type="button" class="btn btn-light" data-toggle="modal" data-target="#login-modal">Login</button> ... ... </nav> and further down on the page I have the loginmodal: <div class="modal fade" id="login-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;"> <div class="modal-dialog"> <div class="loginmodal-container"> <h1>Login to Your Account</h1><br> <form action="{% url 'login_user' %}" method="post"> {% csrf_token %} <input type="text" name="user" placeholder="Username"> <input type="password" name="password" placeholder="Password"> <input type="submit" name="login" class="login loginmodal-submit" value="Login"> </form> <div class="login-help"> <a href="{% url 'register' %}">Register</a> - <a href="{% url 'forgotpass' %}">Forgot Password</a> </div> </div> </div> </div> Pressing the button shows the modal and the fields correctly but whenever I press any of the fields in the modal, it hides. All the links are unclickable as well.. Is there anything i'm missing to make this work? The css loads fine (200 OK in the server shell) and I have bootstrap functionality otherwise.. I'm new to both django and bootstrap so I hope you can point me in the right direction.. -
Django User permissions/views?
I'm using Django class based views. views.py class ReportListView(LoginRequiredMixin, ListView): model = Report def get_queryset(self): queryset = Report.objects.filter(user=self.request.user) return queryset class ReportDetailView(LoginRequiredMixin, DetailView): model = Report class ReportUpdateView(LoginRequiredMixin, UpdateView): model = Report class ReportCreateView(LoginRequiredMixin, CreateView): model = Report class ReportDeleteView(DeleteView): model = Report As you can see, these are the most generic views, but they should all represent data for only the current user. Currently any user can see/view other users data. One way I saw was that people would define their get_queryset method, like above. This approach only filters rendered data, but the user can still access forbidden data through url (provided he knows/guesses the id). How can I restrict access to other users resources?