Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModelFormSet CSS isn't being applied
Here's my code: models.py class InitialConditionsCheck(models.Model): Choices = (('yes', 'Yes'), ('no', 'No')) initial_bool = models.BooleanField(default=False, choices=Choices) values = models.ForeignKey(Values, on_delete=models.CASCADE) forms.py class InitialConditions(forms.ModelForm): class Meta: model = InitialConditionsCheck fields = ['initial_bool'] widgets = { 'initial_bool': forms.RadioSelect(attrs={'class': 'form-check-input', 'id': 'id_initial_bool', 'autocomplete': 'off', 'name': 'Radio'}) } initial_conditions_formset = modelformset_factory(InitialConditionsCheck, form=InitialConditions, extra=0) views.py formset = initial_conditions_formset(queryset=InitialConditionsCheck.objects.filter(values_id=values_id)) context = {'Formset': formset} return render(request, '/view.html', context} view.html {% for form in formset %} {{ form }} {% endfor %} I'm able to get the CSS to render properly with just the ModelForm but the ModelFormSet isn't working as intended. I've tried generating it in the html using {% for form in formset %} {% for field in form %} {{ field.label_tag }} {{ field }} {% endfor %} {% endfor %} Here's the code that I have for the ModelForm which generates the CSS properly, which I tried incorporating with the FormSet with no luck {% for radio in Initial_Conditions_Bool.initial_ <div class="form-check form-check-inline"> {{ radio.tag }} <label class="form-check-label" for="{{ radio.id_for_label }}">{{radio.choice_label}}</label> </div> {% endfor %} -
Dynamically set Django settings variables from Database
I am currently trying to build an application that manages multiple databases. Since the app will be managing data in 30+ databases I am attempting to generate DATABASE_ROUTERS in the settings file. I cannot directly import the db model into the settings file. I get this error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. This error makes since. Is there a way I can control the sequence of events so that I have access to the database before all of the settings are established on execution? My goal is to automate database connections pulling relevant data from a DB and generate the DATABASE_ROUTERS and DATABASES within the setting file. Is this even possible? Is there a package that I can download that does exactly this? If you do not know what I am asking please do not down vote just ask me to elaborate. -
Django Admin list values from many to many fields
For a podcast site I do have a Guest model which (stripped down) looks like this. class Guest(models.Model): ... episodes = models.ManyToManyField(Episode) name = models.CharField(max_length=100, blank=False) ... also there are a few other models connected through many to many fields with the guest model like Job and Topic (simple models with one or two CharField with some information and the ManyToManyField relation with Guest. Now I want to display The Job(s) of a guest and his Topics in the Admin List of Guests. Also for the linked Episodes Model I want to count the amount of episodes a guest was in and also show the date (published_at field in Episode model) of the newest and the oldest Episode the guest was in. I tried a few things already but I can't seem to get the data from the many to many fields into that list display. I'm on Django 2.0.7 -
Django WhiteNoise module not found
I'm using Docker to deploy my application and for some reason every time my Django server keeps returning the following error: ImportError: No module named 'whitenoise', even though it says that the module is already installed: Requirement already satisfied: whitenoise in /usr/local/lib/python3.5/dist-packages (3.3.1). Any help on this issue is greatly appreciated. -
Not able to implement hide and show functionality with django
My functionality is that I have a radio button in my form. If user clicks Yes, he should get an error on the screen suggesting that this is not a right place to submit your data and suggest him to visit other website In case he clicks No, all the other fields in the form should become visible and mandatory. My issue is when I click on No and try to submit without filling all the fields in the form, form gets reloaded and fields are hidden again. Yes, the data is not getting saved in the DB and when I click No, fields are displayed again with errors highlighted. My main concern is when I click No and all the fields are displayed, I don't want them to be hidden again until the form is submitted successfully or user click Yes. I need a solution so that form gets reloaded only when all the fields are correct and submitted successfully to the DB. I will also share the code that I have written so far for better understanding: 1) models.py from __future__ import unicode_literals from django.db import models from bokeh.themes import default from django.contrib.auth.models import User from django.db.models.signals import … -
Python Django video stream control duration
I start to develop small video tube using Django. I have full time video, e.g. 30min., for member zone. I would like to show only 3min (e.g. from 3rd to 6th min) chunk from this video in public zone for non-reg users. I can cut video and have two copies on HDD: full time and 3min chunk. But I'm interested to have one full time video and limit duration on fly on code level (server side). I can't find libs doing something like this. Any ideas? Thanks. -
Django Staticfiles doesn't load at digitalocean but in local
I have a django python app in a digital ocean server. I am using virtualenv and gunicorn within an Nginx server. My app is working now but I am not succesfull collecting static files. In my vagrant using the server in django python manage.py runserver 0:8000 all works perfectly. When I upload it to my Nginx server the static files are not found. My server structure is the following: At /var/www/computationalMarketing drwxr-xr-x 3 root root 4.0K Jul 10 11:43 bin drwxr-xr-x 8 root root 4.0K Jun 28 14:11 computationalMarketing drwxr-xr-x 2 root root 4.0K Jun 28 10:11 include drwxr-xr-x 3 root root 4.0K Jun 28 10:11 lib lrwxrwxrwx 1 root root 3 Jun 28 10:11 lib64 -> lib -rw-r--r-- 1 root root 69 Jun 28 10:11 pyvenv.cfg drwxr-xr-x 3 root root 4.0K Jun 28 10:11 share bin is the path of my virtualenv computationalMarketing is a folder that contains my Git repo The structure of my repo is: -rw-r--r-- 1 root root 91 Jun 28 13:19 Procfile -rw-r--r-- 1 root root 1.2K Jun 28 13:19 README.md drwxr-xr-x 3 root root 4.0K Jun 28 14:13 code -rw-r--r-- 1 root root 189 Jun 28 13:19 requirements.txt -rw-r--r-- 1 root root 12 Jun … -
Improve numerous choices in django
I'm working with choices in Django. I need to improve a lot of choices (exactly 48), and I want to know if there's a better way to do that, instead of the way that I'm trying to do it, because I think that the way I'm trying is not really optitum and is not visually appealing. nota_35="Acoustic Bass Drum" nota_36="Bass Drum 1" nota_37="Side Stick" nota_38="Acoustic Snare" nota_39="Hand Clap" Notas=((nota_35,'Acoustic Bass Drum'),(nota_36,'Bass Drum 1'),(nota_37,'Side Stick'),(nota_38,'Acoustic Snare'),(nota_39,'Hand Clap')) notas=models.CharField(max_length=20, choices=Notas) This is an example. The real problem has, as I said 48 options, and each choice has his own option. -
Nginx, Gunicorn, Django: CSS styling not appearing in IE
I have a Django 2.0 project intended for my work Intranet. I moved the project over to the dedicated Ubuntu 16.04 server. I am new to Gunicorn/Nginx but it was fairly easy to configure and get it running. Everything looks fine in Chrome/Mozilla but in IE there is no CSS styling. If I run the Django development server from the production box, everything looks fine in all browsers. It is only when I run the app through Gunicorn/Nginx that IE sees no CSS styling (Chrome/Mozilla look fine?!). I am not even sure where to start with this one. Has anyone seen this before? Thanks in advance! -
django 2.0 NoReverseMatch in URL template tag
I get a NoReverseMatch exception while trying to call a view using the URL tag in a django template. The code is very minimal becouse I stripped it down to the bare bones hoping to fix the issue. I'm trying to link a view inside a template using the URL tag: prova.html: <a href="{% url 'prova2' %}">Prova</a> views.py def prova2(request): return render(request, 'prova/prova.html') relevant line from urlpatterns[] in urls.py url(r'^prova2/$', views.prova2, name='prova2'), The error I get calling the "prova" view Request Method: GET Request URL: http://127.0.0.1:8000/prova2/ Django Version: 2.0.6 Python Version: 3.4.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'prova'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /vagrant/prova/templates/prova/prova.html, error at line 1 Reverse for 'prova2' not found. 'prova2' is not a valid view function or pattern name. 1 : <a href=" {% url 'prova2' %} ">Turn OFF</a> Traceback: File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/vagrant/prova/views.py" in prova2 43. return render(request, 'prova/prova.html') File "/usr/local/lib/python3.4/dist-packages/django/shortcuts.py" in render 36. content = loader.render_to_string(template_name, context, request, using=using) File "/usr/local/lib/python3.4/dist-packages/django/template/loader.py" in render_to_string 62. return template.render(context, request) File … -
Django modelform - make a modelform that provides a choice based on other models
I want a ModelForm called AddManualVariantForm which is a modelform of my model VariantAnnotationSampleRun. This model is foreign key linked to VariantAnnotation and SampleRun models: class VariantAnnotationSampleRun(models.Model): variant_annotation_id = models.ForeignKey(VariantAnnotation, on_delete=models.CASCADE, db_column='variant_annotation_id') sample_run_id = models.ForeignKey(SampleRun, on_delete=models.CASCADE, db_column='sample_run_id') I want to make a modelform which will CREATE a VariantAnnotationSampleRun instance. Basically, I want to display 5 'VariantAnnotation' instances in relation to 1 SampleRun on my page, and if the user selects a checkbox, create a VariantAnnotationSampleRun instance. Firstly - am i correct in doing this as a VariantAnnotationSampleRun modelform? Here is what I am trying at the moment: forms.py: class AddManualVariantForm(forms.ModelForm): report = forms.ChoiceField( choices =( ("dontreport", '-'), ("report" , 'Report'), ("toconfirm", 'To confirm') ), label = 'report' ) class Meta: model = VariantAnnotationSampleRun fields = ('id', 'report') def __init__(self, *args, **kwargs): sample_obj = kwargs.pop('sample_obj', None) super(AddManualVariantForm, self).__init__(*args, **kwargs) views.py: class VariantSampleRunList(LoginRequiredMixin, View): addvariantform = AddManualVariantForm def get(self, request, *args, **kwargs): va_lst = [..list of VariantAnnotation IDs I want to include...] FormSet = modelformset_factory( VariantAnnotationSampleRun, form=self.addvariantform, extra=0 ) formset = FormSet( queryset = VariantAnnotation.objects.filter(id__in=va_lst), # form_kwargs={'sample_run_obj':sample_run_obj} ) This displays the VariantAnnotation instances I want on my page, in a formset, but the 'id' is that of a VariantAnnotation object - NOT … -
How do I query a pair of objects from a single Django Model efficiently?
I have a Track model and currently I do a nested loop through the models id to get the pair and then pass it into a function to count the similarity between these two non-equivalent track object track_set = Track.objects.all() track_ids = [track.id for track in track_set] pointer_a = 0 pointer_b = 1 counter = 0 for pointer_a in range(len(track_ids) - 1): for pointer_b in range(pointer_a + 1, len(track_ids)): track_a = Track.objects.get(pk=track_ids[pointer_a]) track_b = Track.objects.get(pk=track_ids[pointer_b]) counter += 1 count_it_sim(track_a, track_b, counter) I think the way I get the object is not very efficient, is there any way to optimize it ? -
how to get full name of users in template with a ModelMultipleChoiceField
I have a form look like this: class ProjectForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProjectForm, self).__init__(*args, **kwargs) members = forms.ModelMultipleChoiceField( label="Projets", queryset=User.objects.all(), widget=forms.CheckboxSelectMultiple, required=False, ) class Meta: model = Project fields = ['title', 'description', 'objective', 'duration', 'members'] and this is a portion from my template {% for pk, member in project_form.members.field.widget.choices %} <tr> <td> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="id_members_{{forloop.counter0}}" value="{{pk}}"> <label class="custom-control-label" for="id_members_{{forloop.counter0}}">{{member.first_name}}</label> </div> </td> </tr> {% endfor %} I want to get the full name of every user not the username, how can I do this. -
Django registration with a phone number
I have a Django project and a Django REST in the backend and vue js on the client side. I want to use my phone number for registration and login quality. How can I do this if I'm sorry if someone is doing it earlier? I will be happy for your advice, and sorry for my English. -
TemplateSyntaxError django
I added a new custom template filter for my django app but I get the error I added my_filters.py in templatetags directory in the app directory. It also contains the init.py file 'my_filters' is not a registered tag library. Must be one of: admin_list admin_modify admin_static admin_urls cache compress i18n js keyvalue l10n log mul rest_framework static staticfiles tz -
There's no actions feedback when sending request using ajax
I am send a request using ajax the html part: <a id="delArticleLink"><span class="glyphicon glyphicon-trash" aria-hidden="true">delete</span></a> <hr> and the javascript: <script> $("#delArticleLink").on("click", function(e){ e.preventDefault(); if ( confirm("Delete this article?") ) { $.ajax({ type: "GET", url: {% url "article:article_del" article.id %}, success: function(data){ var ret = JSON.parse(data); if ( ret['status'] == 1) { window.location.href = "{% url 'article:article_list' article.block_id %}"; } else { alert(ret['msg']); } }, }); } else{ e.preventDefault() } }); </script> However, when I lick the delete link, there's no actions feedback. jQuery is imported properly. -
How to create a search with CheckboxSelectMultiple that can be empty
Hi guys I'm trying to create a search, it will have some CheckboxSelectMultiple. The problem is when one of the field is empty it returns me an error MultiValueDictKeyError at /technology/ but when I select one of each field it works normally but when I try to paginate I get this error MultiValueDictKeyError at /technology/ as well form.py class TechnologySearchForm(forms.Form): CATEGORY_CHOICES = ( (0,'Acabada'), (1,'Em Desenvolvimento'), ) KIND_CHOICES = ( (0, 'Produto'), (1, 'Processo'), (2, 'Software') ) PATENT_CHOICES = ( (0,'Depositada'), (1,'Licenciada'), (2,'Não Possui') ) PATENT_TYPE_CHOICES = ( (0, 'Patente De Invenção'), (1, 'Modelo de Utilidade') ) title = forms.CharField(label="Título", max_length=50, required=False, widget=forms.TextInput(attrs={'class':'form-control'})) description = forms.CharField(label="Descrição", max_length=50, required=False, widget=forms.TextInput(attrs={'class':'form-control'})) application_area = forms.CharField(label="Área de Aplicação", max_length=50, required=False, widget=forms.TextInput(attrs={'class':'form-control'})) category = forms.ChoiceField(label="Categoria", choices=CATEGORY_CHOICES, widget=forms.CheckboxSelectMultiple(),required=False) kind = forms.ChoiceField(label="Tipo de Tecnologia", choices=KIND_CHOICES, widget=forms.CheckboxSelectMultiple(),required=False) patent = forms.ChoiceField(label="Patente", choices=PATENT_CHOICES, widget=forms.CheckboxSelectMultiple(),required=False) patent_type = forms.ChoiceField(label="Tipo de Patente", choices=PATENT_TYPE_CHOICES, widget=forms.CheckboxSelectMultiple(),required=False) my list view class TechnologyListView(LoginRequiredMixin, ListView): model = Technology template_name = "technology/technology.html" paginate_by = 6 def get_context_data(self, **kwargs): data = super(TechnologyListView, self).get_context_data(**kwargs) data['imagearea'] = self.request.GET data["filter_form"] = TechnologySearchForm(self.request.GET) return data def get_queryset(self, *args, **kwargs): qs = super(TechnologyListView, self).get_queryset(*args, **kwargs) query = self.request.GET queryset = Technology.objects.filter(user=self.request.user) if query: qs = queryset.filter( Q(title__icontains=query['title']) & Q(description__icontains=query['description']) & Q(category__in=query['category']) | Q(kind=query['kind']) | Q(patent__exact=query['patent']) … -
Django image tools / Pillow, empty image name / file path
Using Django (Rest Framework), with the library django-image-tools (DIT), which uses an ImageField, I try to programatically create a new Image instance. To be clear, both django-image-tools (DIT) and Pillow have their own Image model. The above Image instance is the DIT Image model. While trying to create a new DIT Image instance (code will follow below), I get the following error: FileNotFoundError: [Errno 2] No such file or directory: '' Which seems to imply trying to access a file path which equals an empty string. Full traceback can be found below So, I started digging in the source code to find out what is going wrong. The best way to ask my question is to show the actual code in question. But this is my main question, and the code below should make it more clear if it isn't initially: How can I have DIT get the correct file path? Full traceback of the error: Traceback (most recent call last): File "manage.py", line 16, in <module> execute_from_command_line(sys.argv) File "C:\Users\riksch\Documents\MEGAsync\projects\Current\greenery-marketplace\backend\venv\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\riksch\Documents\MEGAsync\projects\Current\greenery-marketplace\backend\venv\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\riksch\Documents\MEGAsync\projects\Current\greenery-marketplace\backend\venv\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\riksch\Documents\MEGAsync\projects\Current\greenery-marketplace\backend\venv\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) … -
Is it possible to have modelformsets generate forms within another for loop
What I'm trying to do is to get a ModelFormSet to generate a Form within a for loop of another Jinja for loop, as I'm dynamically generating some data and need a form to be generated with each piece of data. The input would only be generated once, which is where I'm having trouble since the FormSet docs have all the forms generated together. Here's what I'm currently doing: <form action="#testingg" method="POST" role="form"> {% csrf_token %} {% for foo in Foo %} <li class="box"> <div class="row"> <div class="col"> {{ foo.description }} </div> <div class="col"> <!-- Form input would go here --> </div> </div> </li> {% endfor %} <input type="submit" value="submit"> </form> What I was wondering is if it's possible to generate a ModelForm without it being in a For loop as the docs specify, or would I have to generate the ModelForm alongside foo in the for loop. Or could I just insert the ModelForm without it being generated by the formset_factory. Additionally, say that in one instance of the loop I have to generate one form and in another I have to generate two forms, is this possible using formsets? -
Django - What is the best way to store in the DB answers that can be numerical or text?
I'm working on a student survey project. The model that stores the questions is something like: ID Question Type 1 is good teacher? Choice 2 What do you like about Open-answer the teacher? Then in the choice type questions the student will choose an option (e.g.: fully agree) and this will store a numerical code (e.g. 5). But in the open-answer questions , the student will write text. what kind of field should store these answers in the answers model? maybe TextField? -
invalid literal for int() with base 10 in django
I'm trying to make a profile page with an <owner> argument in the link the owner in the models is a ForeignKey to the user but with any value i submit it saids invalid literal for int() with base 10: models.py owner = models.ForeignKey( User, related_name="user_profile_user_key", verbose_name="owner of the profile", blank=False, null=False, on_delete = models.CASCADE, ) views.py def my_profile(request, owner): template='my_profile.html' context = { 'profile' : get_object_or_404(UserCommunityProfile, owner=owner), } return render(request, template, context) -
Django queryset convert into dictionary
I'm looking for a way to directly convert a Django queryset into a dictionary with required fields. For example, I've got a model Test - class Test(models.Model): test_id = models.AutoField() test_name = models.CharField(max_length=50) test_author = models.CharField(max_length=50) I want to get only the test_name and test_author for a filtered queryset. I know I can do - objs = Test.objects.filter(test_id__in=test_ids) res_dict = map(lambda x: {'name': x.test_name, 'author': x.test_author}, objs) But I wanted a way to do the above in the database directly, chaining it to the filter method. I looked into the docs, but couldn't find any such method. Thank you! -
Django router retrieve specific account
This code works for retrieving the entire list of accounts with localhost:8000/accounts/, but not for a specific account when given the email associated with the account (localhost:8000/accounts/[email of account]/. Instead, the data sent back is an HTML file. Sometimes if I put in an email that doesn't exist, it tells me the detail was not found. But only sometimes. Any help would be greatly appreciated! Here are my different files: VIEWS.PY class AccountViewSet(views.ModelViewSet): lookup_field = 'email' queryset = Account.objects.all() serializer_class = AccountSerializer URLS.PY router = routers.SimpleRouter() router.register(r'accounts', AccountViewSet) url patterns = [ url(r'api/v1/', include(router.urls)), ] MODELS.PY class Account(AbstractBaseUser): email = models.EmailField(unique=True) name = models.CharField(max_length=40, blank=True) objects = AccountManager() -
Django Restframework(drf) Bulk Update not working?
I am using djangorestframework-bulk to perform bulk update have followed documentation DRF-Bulk but for me update wasnt working.. it says, File "/webapps/env_apibot/local/lib/python2.7/site-packages/rest_framework_bulk/drf3/serializers.py", line 43, in <dictcomp> for i in all_validated_data KeyError: 'my_pk' my configuration was, views.py class MymodelBulkViewSet(BulkModelViewSet): model = Mymodel queryset = Mymodel.objects.all() serializer_class = MymodelBulkSerializer serializers.py class MymodelBulkSerializer(BulkSerializerMixin): class Meta: model = Mymodel list_serializer_class = BulkListSerializer update_lookup_field = 'my_pk' but it raise 400 error and it says, key error my_pk not found.. drf version 3.3.2 django 1.8.9 -
Specify startapp() function in a ASGI application
i am working on a web application made in python 3.5 and javascript. The goal of the application is to display in real time data sent by some raspberry PI running under different protocols (MQTT, XMPP and CoaP). I tell my django server to make get request to differents servers which handles different protocols, then save those data into a database that i can finally retrieve into my redux store and then display those on my client. So at the beginning i was working with a WSGI app and the i heard about ASGI so it seemed it was the best solution for what i wanna do. However after make the transition i've noticed that the application doesn't run anymore my function StartApp() which is supposed to get datas from the raspberry pi. before i had the wsgi.py : import os from django.core.wsgi import get_wsgi_application from Dashboard.pySharkToDb.LAN_to_DB import StartApp os.environ.setdefault("DJANGO_SETTINGS_MODULE", "IOT-Testbed-Dashboard.settings") StartApp() application = get_wsgi_application() is there any way to specify the ASGI app a function to run when i launch the application ?