Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM: `TruncDate` on the *left* hand side?
The TruncDate and similar functions can be used on the right hand side of an equality expression, eg ...my_query.values(date_only=TruncDate(timestamp)) But how could I use it on the left-hand side for filtering. Eg, how do I do something like ...my_query.filter(TruncDate('timestamp') <= arg) where timestamp is the model's own field, and arg is an external timestamp value passed from a function -
Django- database is not updated with foreign key values - django-excel
I am using django-excel to import data for samples model except for the area which is a select field. User can upload the file by selecting the area which it belongs to. Error- However after clicking on submit, area shows a null value Models -- class Area(models.Model): Area = models.CharField(max_length=15, null=True, verbose_name='area') def __str__(self): return self.Area class samples(models.Model): transaction_Gldescription = models.CharField(max_length=15) transaction_GlCode = models.CharField(max_length=15) transaction_date = models.DateTimeField(auto_now=True) Area = models.ForeignKey('area', on_delete=models.CASCADE, null=True) def __str__(self): return self.transaction_Gldescription View - def import_data(request): if request.method == "POST": form = SamplesForm(request.POST,request.FILES) if form.is_valid(): form.save() request.FILES['samplesfile'].save_book_to_database( models=[samples], initializers=[None], mapdicts=[ ['transaction_Gldescription', 'transaction_GlCode', 'transaction_date']) return redirect('question') else: return HttpResponseBadRequest() else: form = SamplesForm() return render(request, 'upload_form.html', { 'form': form, 'title': 'Import excel data into database example', 'header': 'Please upload sample-data.xls:' }) Forms - class SamplesForm(forms.ModelForm): samplesfile = forms.FileField(label = 'Upload samples as per the format') class Meta: model = samples fields = ["Area"] -
Specific DB Access Query Optimisation
In [14]: from accounts.models import CustomUser In [15]: CustomUser.objects.filter() Out[15]: <QuerySet [<CustomUser: nimish4july1998@gmail.com,Nimish,(9)>, <CustomUser: company1@gmail.com,Escale,(10)>, <CustomUser: adv1@gmail.com,advertiser1,(16)>, <CustomUser: adv2@gmail.com,,(17)>, <CustomUser: adv3@gmail.com,,(18)>, <CustomUser: adv4@gmail.com,,(19)>, <CustomUser: adv5@gmail.com,,(20)>, <CustomUser: ok@gmail.com,,(33)>, <CustomUser: pub_company1@gmail.com,,(34)>, <CustomUser: ,,(35)>, <CustomUser: employee1@gmail.com,,(40)>, <CustomUser: employeeno1@gmail.com,,(41)>, <CustomUser: adv500@gmail.com,,(42)>]> In [17]: CustomUser.objects.using("company1") Out[17]: <QuerySet [<CustomUser: nimish4july1998@gmail.com,Nimish,(9)>, <CustomUser: company1@gmail.com,Escale,(10)>, <CustomUser: adv1@gmail.com,advertiser1,(16)>, <CustomUser: adv2@gmail.com,,(17)>, <CustomUser: adv3@gmail.com,,(18)>, <CustomUser: adv4@gmail.com,,(19)>, <CustomUser: adv5@gmail.com,,(20)>, <CustomUser: ok@gmail.com,,(33)>, <CustomUser: pub_company1@gmail.com,,(34)>, <CustomUser: ,,(35)>, <CustomUser: employee1@gmail.com,,(40)>, <CustomUser: employeeno1@gmail.com,,(41)>, <CustomUser: adv500@gmail.com,,(42)>]> In [18]: CustomUser.objects Out[18]: <django.db.models.manager.Manager at 0x7ff0906fa1d0> So my question is that when we want to use a specific db as soon as we apply function using() we see the whole queryset.On the other hand using it normally like CustomUser.objects it doesnot return queryset unless we apply filter so does that mean for a specific database we are able to see the whole queryset and then we have to apply filter will not make query fast.Actually I am confused that will there be any difference if there are same no of records in "default db" and "company1 db" and exactly same data, will one query be faster than the second or not? -
How to display messages using the messages framework in Django using a background job?
I am running background tasks in my Django app using Django Background Tasks, which is checking from a Django model if a particular deadline is crossed. @background(schedule=10000) def check_deadline(repeat=30000): # Check if deadline has crossed from DB # Return the record's title whose deadline has crossed If the condition is satisfied, then the background task must send a message to any template that is being currently viewed. I am not sure how to send a message to the template from the background task. -
Django Postgres Array Field - Count number of overlaps?
I have Article model that contain a keywords field which is an ArrayField of a list of keywords in sorted ascending order. I want to do a query that finds all articles that have a minimum amount of keywords overlapping. Example: article_a = Article(keywords=["tag1", "tag2", "tag3"] article_b = Article(keywords=["tag1", "tag2", ] article_c = Article(keywords=["tag1", ] article_a.find_similar_articles(min_overlap=2) # Returns [article_b, ] since it overlaps with at least 2 elements. There is a similar question here that is for general Postgres, not for the Django ORM. Anyone know how I can query the Array Field in this way? Or perhaps you have a suggestion of another way to achieve the same result by structuring the data in another manner? -
Pass a template variable to django url using jquery
Is it possible to pass a template variable to a django url with jquery? I've tried the standard way of passing the parameter to the django url, but I get a no reverse match. Javascript <button id = "testid" href = "{%url 'test:justatest' id=8}">Click here for something</button> <script type="text/javascript"> var btn = $('#testid'); btn.click(function (e) { var goto = $(this).attr('href'); e.preventDefault(); $.ajax({ url: goto, type: "GET", success: function(data){ console.log(data); alert(data); }}); }); </script> urls.py path('test/<int:id>',views.TestDetail.as_view(),name="justatest") I also tried this based off this post but I just get a 404. <button id = "testid" href = "{%url 'test:justatest'%?id=8}">Click here for something</button> <script type="text/javascript"> var btn = $('#testid'); btn.click(function (e) { var goto = $(this).attr('href'); e.preventDefault(); $.ajax({ url: goto, type: "GET", success: function(data){ console.log(data); alert(data); }}); }); </script> -
def form_valid for django rest framework
I am new to Django Rest Framework. I have been using regular Django I want something similar to Django's CreateView for this model. Intro: The superuser is the only user. All patients belong to the user and Embryos belong to the patient. One patient can have multiple embryos. Below are my models class Patients(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=35) email = models.EmailField(unique=True) class Embryo(models.Model): patient = models.ForeignKey(Patients, on_delete=models.CASCADE) code_name = models.CharField(max_length=100) karyotype = models.CharField(max_length=100) GENDER_CHOICES = ( ("M", "Male"), ("F", "Female"), ) sex = models.CharField(max_length=1, choices=GENDER_CHOICES) I am trying to make create views for my models. Below is what I have so far class PatientsApiView(viewsets.ModelViewSet): """Handles Creating, reading and updating Patients""" serializer_class = serializers.PatientsSerializer queryset = Patients.objects.all() authentication_classes = (TokenAuthentication,) filter_backends = (filters.SearchFilter,) search_fields = ("first_name", "last_name", "phone", "email",) def form_valid(self, form, *args, **kwargs): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) """How can I get the above with Django Rest Framework. Can I do: def __getattr__(self, user): return self.request.user """ class EmbroApiView(viewsets.ModelViewSet): """Handles Creating, reading and updating Patients""" serializer_class = serializers.EmbryoSerializer queryset = Embryo.objects.all() authentication_classes = (TokenAuthentication,) filter_backends = (filters.SearchFilter,) search_fields = ("code_name", "karyotype", "sex", "down_syndrome",) def form_valid(self, form, *args, **kwargs): self.object = … -
Django model form with m2m field only showing one select box even im using FilteredSelectMultiple as the widget
Django model form with m2m field only showing one select box even im using FilteredSelectMultiple as the widget for that field . required admin filesbase files are added class ExamForm(forms.ModelForm): question_m2m = forms.ModelMultipleChoiceField(queryset=Question.objects.all(), label=('Select Question'), widget=FilteredSelectMultiple( ('question'), False, )) class Meta: model=Exam fields = ('question_m2m',) and static files are aded in base template <link href="{% static 'css/theme.css' %}" rel="stylesheet" media="all"> <script type="text/javascript" src="{% static 'js/jquery.min.js' %}"></script> <script type="text/javascript" src="{% static 'js/jquery.init.js' %}"></script> {{ examform.media }} {{form.media}} -
Get queryset of many-to-many field under another many-to-many field
I am working on a User/Role/Permission model in django, where the model structure is this. class GlobalPermission(BasicAbstractClass): TYPE_CHOICES = ["user_level", "platform_level", "user_platform_access_level"] short_code = models.CharField(max_length=64, blank=True, null=True) name = models.CharField(max_length=92, blank=True, null=True) description = models.CharField(max_length=189, blank=True, null=True) type = EnumField(choices=TYPE_CHOICES, blank=True, null=True) def __str__(self): return self.name class Meta: db_table = 'global_permission' class Role(BasicAbstractClass): ROLE_CHOICES = ["admin", "analyst", "moderator", "editor", "superuser", "developer"] SERVICE_CHOICES = ["social_media_management", "survey"] service = EnumField(choices=SERVICE_CHOICES) name = EnumField(choices=ROLE_CHOICES) permissions = models.ManyToManyField(GlobalPermission, related_name="role_permissions", blank=True, through="RolePermission") def __str__(self): return self.name + " of " + self.service class Meta: db_table = 'role' class RolePermission(models.Model): role = models.ForeignKey(Role, on_delete=models.CASCADE) permission = models.ForeignKey(GlobalPermission, on_delete=models.CASCADE) def __str__(self): return str(self.id) class Meta: db_table = "role_permissions" class UserAccount(models.Model): roles = models.ManyToManyField(Role, related_name="+", blank=True, through="UserRole") class UserRole(BasicAbstractClass): user = models.ForeignKey(UserAccount, on_delete=models.CASCADE) role = models.ForeignKey(Role, on_delete=models.CASCADE) def __str__(self): return str(self.id) class Meta: db_table = "user_role" What I want here, is to get the list of permissions of a user. Here, the user may be assigned multiple roles, and I want a queryset containing all the permissions for those roles. -
django.template.exceptions.TemplateSyntaxError: 'django_markdown' is not a registered tag library. Must be one of
After upgrading django2.1.3 and install 'django_markdown' This error throwing, when I'm going to add any user or to see details from Django admin panel. But I didn't use django_markdown in my project yet. So what should I do now for this problem? 'django_markdown' is not a registered tag library. admin_list admin_modify admin_static admin_urls cache i18n l10n log static staticfiles tz -
Django: how to get a dictionary from views.py into javascript function (html file)
Pretty new to html/ javascript but basically in my views.py, I have a dictionary object created from user form data: return render(request, 'graph/result.html', {'single_wv': single_wv}) How do I get that context variable into a javascript function (function is inside my html file)? **Basically I want: index.html form data --> obtained inside views.py with POST --> some manipulation --> dictionary --> dictionary set as context variable --> call inside same index.html javascript function Sorry if this question is kind of vague, I'm currently in the process of trying to figure everything out! -
Django get object from QueryDict
I have a model called barcard, and a form for selecting one of the barcards in the database. My objective is to get an instance of the selected barcard. I have the following code: models.py class Barcard(models.Model): name = models.CharField(max_length=30) drinks = models.ManyToManyField(Drink) barcardFile = models.FileField(blank=True, upload_to='barcard') mixingFile = models.FileField(blank=True, upload_to='mixing') def __str__(self): return self.name forms.py class BarcardGenForm(forms.Form): barcard = forms.ModelChoiceField(Barcard.objects.all()) views.py class BarcardSelect(FormView): template_name = 'drinks/home.html' form_class = BarcardGenForm success_url = 'download/' def form_valid(self, form): return super().form_valid(form) def barcardGen(request): if request.method =='POST': card = request.POST.get('barcard') barcardName = card.name card.generateFiles() return HttpResponseRedirect('drinks/download/?b='+barcadName) return render(request, 'drinks/download.html') When i use get() on the QueryDict, with the key 'barcard' it returns a string, with a number. It seems like the number correspond to the index, that the selected barcard has in the ModelChoiceField. I had hoped that the card variable would contain an instance of a barobject or a name, so i could make a query. -
How to provision one docker container per code branch for CD
We are using bitbucket pipelines for CI. I want to automate the CD flow such that whenever there is a push on a new/existing branch say feature_abc(normalized) the latest code of that branch be deployed using a Docker container on my ec2 box and mapped to a subdomain named same as the branch name, i.e. feature_abc.mydomain.com for the QA team to start testing that branch's upcoming changes. How to do it? Do I have to use fabric in the automation somewhere or docker-compose can do it? P.S.: I am seasoned Python/Django developer but new to Docker stuff. Have read a lot of dockerfile and docker-compose.yml stuff on the web and getting confused. -
django form initial with model
I am trying to load data from an instance of Model into a model form. The model has a date field. But there comes two date input for the field. View:iForm = InvoiceForm(instance = object); Template: {{iForm.as_table}} Form: class InvoiceForm(forms.ModelForm): class Meta: model = Invoice def __init__(self, *args, **kwargs): super(InvoiceForm, self).__init__(*args, **kwargs) self.fields['create_date'].widget.attrs['class'] = 'vDateField'; the created date is datefield. -
Loading Django static files via Apache
I know there are dozens of this questions around and I think I've read all of them, but couldn't find my problem. I've created a file named /etc/httpd/conf.d/django.conf and this is what I've written in it: <VirtualHost *:8000> Alias /media/ /var/www/html/igame/media/ Alias /static/ /var/www/html/igame/static/ <Directory /var/www/html/igame/static> Require all granted </Directory> <Directory /var/www/html/igame/media> Require all granted </Directory> WSGIScriptAlias / /var/www/html/igame/igame/wsgi.py <Directory /var/www/html/igame/igame> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess igame python-path=/lib/python3.6/site-packages WSGIProcessGroup igame </VirtualHost> And this is my static settings in settings.py: DEBUG = True STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') PROJECT_DIR = os.path.dirname(__file__) But when I run the project by python3.6 manage.py runserver 0.0.0.0:8000, the statics files does not load on my project. I use python 3.6 plus django 2.1and Apache 5.4. What am I missing here? -
How to display uploaded image name in django?
I only know to display image url in django through {{object.image.url}} but it displays url path and I want to show image name but have no idea about displaying its name only in django template. How can it be done? -
django parameter causing the wrong template and view to render
Overview / Problem: Hi! The wrong template and view are loading every time I click the check_tier_level link in my template. When that parameter is in, it loads the home view with "check_tier_level" as the special_message, even though my links go to the view for check_tier_level. If I click any of the form buttons to grant access, the proper message shows up in that spot. I just can't check the level. The app works fine and renders the right template / view only when I remove the special_message parameter from the urlpattern and view. The only other lead I have on this is that the url in the browser will also look like http://127.0.0.1:8000/tiered_access_app/Tier 1 granted!/, instead of having the characters escaped with %20 and so on. My goal The whole reason I want to keep that parameter in is so a special_message can notify users of the latest update based on their actions. If anyone knows a better way to do this without making a whole new view / template (which I know is a solution, and how to do it), I'd like to know how. Anyways, here's my code: urlpatterns.py path('', views.home, name='home'), path('<str:special_message>/', views.home, name='home_special_message'), path('check_tier_level/', views.check_tier_level, … -
How i can connect a ESP8266 with a django app ?
I am trying to send data from a temperature sensor using a ESP8266 to a Django web aplication, store the data in a database sqlite3 and view the data obtained in a template, but I don't Know how make the connection between django and the ESP8266, I already have the code in an arduino IDE to obtain the data and puts in the server of ESP8266. Whar are the steps that i can follow for make the project ? -
Deployment of a Django Multi Tenant app on digital-ocean
At this point I have my django tenant app running well locally. I am using django tenant schema library. I am going to deploy it on digital ocean but i have one question though. Will it be enough to specify my tanents in django app or do i have to create records for them by creating subdomains in digital ocean dns and my nginx server block? or just in nginx will do the trick? Please someone help me thank you so much. you guys are awesome. -
Django rest framework serializer with field from related table
I have the following models: class Workflow(models.Model): name = models.CharField(max_length=200) class Task(models.Model): name = models.CharField(max_length=200) class TaskParameter(models.Model): default_value = models.CharField(max_length=1000, null=True) name = models.CharField(max_length=200) task = models.ForeignKey(Task, related_name='parameters', on_delete=models.CASCADE, null=True) class WorkflowTask(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE) workflow = models.ForeignKey(Workflow, related_name='workflow_tasks', on_delete=models.CASCADE, null=True) class WorkflowTaskParameter(models.Model): value = models.CharField(max_length=1000) workflow_task = models.ForeignKey(WorkflowTask, on_delete=models.CASCADE, related_name='workflow_task_parameters', null=True) task_parameter = models.ForeignKey(TaskParameter, on_delete=models.CASCADE, related_name='+') So basically what i try to do is having workflows that contain tasks (Using the WorkflowTask association table), and those tasks have parameters (TaskParameter). Those parameters have a default value but i want to be able to override this default value with another one (that's what the WorkflowTaskParameter table is for). And here are my serializers : class TaskParameterSerializer(serializers.ModelSerializer): class Meta: model = TaskParameter fields = ('name', 'default_value') class WorkflowTaskParameterSerializer(serializers.ModelSerializer): name = serializers.StringRelatedField(many=False) # here i want the name from the associated TaskParameter class Meta: model = WorkflowTaskParameter fields = ('name', 'value') class WorkflowTaskSerializer(serializers.ModelSerializer): task = serializers.StringRelatedField(many=False) workflow_task_parameters = WorkflowTaskParameterSerializer(many=True, read_only=True) class Meta: model = WorkflowTask fields = ('task', 'workflow_task_parameters') class WorkflowSerializer(serializers.ModelSerializer): workflow_tasks = WorkflowTaskSerializer(many=True, read_only=True) class Meta: model = Workflow fields = ('name', 'workflow_tasks') I'm almost getting the result i want : { "name": "MyWorkflow", "workflow_tasks": [ { "task": "MyTask", "workflow_task_parameters": … -
django CreateView doesn't show on ListView until rerun the server
I am trying to create an object using CreateView class PlayerCreate(CreateView): template_name = 'form.html' model = Player form_class = PlayerForm header = "Player" def get_context_data(self): context = super(PlayerCreate, self).get_context_data() context['header'] = self.header return context def form_valid(self, form): valid = super(PlayerCreate, self).form_valid(form) if not self.request.user.is_staff or not self.request.user.is_superuser: return HttpResponse("Only authorized user can edit or create") return valid It works. However, when I jump into the ListView Part, I need to rerun python manage.py runserver to make the new item show on the list. I want to make it work without rerun the server. Thanks! Below is my ListView code class PlayerList(ListView): template_name = "list.html" header = 'Player' queryset = Player.objects.all().order_by("-timestamp") def get_context_data(self): context = super(PlayerList, self).get_context_data() context['header'] = self.header return context def get_queryset(self): query = self.request.GET.get("q") if query: self.queryset = self.queryset.filter( Q(name__icontains=query) ).distinct() return self.queryset else: return self.queryset -
Integrate machine learning model with Django
I've been working with some machine learning models created with python and I'd like to use them in a web app created in django. Sadly I haven't found any useful information about how to do it. Is there any way to do that? I only want to connect a simple abm to send data to those models. I'd very grateful if you could help me -
Requesting at least one of two fields in a Form
I've done a model which has the email and phone fields and I want to make only one of both obligatory. In other words, you only need to complete one of them in order to send the form. I've tried to do this: class ClientQueriesModel(models.Model): # [...] email = models.EmailField(max_length=100, null=True, blank=True) phone = models.CharField(max_length=100, null=True, blank=True) class ClientQueriesModelForm(forms.ModelForm): class Meta: model = ClientQueriesModel fields = ['name', 'email', 'phone', 'subject', 'message'] def clean(self): cleaned_data = super(ClientQueriesModelForm, self).clean() cc_myself = cleaned_data.get("email") subject = cleaned_data.get("phone") if not cc_myself and not subject: raise forms.ValidationError("At least one of both field must be completed: email or phone number.") But it doesn't work. The form isn't sent, but the user doesn't see any error message, the page just refreshes (without sending it but cleaning the name field). How can I make from two fields one obligatory? Note that I'm using a custom Form template, so if I must perform any edit in my HTML template (which, I haven't found on the internet), please tell me. P.S: I'm using Django 1.11. -
PIL module ImportError on Apache2 Server
I am getting this traceback on my Apache2 server when trying to upload an image. I am using Python 3.5.2 and Pillow 5.0.0 and Django 2.1.1 I was able to upload images successfully when I am working on my localhost, but when I uploaded this code to the apache2 server, then it gives this traceback. Pillow is in the requiremnts.txt though. No where in the code do I explicitly try to import PIL, but it seems to be getting called. I have tried installing Pillow and PIL. I have tried to uninstall PIL, uninstall Pillow, I have tried re-install both. Nothing seems to be working. View.py from django.http import JsonResponse, HttpResponse from django.shortcuts import render from django.core import serializers from manager.models import Manager, Inspection from . import InspectorService from . import InspectionService import json from .forms import InspectionImageForm ... more unrelevant code here ... def upload_image(request): if request.method == 'POST': form = InspectionImageForm(request.POST, request.FILES) inspection_id = request.POST.get('inspection_id') if form.is_valid(): m = Inspection.objects.get(id = inspection_id) m.image = form.cleaned_data['image'] m.save() return JsonResponse({'error': False, 'message': 'Uploaded Successfully', 'location': m.image.name}) else: return JsonResponse({'error': True, 'errors': form.errors}) else: return JsonResponse({'error': True, 'errors': 'Post error'}) forms.py from django import forms class InspectionImageForm(forms.Form): image = forms.ImageField() inspection_id … -
Pyenv command not found when trying to execute gunicorn
I'm starting to implement a webapp in Django with nginx, gunicorn ,mysql and supervisor and using pyenv with an virtualenv. I've been following a tutorial to configure the gunicorn, I have a code like this for my shell script: NAME="myapp" # Name of the application DJANGODIR=/home/myapp/myapp # Django project directory SOCKFILE=/home/myapp/run/gunicorn.sock # we will communicate using this unix socket USER=myappuser # The user to run as GROUP=webdata # The group to run as NUM_WORKERS=3 # How many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=myapp.settings_production # Which settings file should Django use DJANGO_WSGI_MODULE=myapp.wsgi # WSGI module name echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR pyenv activate env export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start your Django Unicorn exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user $USER \ --bind=unix:$SOCKFILE The problem is that the supervisor log output always says: pyenv command not found and exec: gunicorn: not found, I guess that is because somehow the pyenv instruction is not available for the shell script but I have no clue about how can I fix it, Anyone can help …