Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Request MiddleWare Not Taking Effect in View
I am working on a solution that is taking a JWT token, finding the associated user, and setting the user in the request to the found user with the token. My middleware looks like this: class UserTokenMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): header_token = request.META.get('HTTP_AUTHORIZATION', None) if header_token is not None: try: token = request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1] data = {'token': token} valid_data = VerifyJSONWebTokenSerializer().validate(data) user = valid_data['user'] request.user = user except Token.DoesNotExist: pass print(request.user.auth_token); return self.get_response(request) And it works! The auth_token is present! And its added at the bottom of my middleware like so: MIDDLEWARE = [ #Added Last "app.middleware.UserTokenMiddleware" ] Now here where doesn't work. I am trying to log out by deleted token, and I need the key. So I have this: @action( url_path="logout", detail=False, methods=["get"], renderer_classes=[JSONRenderer]) def endsession(self, request): result = logout(request) #request.user.auth_token.delete() print("Auth Token") print(request.user.auth_token); print(result) return Response({"logout": "successful"}) Except I always get the following error: Exception Type: AttributeError at /v1/users/logout Exception Value: 'AnonymousUser' object has no attribute 'auth_token' Any clue to why the auth_token is suddenly disappearing and reverting to AnonymousUser? -
reversing django object query with parent-child M2M relationship
in a case with three models (objects) with this type of object relationship: # Team = parent, a group or collection of people class Team(models.Model): name = models.CharField(max_length=100, unique=True) ... # Person = an individual person who belongs to a team class Person(models.Model): # relationships team = models.ForeignKey('Team', on_delete=models.CASCADE, related_name='people') projects = SortedManyToManyField('Project', related_name='people') # Project = each Person can have zero, one, or multiple Projects # multiple different teams can work on same Project class Project(TimeStampedModel): TYPES = Choices( ... ) I know I can query "People with Projects on a Team" like this: user_teams = Team.objects.filter(user=request.user, ...) people_with_projects = Person.objects.filter(team__in=user_teams, projects=True) how would I reverse that to get the queryset for "list of Projects People who are on Team Foo are working on"? (i.e., Projects by specific Team) thanks -
TypeError: _getfullpathname: path should be string, bytes or os.PathLike, not function (wsgi.py error)
I developed this django project on ubuntu using Django 2.0 and Postgresql, then I cloned it to run on windows. After migrating the databases when I run "python manage.py runserver" it throws the following type error. Any help would be appreciated! Traceback Performing system checks... System check identified no issues (0 silenced). January 24, 2019 - 20:02:45 Django version 2.1.2, using settings 'main.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03A378A0> Traceback (most recent call last): File "C:\Users\HP\Desktop\django\crowd-social\crowdsocial_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\HP\Desktop\django\crowd-social\crowdsocial_env\lib\site-packages\django\core\management\commands\runserver.py", line 137, in inner_run handler = self.get_handler(*args, **options) File "C:\Users\HP\Desktop\django\crowd-social\crowdsocial_env\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "C:\Users\HP\Desktop\django\crowd-social\crowdsocial_env\lib\site-packages\django\core\management\commands\runserver.py", line 64, in get_handler return get_internal_wsgi_application() File "C:\Users\HP\Desktop\django\crowd-social\crowdsocial_env\lib\site-packages\django\core\servers\basehttp.py", line 44, in get_internal_wsgi_application return import_string(app_path) File "C:\Users\HP\Desktop\django\crowd-social\crowdsocial_env\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\python3\Lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\HP\Desktop\django\crowd-social\main\main\wsgi.py", line 19, in <module> application … -
Two forms, two views, one page Django - only one form displays
I have two separate forms stemming from the same model (CustomUser). I want to have two separate forms with separate buttons to break the EditProfile form down into two forms on the same page. I created two separate forms, two views and two urls. I also added two separate actions to the forms, but I can only get the first form to display. I tried adding both the name of the url and the name of the view function in the action, but it didn't work. views.py: def EditProfileView(request): form = EditProfile() if request.method == 'POST': form = EditProfile(request.POST, instance =request.user) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('edit_profile')) else: form = EditProfile(instance = request.user) return render(request, 'edit_profile.html', { 'form': form, }) def EditProfileDetailView(request): form = EditProfileDetail() if request.method == 'POST': form = EditProfileDetail(request.POST, instance =request.user) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('profile')) else: form = EditProfileDetail(instance = request.user) return render(request, 'edit_profile.html', { 'form': form, }) urls.py: urlpatterns = [ path('profile/edit/', views.EditProfileView, name='edit_profile'), path('profile/edit/', views.EditProfileDetailView, name='edit_profile_detail'), ] forms.py: class EditProfile(forms.ModelForm): class Meta: model = CustomUser fields =('diff_field', 'diff_field2',) class EditProfileDetail(forms.ModelForm): class Meta: model = CustomUser fields =('skill_area1_title', 'skill_area1',) edit_profile.html: <form class="form-group booking_form" method="post" action="{% url 'edit_profile' %}"> {% csrf_token %} #form stuff </form> <form class="form-group … -
Django, Celery, Redis: AttributeError: module 'expert' has no attribute 'celery'
Tyring to start celery -A imp_expert worker -l info as per the Celery documentation (my project is not named proj, it's imp_expert) I get: Traceback (most recent call last): File "/home/expert/.virtualenvs/semion_expert/bin/celery", line 11, in <module> sys.exit(main()) File "/home/expert/.virtualenvs/semion_expert/lib/python3.5/site-packages/celery/__main__.py", line 16, in main _main() File "/home/expert/.virtualenvs/semion_expert/lib/python3.5/site-packages/celery/bin/celery.py", line 322, in main cmd.execute_from_commandline(argv) File "/home/expert/.virtualenvs/semion_expert/lib/python3.5/site-packages/celery/bin/celery.py", line 496, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/home/expert/.virtualenvs/semion_expert/lib/python3.5/site-packages/celery/bin/base.py", line 273, in execute_from_commandline argv = self.setup_app_from_commandline(argv) File "/home/expert/.virtualenvs/semion_expert/lib/python3.5/site-packages/celery/bin/base.py", line 479, in setup_app_from_commandline self.app = self.find_app(app) File "/home/expert/.virtualenvs/semion_expert/lib/python3.5/site-packages/celery/bin/base.py", line 501, in find_app return find_app(app, symbol_by_name=self.symbol_by_name) File "/home/expert/.virtualenvs/semion_expert/lib/python3.5/site-packages/celery/app/utils.py", line 370, in find_app found = sym.celery AttributeError: module 'imp_expert' has no attribute 'celery' I have in __init__.py: from __future__ import absolute_import from .celery import app as celery_app __all__ = ('celery_app',) In celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'imp_expert.config.base') app = Celery('imp_expert') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) In base.py … -
PostgreSQL with Django: should I store static JSON in a separate MongoDB database?
Context I'm making, a Django web application that depends on scrapped API data. The workflow: A) I retrieve data from external API B) Insert structured, processed data that I need in my PostgreSQL database (about 5% of the whole JSON) I would like to add a third step, (before or after the "B" step) which will store the whole external API response in my databases. For three reasons: 1) I want to "freeze" data, as an "audit trail" in case of the API changes the content (It happened before) 2) API calls in my business are expensive, and often limited to 6 months of history. 3) I might decide to integrate more data from the API later. Calling the external API again when data is needed is not possible because of 2) and 3) Please note that the raw external API responses will never be updated and read performance is not really important. To provide additional context, there is a few thousand API calls a day, which represent arround 50GB of data a year. Here comes my question(s) Should I store the raw JSON in the same PostgreSQL database I'm using for the Django web application, or in a separate … -
docker-compose with two containers: web can not connect to db
docker-compose fails to build web component because it can not connect to the previously created db component Mac OSX 10.13.6, conda 4.5.11, Python 3.6.8, Docker version 18.09.1, docker-compose version 1.23.2 django 1.8.3 gets installed with requirements.txt from Dockerfile. Not at liberty to upgrade. Several very similar discussions on SO did not help (like this one: Docker-compose with django could not translate host name "db" to address: Name or service not known). I have a docker-compose.yml with a network and two components: version: '3' networks: bridge: driver: bridge services: db: image: postgres:10 container_name: myapp-db volumes: - ./postgres_data:/var/lib/postgresql/data/ ports: - "5432:5432" environment: POSTGRES_DB: actionability-master POSTGRES_PASSWORD: postgres POSTGRES_USER: postgres networks: - bridge web: restart: unless-stopped container_name: myapp-web build: . command: /start_gunicorn.sh ports: - "8080:8080" environment: PRODUCTION: 'true' networks: - bridge In my settings.py I have DATABASES section: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': INSTANCE_NAME, 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432' }, } When I run $ docker-compose up -d, the first image (db) gets created and its container gets started. Can see it's running and listening on port 5432 with docker ps and lsof . The same thing happens if I remove web: component from docker-compose.yml file Now, the … -
Unable to install right version of mysql(8.0.13) on windows
I am a Windows user and very new with django and database. My current group project requires to use django and mysql. My teammate(macOS user) has already built a django web and I was trying to run the web by running it on virtualenv. I tried to download every required packages by typing 'pip install -r requirements.txt'. Although, it downloaded most of the packages, but it did not allow me to install mysql==8.0.13. I tried other methods such as 'pip install mysql==8.0.13' or even trying it on ubuntu bash. However, I always get this message.... (virtualenv) C:\Users\ed>pip install mysql==8.0.13 Collecting mysql==8.0.13 Could not find a version that satisfies the requirement mysql==8.0.13 (from versions: 0.0.1, 0.0.2) No matching distribution found for mysql==8.0.13 So even after many tries, I could not find a solution so when I just type 'py manage.py runserver' or 'python manage.py runserver', the results show like this.... (virtualenv) C:\kim....\projectsite>py manage.py runserver Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by .wrapper at 0x03585618> Traceback (most recent call last): File "C:\Users\edwardkim\Envs\shkim\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection self.connect() File "C:\Users\edwardkim\Envs\shkim\lib\site-packages\django\db\backends\base\base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\edwardkim\Envs\shkim\lib\site-packages\django\db\backends\mysql\base.py", line 227, in get_new_connection return … -
modelling an ER diagram for django
I needed some help to convert to tables and later to django's models, using Django's Admin interface, two entities (Item, Prototype) where: Item can be a standalone object or be part of one prototype only Prototype exists only if it contains at least an Item A Prototype can contain many different items. The ER diagram should be this: At the Django side I wished: from the PrototypeAdmin to include any Item(s) and from ItemAdmin to assign to one prototype like in the followings pictures: I made some attempts designing different models but I'm not fully satisfied of my results (one try implies many NULLs, another gives an admin interface not very easy to use, from another one I can only add Items to protype..) -
How to write a unit test for uploading an Image in django rest framework
I'm using Django rest frame work to develop a RESTful API. I've implemented a post method that allows a user to upload and image as shown below. I'm using models.ImageField for the document field. Further below I have also implemented the test case I doubt it will work. How do I implement a test case for uploading and image. Post method def post(self, request, *args, **kwargs): """ Creates a document. """ logged_in_user = request.auth['user_id'] # print(request.data) org_id = get_auth(request) name = request.data['name'] document = request.FILES['document'] try: doc_object = Document.objects.create( owner = logged_in_user, org_id= org_id, name=name, document=document ) return Response(status=status.HTTP_201_CREATED) except Exception as e: raise e Test Case def test_can_upload_a_document(self): pic = os.path.join(settings.BASE_DIR, '/media/images/', 'test_pic.png') test_picture = open(pic, 'rb') payload ={ "owner":self.employee.id, "name":"Edward Gates", "document":test_picture, "notes":"Add notes here", "assessment_status":"Pending" } url = reverse('hr:documents') self.client.credentials(HTTP_AUTHORIZATION=self.token) response = self.client.post(url,data=payload,format='mutipart') self.assertEqual(response.status_code, 200) -
Saving translated slug of django modeltranslation not working
I've been breaking my head over this for a day now. I use django-modeltranslation to translate blog-like posts. All works fine, except I also try to automatically translate the slugs from the title, based off of this article: https://raphaelbeck.wordpress.com/2011/04/16/how-to-translate-slug-with-django-modeltranslation/ Only the translated slug is not translated saved to the database. class Item(models.Model): category = models.ForeignKey( 'help.category', on_delete=models.PROTECT, related_name='categories') title = models.CharField(_('Titel'),max_length=255) description = RichTextField(_('Omschrijving')) slug = AutoSlugField(_('slug'), populate_from='title', overwrite=True) class Meta: verbose_name = _(u"Item") verbose_name_plural = _(u"Items") #automatically creating slugs for translations def save(self, *args, **kwargs): for lang_code, lang_verbose in settings.LANGUAGES: if hasattr(self, 'slug_%s' % lang_code) and hasattr(self, 'title_%s' % lang_code): setattr(self, 'slug_%s' % lang_code, slugify(getattr(self, 'title_%s' % lang_code, u""))) print(self.slug_nl) print(self.slug_en) print(self.slug_nl) print(self.slug_en) super().save(*args, **kwargs) def __str__(self): return str(self.title) I added some print funtions to see what actually happens. The console logs are as expected: dutch-slug None dutch-slug english-slug dutch-slug english-slug -> slug_en is translated correctly based on the title in the console, but in the database the dutch slugs are saved. Thanks in advance! Any ideas are greatly appreciated. -
Writing in memory zip file to django FileField
Im trying to read files from FileField, put them all to zip and save that zip to another FileField. Im trying to avoid using temp file but it seems that i might have to. Here is what i got so far: def generate_codified_batch(modeladmin, request, queryset): for batch in queryset: pieces = Pieces.objects.filter(batch=batch) mem_zip = InMemoryZipFile(file_name=batch.name) for piece in pieces: in_file = open(piece.file.path, 'rb') data = in_file.read() mem_zip.append(filename_in_zip=f'/{piece.folder_assigned} /{piece.period}/{piece.codification}. \ {piece.file_name.rsplit(".")[-1]}' , file_contents=data) in_file.close() files_codified = ContentFile(mem_zip.data) Batches.objects.filter(pk=batch.id).update(file_codified=files_codified) InMemoryZipFile is a class from this packet: https://bitbucket.org/ruamel/std.zipfile/src/faa2c8fc9e0072f57857078059ded42192af5435/init.py?at=default&fileviewer=file-view-default#init.py-57 Important are only two last lines files_codified = ContentFile(mem_zip.data) Batches.objects.filter(pk=batch.id).update(file_codified=files_codified) mem_zip.data is a property of InMemoryZip and returns bytes object (from InMemoryZip class): self.in_memory_data = StringIO() @property def data return self.in_memory_data.getvalue() I cannot for the life of me figure out how to read from that bytes object and pass it to FileField. -
get_FIELD_display() does not display correct value
I have been trying to use get_name_display() in my API View but it does not display the text, just number. I have checked the documentation but it does not mention anything about it - it should be working. For instance, the folowing code prints 3 instead of 'GaussianNB'. Model class Algorithm(models.Model): ALGORITHM_NAME = ( (0, 'KNeighborsClassifier'), (1, 'LogisticRegression'), (2, 'LinearSVC'), (3, 'GaussianNB'), (4, 'DecisionTreeClassifier'), (5, 'RandomForestClassifier'), (6, 'GradientBoostingClassifier'), (7, 'MLPClassifier'), ) name = models.CharField(max_length=64, choices=ALGORITHM_NAME) parameters = JSONField() View class CalcUpdateView(UpdateAPIView): queryset = Calc.objects.all() serializer_class = CalcSerializer def perform_update(self, serializer): instance = serializer.save() algorithm = Algorithm.objects.get(pk=self.request.data['algorithm']) print(algorithm.get_name_display()) Thanks in advance for help! -
django form wizard using UserCreationForm
I'm trying to make a 3paged form which is an application form for my school club. I just looked over the formtools official document but I barely understood how to use it. And this is the code for the form. (forms.py) from django import forms from django.contrib.auth.forms import UserCreationForm from .models import HiarcUser, STATUSES, MAJORS, SEMESTERS import json # import request class HiarcUserCreationForm1(UserCreationForm): # 1 email = forms.EmailField(required=True) real_name = forms.CharField(required=True, max_length=20) student_id = forms.CharField(required=True, max_length=7) # validator phone_number = forms.CharField(required=True, max_length=20) status = forms.CharField(required=True, widget=forms.Select(choices=STATUSES)) semester = forms.CharField(required=True, widget=forms.Select(choices=SEMESTERS)) major = forms.CharField(required=True, widget=forms.Select(choices=MAJORS)) minor = forms.CharField(required=True, widget=forms.Select(choices=MAJORS)) class Meta: model = HiarcUser fields = ("email", "real_name", "student_id", "phone_number", "status", "semester", "major", "minor") def save(self, commit=True): user = super(HiarcUserCreationForm1, self).save(commit=False) user.email = self.cleaned_data["email"] user.real_name = self.cleaned_data["real_name"] user.student_id = self.cleaned_data["student_id"] user.phone_number = self.cleaned_data["phone_number"] user.status = self.cleaned_data["status"] user.semester = self.cleaned_data["semester"] user.major = self.cleaned_data["major"] user.minor = self._clean_fields["minor"] ''' webhook_url = system.environment['SLACK_WEBHOOK_URL'] message = "회원가입 신청이 들어왔습니다. \n이름 : {}\n 이메일 : {} \n학과/학번/학년 : {}\n 자세한 사항은 관리자페이지에서 확인해보세요.".format(user.real_name, user.email, user.status) slack_data = { "text": message, "color": "#FAA3E3"} response = requests.post( webhook_url, data=json.dumps(slack_data), headers={'Content-Type': 'application/json'} ) ''' if commit: user.save() return user class HiarcUserCreationForm2(UserCreationForm): # 2 motivation = forms.CharField(required=True, widget=forms.Textarea) portfolio = forms.CharField(widget=forms.Textarea) … -
Exception Value:NOT NULL constraint failed: auth_user.username
I am creating a project to register and view profile using Django. The problem is when I am trying to register a new user I am getting some errors NOT NULL constraint failed: auth_user.username Here is my form.py and view.py file: form.py from django.contrib.auth.models import User from django import forms from django.contrib.auth.forms import UserCreationForm,UserChangeForm class FileDataForm(forms.Form): name = forms.CharField(max_length=50) file = forms.FileField() image = forms.ImageField() class userregister(UserCreationForm): first_name = forms.CharField(max_length=50, required = False ,help_text ='optional') last_name = forms.CharField(max_length=50, required = False ,help_text ='optional') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('first_name', 'last_name', 'email', 'password1', 'password2', ) class editprofileform(UserChangeForm): class Meta: model = User fields = ('first_name', 'last_name', 'email','password') View.py: from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render,redirect,render_to_response from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import View from .models import FileData from .forms import FileDataForm from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from .forms import userregister,editprofileform from django.contrib.auth.forms import UserChangeForm , PasswordChangeForm from django.contrib.auth import update_session_auth_hash # Create your views here. @login_required def home(request): return HttpResponse('<h1>Welcome to your first page<h1>') def registration(request): print request print 'request' if request.method == 'POST': #save the user data … -
Search multiple models (Elasticsearch)
i added a second model to my app and now i also want to search trough the fields for that model and return it in the same view as my first model. views.py #Elasticsearch def globalsearch_elastic(request): qs = request.GET.get('qs') page = request.GET.get('page') if qs: qs = PostDocument.search().query("multi_match", query=qs, fields=["title", "content", "tag"]) qs = qs.to_queryset() else: qs = '' paginator = Paginator(qs, 10) # Show 10 results per page try: qs = paginator.page(page) except PageNotAnInteger: qs = paginator.page(1) except EmptyPage: qs = paginator.page(paginator.num_pages) return render(request, 'MyProject/search/search_results_elastic.html', {'object_list':qs}) currently only PostDocument get searched for a match, how do i add a second one here from documents.py in this function? or to be more specific, what do i have to change in this line to Search multiple documents? qs = PostDocument.search().query("multi_match", query=qs, fields=["title", "content", "tag"]) Thanks in advance -
Django logging to wxpython window?
I'm writing a utility to start up a django server process that outputs its logs to a TextCtrl in a wxpython window. Unfortunately, a couple different approaches have led to weird issues where the operating system (OSX in this case) crashing the program with complaints about "Illegal Instruction" after a few successful log entries. I'm currently doing this by implementing a logging.Handler subclass that posts events to wx that contain the logging records to be shown in the window. Is there a better approach? Thanks! -
.env file in pipenv (django) - ValueError: embedded null character
I got a .env file inside my project SECRET_KEY="vvvvvvvtestvvvvv" I run pipenv shell But I get like a bunch of errors. File "c:\users\sander-pc\appdata\local\programs\python\python37\lib\site-packages\pipenv\core.py", line 172, in load_dot_env dotenv.load_dotenv(dotenv_file, override=True) File "c:\users\sander-pc\appdata\local\programs\python\python37\lib\site-packages\pipenv\vendor\dotenv\main.py", line 262, in load_dotenv return DotEnv(f, verbose=verbose).set_as_environment_variables(override=override) File "c:\users\sander-pc\appdata\local\programs\python\python37\lib\site-packages\pipenv\vendor\dotenv\main.py", line 105, in set_as_environment_variables os.environ[k] = v File "c:\users\sander-pc\appdata\local\programs\python\python37\lib\os.py", line 684, in __setitem__ self.putenv(key, value) What am I doing wrong? -
I'm trying to output a filtered list on my Django template
For example, I have in models.py: class Development(models.Model): id = models.AutoField(primary_key=True) client = models.ForeignKey(InsName, on_delete=models.SET_NULL, null=True, blank=True) platform = models.ManyToManyField(Platform) user = models.ForeignKey(User, on_delete=models.CASCADE) and in views.py (with the corresponding url added to urls.py): class DevelopmentFilterView(generic.ListView): model = Development How do I tell my template to only output a list of the database entries for a certain client? -
Django-filter best practice on model field choice filter
I am struggling with an issue that I would think is pretty common but on which i couldn't find any working example. Say I have a Django Model : class Shop(models.Model): name = models.CharField(max_length=100, verbose_name="Shop Name") ... city = models.CharField(max_length=100, verbose_name="City") ... class Meta: verbose_name = "Chantier" What would be the best way to allow the user to filter Shops by City using django-filter ? So far I've used ModelMultipleChoiceFilter with the widget CheckboxSelectMultiple, but for some reason I'm struggling with getting a clean list of choices (no duplicates) and linking the filtered values to an actual filter query that works (without having to do some complex things). Is there an easy way to do this ? Thanks ! -
Checkbox data not coming through in django
I have a html template with multiple checkboxes, when i run request.POST.getlist(), I get an empty list back regardless of what checkboxes are selected. view class: class AddNewDevice(TemplateView): def get(self, request, *args, **kwargs): context = {} context['devices'] = get_devices(request.user) return render(request, self.template_name, context) def post(self, request, *args, **kwargs): post_data = request.POST print(request.POST.getlist('devices_selected')) save_data(request.POST.getlist('devices_selected')) return redirect('/dashboard.html') html form: <form method='POST'> {% csrf_token %} <div class="card mb-3"> <div class="card-header"> <i class="fas fa-table"></i> devices</div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th></th> <th>Serie Nummer</th> <th>Gebouw</th> <th>Locatie</th> </tr> </thead> <tbody> {% for device in devices %} <tr> <td> <input type="checkbox" value="{{obj.serial_number}}" name="devices_selected"> </td> <td>{{device.serial_number}}</td> <td>{{device.device_building}}</td> <td>{{device.device_location}}</td> </tr> {% endfor %} </tbody> </table> </div> </div> <div class="card-footer small text-muted">Geupdate om 12:00 uur</div> </div> <br> <button type="submit" class="btn btn-primary">Toevoegen</button> <br> </form> As i stated earlier request.POST.getlist('devices_selected') returns an empty list, regardless of what is selected. I want a list with all the values (obj.serial_number) from the selected checkboxes. -
Django 2.1 error while executing makemigrations
I am on my way to move to Django 2.1.5 with Python 3.7 from Django 1.6.0 with Python 2.7 and encountered an error while executing python manage.py makemigrations myapp. Could anyone give me a hint to solve, please? I probably need to modify the model but am not sure what I should start with. Migrations for 'model': model/migrations/0001_initial.py - Create model XXXX - Create model YYYY - Create model ZZZZ Traceback (most recent call last): File "manage.py", line 7, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/makemigrations.py", line 184, in handle self.write_migration_files(changes) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/makemigrations.py", line 222, in write_migration_files migration_string = writer.as_string() File "/usr/local/lib/python3.7/site-packages/django/db/migrations/writer.py", line 151, in as_string operation_string, operation_imports = OperationWriter(operation).serialize() File "/usr/local/lib/python3.7/site-packages/django/db/migrations/writer.py", line 110, in serialize _write(arg_name, arg_value) File "/usr/local/lib/python3.7/site-packages/django/db/migrations/writer.py", line 62, in _write arg_string, arg_imports = MigrationWriter.serialize(item) File "/usr/local/lib/python3.7/site-packages/django/db/migrations/writer.py", line 279, in serialize return serializer_factory(value).serialize() File "/usr/local/lib/python3.7/site-packages/django/db/migrations/serializer.py", line 37, in serialize item_string, item_imports = serializer_factory(item).serialize() File "/usr/local/lib/python3.7/site-packages/django/db/migrations/serializer.py", line 197, in serialize return self.serialize_deconstructed(path, args, kwargs) File "/usr/local/lib/python3.7/site-packages/django/db/migrations/serializer.py", line 85, … -
Django 2.0 custom middleware process_exception hook not firing
My custom middleware class seems to be skipping the process_exception stage during the response cycle from django.utils.deprecation import MiddlewareMixin class MyMiddleware(MiddlewareMixin): def process_request(self, request): print("Request!") def process_response(self, request, response): print("Response!") return response def process_exception(self, request, exception): print("Exception!") Middleware configured.... DJANGO_MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', ] LOCAL_MIDDLEWARE = [ 'path.to.MyMiddleware', ] MIDDLEWARE = DJANGO_MIDDLEWARE + LOCAL_MIDDLEWARE and buried in my view code: def some_view(request): ... raise Exception("foo") However when I hit the url I get this in the console log: Request! Internal Server Error: /my/url/ Traceback (most recent call last): ... long traceback ... File "/path/to/my/views.py", line 184, in some_view raise Exception("foo") Exception: foo ERROR django.request 2019-01-24 11:50:48,270 [exception.py handle_uncaught_exception 118] Internal Server Error: /my/url/ Traceback (most recent call last): ... long traceback ... File "/path/to/my/views.py", line 184, in some_view raise Exception("foo") Exception: foo Response! As you can see, process_exception isn't called at all, process_request and process_response both. And for some reason the exception traceback is shown twice before my middleware's process_response is even hit. The response that is passed to process_response for my middleware is a standard Django 500 debug page suggesting that the exception has been handled already, but I was under … -
Creating a new model object populating a form
I made another post before about this but I think I explained myself wrong. I have my class called 'Empresa'. Users of the webpage can registrate their own company ('Empresa') by populating a ModelForm in a view. The problem is that I can't find the syntaxis anywhere. I have: models.py: from django.db import models class EmpresaManager(models.Manager): def create_empresa(self): empresa = self.create() return empresa class Empresa(models.Model): codigo = models.CharField(max_length=3, null=False, default='000') nombre = models.CharField(max_length=100, null=False, default='Sin nombre') email = models.EmailField(null=False, default='email@empresa.com') direccion = models.CharField(max_length=100, null=False, default='Sin direccion') localidad = models.CharField(max_length=100, null=False, default='Sin localidad') codDgi = models.SmallIntegerField(null=True) docDgi = models.CharField(max_length=13, null=True) sIva = models.CharField(max_length=1, null=True, default='1') mesCierre = models.IntegerField(null=True, default=0) fecIni = models.DateField(null=True) ruca = models.IntegerField(null=True) novedad = models.CharField(max_length=50, null=True, default='') fecNovedad = models.DateTimeField(null=True) ultVersion = models.CharField(max_length=20, null=True, default='') logo = models.ImageField(null=True) habilitado = models.CharField(max_length=1, null=True, default='S') codEmpresa = models.CharField(max_length=3, null=True) codComp = models.CharField(max_length=3, null=True, default='') objects = EmpresaManager() forms.py: from django import forms from django.forms import ModelForm from .models import Empresa class RegistroEmpresaForm(ModelForm): class Meta: model = Empresa fields = ["nombre", "docDgi", "email"] views.py: from django.shortcuts import render from Empresa.forms import RegistroEmpresaForm from Empresa.models import Empresa from django.http import HttpResponse def registrado(request): form = RegistroEmpresaForm(request.POST or None) titulo = "Registro SIG … -
Django Monitoring Web App IoT project using LoRaWAN with Arduino+Dragino nodes
I have a project "Django Monitoring Web App IoT project using LoRaWAN with Arduino+Dragino nodes". And I would like to ask what limitations will I have, if it is possible for 100% to pull/push data to the app and how does this concept seems to be. I have something like this in mind Whole concept. I appreciate any help and advice. Thank you very much!