Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change Cell Color Conditional Formating Django HTML
I have a table in my HTML view that I want the cell background to change when a certain value is within the cell. Here is a screenshot of my table in HTML. The values are populated with a simple for loop within my Django views. Attached you will see the css and HTML. On the top of the table, you will see the legend. For example if the value in any td tag == 6 , make cell background rgb(1, 109, 167). That's what I'm trying to accomplish. Thanks <div class="table-responsive"> <table class="table" id="scores"> <thead> <tr> <td rowspan="3"></td> <th colspan="3" scope="colgroup">Reasoning</th> <th colspan="3" scope="colgroup">Executive Functions</th> <th colspan="2" scope="colgroup">Speed</th> <th colspan="2" scope="colgroup">Memory</th> </tr> <tr> <th scope="col">Verbal</th> <th scope="col">Spatial</th> <th scope="col">Abstract</th> <th scope="col">Flexible</th> <th scope="col">Working Memory</th> <th scope="col">Attention</th> <th scope="col">Processing</th> <th scope="col">Visual Motor</th> <th scope="col">Verbal</th> <th scope="col">Visual </th> </tr> </thead> {% for i in scores %} <tbody> <tr> <td>{{i.test_date}}</td> <td>{{i.reasoning_verbal }}</td> <td>{{i.reasoning_spatial}}</td> <td>{{i.reasoning_abstract}}</td> <td>{{i.executive_flexibility}}</td> <td>{{i.executive_working_memory}}</td> <td>{{i.executive_attention}}</td> <td>{{i.speed_processing}}</td> <td>{{i.speed_visual_motor}}</td> <td>{{i.memory_verbal}}</td> <td>{{i.memory_visual}}</td> </tr> </tbody> {% endfor %} </table> #d6 { background-color: rgb(1, 109, 167); color: black; } #d5 { background-color: rgb(1, 167, 164); color: black; } #d4 { background-color: rgb(154, 191, 80); color: black; } #d3 { background-color: rgb(228, 190, 36); color: black; … -
How to logged a user in just after Sign up with class based views?
I am working on a site which deals in selling images,i am tryting to find out a way so that user can login after signup using class based views, I have already done it with function based views, but i want to do it class based, because its requires less code. Below is with function based views: My models.py: from django.db import models from django.contrib.auth.models import User class JobType(models.Model): job_name = models.CharField(max_length=50) def __str__(self): return self.job_name class Country(models.Model): country_name = models.CharField(max_length=50) def __str__(self): return self.country_name class IndianState(models.Model): state_name = models.CharField(max_length=30) def __str__(self): return self.state_name class SignUpModel(User): company_name = models.CharField(max_length=80) job = models.ForeignKey(JobType, on_delete=models.CASCADE) mobile_no = models.PositiveIntegerField() country = models.ForeignKey( Country, on_delete=models.CASCADE, blank=True) state = models.ForeignKey(IndianState, on_delete=models.CASCADE) forms.py from django import forms from django.contrib.auth.forms import AuthenticationForm, UsernameField from django.utils.translation import gettext, gettext_lazy as _ from django.core import validators from .models import JobType, SignUpModel class MyAuthenticationForm(AuthenticationForm): username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True})) password = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput(attrs={'autocomplete': 'current-password'}), ) error_messages = { 'invalid_login': _( "Please enter a correct %(username)s and password." ), 'inactive': _("This account is inactive."), } class LoginForm(MyAuthenticationForm): username = UsernameField(widget=forms.TextInput( attrs={"autofocus": True, "class": 'form-control', 'placeholder': 'Enter Username'}), error_messages={'required': 'Enter Username'}) password = forms.CharField( strip=False, widget=forms.PasswordInput( attrs={'placeholder': "Enter Password", 'class': 'form-control', … -
How to GET multipule ModelSrializer in one APIVIEW using Django Rest Framework
I have UserModel each user has multiple package and each package have price and program. model.py: class User(models.Model): name= models.CharField(max_length=100) class Package(models.Model): package_name = models.CharField(max_length=100) user= models.ForeignKey(User, on_delete=models.CASCADE,related_name='user_package') class Program(models.Model): title = models.CharField(max_length=100) user_package = models.ForeignKey(Package, on_delete=models.CASCADE) class Price(models.Model): price = models.FloatField() user_package = models.ForeignKey(Package, on_delete=models.CASCADE) serializer look like: class UserSerializer(NestedCreateMixin, NestedUpdateMixin,serializers.ModelSerializer): program = ProgramSerializer(source='user_program', many=True, read_only=True) package = PackageSerializer(source='user_package', many=True, read_only=True) price = PriceSerializer(source='price', many=True, read_only=True) class Meta: model = User fields= ("__all__") views.py: class user_apiView(APIView): def get(self, request): user= user.objects.all() serializer = UserSerializer(user, many = True) return Response(serializer.data) and that what I get: { "id": 1, "package": [ { "id": 1, "package_name": "wfe", "user": 1 }, { "id": 2, "package_name": "wfe", "user": 1 } ] } how can GET this RESULT? { "id": 1, "package": [ { "id": 1, "package_name": "wfe", "user": 1 }, { "id": 2, "package_name": "wfe", "user": 1 } ], "price": [ { "id": 1, "price": "wfe", "package": 1 }, { "id": 2, "price": "wfe", "package": 2 } ] "program": [ { "id": 1, "title": "wfe", "package": 1 }, { "id": 2, "title": "wfe", "package": 2 } ] } -
parse id in url Django
I want to be able to parse an id in my url and then get information from that url. If i don't parse a url, i would like to see all information my urls.py from django.urls import path from . import views from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ path('', views.home, name="home"), path('title', views.titles, name="titles"), path('json/<article_id>', views.articleList.as_view(), name="json"), ] my views.py class articleList(APIView): def get(self, request, article_id): if article_id == None: articles = Information.objects.all() serializer = InformationSerializers(articles, many=True) return Response(serializer.data) else: articles = Information.objects.filter(id = article_id) serializer = InformationSerializers(articles, many=True) return Response(serializer.data) def post(self): pass If i don't put anything behind .../json/ i get an error that i should fill in an id. How do i solve this issue? -
Html Button wrapped with anchor tags redirecting to ancor tag URL instead of button Onlick property
I have an HTML code in my Django project. I used an anchor tag to wrap a button. The anchor tag has its own href and the button also has an onclick property that when pressed will lead to a different destination. see code below <article class="card-group-item"> <header class="card-header"><h4 class="title">Links </h4></header> <div class="filter-content"> <div class="list-group list-group-flush"> <a href={{ add_drug_disposal_url }} class="list-group-item">Drug Disposal form <button class="button" onclick={{ add_drug_disposal_upload_url }}> <i class="fa fa-upload"></i> </button> </a> <a href={{ add_chain_of_custody_url }} class="list-group-item">Chain of custody <button class="button" onclick={{ add_chain_of_custody_upload_url }}> <i class="fa fa-upload"></i> </button> </a> <a href={{ add_drug_disposal_url }} class="list-group-item">Incident and Temperature Excursion Report <button class="button" onclick={{ add_incident_report_upload_url }}> <i class="fa fa-upload"></i> </button> </a> </div> <!-- list-group .// --> </div> </article> <!-- card-group-item.// --> how can I make sure that the button onclick will trigger when the button is pressed and not that of the anchor tag? note that all URLs are being picked by the template from the view just fine -
AJAX modal not opening in Django template using query in url
I'm trying to create a modal to open a window with the following url: http://127.0.0.1:8003/dados/add_dados?filter=crew So in urls.py: path('add_dados', add_dados, name="add_dados"), Follow the code below: <h2>Modal Example</h2> <!-- Trigger/Open The Modal --> <button id="myBtn">+ Add</button> <!-- The Modal --> <div id="myModal" class="modal"> <!-- Modal content --> <div class="modal-content"> <span class="close">&times;</span> </div> </div> <script> document.getElementById('myBtn').onclick = function(){ $.ajax({ url:"{% url 'add_dados' %}?filter=sample_unit_trap", type:'GET', data_type: 'html', success: function(data){ $('#modal-content').html(data); $("#modal-content").modal('show'); } }); } </script> But the popup does not open. Any suggestion to make open the window with the page content add_dados?filter=sample_unit_trap -
How to make Django Wagtail API Private
I am trying to find a solution to make the Wagtail API v2 private, i.e being accessible only by having an API key, but I don't seem to be able to find solutions online. Does anyone have any idea how to do this? Thanks! -
How to create a code field in django form and save it as a json to the db
I am having a usecase where I want to have a code snippet field in django and use that code field value and save it as a json in the DB. class TestForm(forms.Form): rule_name = forms.CharField(max_length=200) rule_code = forms.CharField(max_length=200) the rule_code field should be able to accept code and when reading I should be able to parse as json. eg: rule_code = a+b while parsing it should be as json. eg: {"data":{"lval":"a", "rval": "b", "log":"+"}} any suggestion will be helpful. Thanks -
how to have a django form validator run on each object with ModelMultipleChoiceField rather than the queryset as a whole
I have a modelform which generates a series of checkboxes to add children to a parent part. I have created a validator that checks for cyclic relationships. I'm currently getting errors however because "proposed_child" is a queryset containing however many values the user has selected. How do I have this validator run on each object in that queryset? def __init__(self, qs, part, *args, **kwargs): super(AddPartToAssemblyForm, self).__init__(*args, **kwargs) self.part = part self.fields['children'] = forms.ModelMultipleChoiceField( queryset=qs, widget=forms.CheckboxSelectMultiple ) def clean_children(self): proposed_child = self.cleaned_data['children'] part = self.part validate_acyclic_relationship(part, proposed_child) class Meta: model = Part fields = ['children'] -
a problem with twilio outbound call in django
im trying to implement twilio in my django app to make outbound calls. but there is a probelm. in following code, the sample app get the phone number from a django form. https://github.com/TwilioDevEd/browser-calls-django/blob/main/browser_calls/static/js/browser-calls.js but what I wanna do is calling random phone numbers which is stored in my db. I have a django model in my app and there is a random selector function. How can I do that? all the example files is flask framework and I dont know how can I call random phone numbers in my db and record them. -
Django 4 with sqlite3 JSONField creating a "TEXT" column instead of "JSON"
I'm using Django 4 with SQLite3 database (although I will use mysql in production). I have a model such as this: class Video(models.Model): title = models.CharField(max_length=180) meta = models.JSONField(default=dict) I would expect that the column type of "meta" should be "JSON", but actually the migration creates it as a "TEXT" column and then encodes/decode the json data as a string. This is a problem because you lose JSON field capabilities (such as updating only certain keys, not updating the entire encoded string). From reading it appears that sqlite3 supports JSON field type, so how can I force Django to use it? -
How can i print form.errors in a template in django
I am a beginner in django.. How can i print form.errors in a template in django. I want to print each error below each field. I pass errors using below code from view using AJAX else: return JsonResponse({"error": form.errors}, status=400) -
error with docker container in bitbucket pipelines
I'm deploying my dockerized Django app using bitbucket pipelines but unfortunately, the pipeline already creates two containers but not the last one the error and my files are attached below. error ERROR: for db Cannot create container for service db: authorization denied by plugin pipelines: -v only supports $BITBUCKET_CLONE_DIR and its subdirectories Encountered errors while bringing up the project. docker-compose.yml version: "3.8" services: db: container_name: db image: "postgres" restart: always volumes: - postgres-data:/var/lib/postgresql/data/ app: container_name: app build: context: . restart: always volumes: - static-data:/vol/web depends_on: - db proxy: container_name: proxy build: context: ./proxy restart: always depends_on: - app ports: - 80:8000 volumes: - static-data:/vol/static volumes: postgres-data: static-data: bitbucket-pipelines.yml image: python:3.7.2 pipelines: default: - step: services: - docker caches: - docker - pip script: - pip install docker-compose - docker-compose -f docker-compose-deploy.yml up --build - pipe: atlassian/aws-code-deploy:0.2.5 variables: AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY COMMAND: 'upload' APPLICATION_NAME: $APPLICATION_NAME ZIP_FILE: 'application.zip' S3_BUCKET: $S3_BUCKET VERSION_LABEL: 'my-app-2.0.0' - pipe: atlassian/aws-code-deploy:0.2.5 variables: AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY COMMAND: 'deploy' APPLICATION_NAME: $APPLICATION_NAME DEPLOYMENT_GROUP: $DEPLOYMENT_GROUP WAIT: 'true' S3_BUCKET: $S3_BUCKET VERSION_LABEL: 'my-app-2.0.0' IGNORE_APPLICATION_STOP_FAILURES: 'true' FILE_EXISTS_BEHAVIOR: 'OVERWRITE' definitions: services: docker: memory: 3072 `` -
Pass variable to tables2?
In trying to follow the DRY principle for python, I am attempting to define some information about a column in tables2 with a variable. I can see that the variable is being passed to my init function, but I can't see it in the main body of my class. Is there a better way to do this? Below is a simplified version of the table that I am trying to use. class StuffTable(tables.Table): input(self.FontClass) # the variable is not showing up here columnAttributes = {"style": "font-size: 12px; max-width:120px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"} columnHeaderAttributes = {"class": f"mb3 { self.FontClass }"} columnFooterAttributes = {"style": "font-size: 12px; font-weight: bold; max-width:120px; overflow: hidden; text-overflow: ellipsis;"} Type = tables.Column(verbose_name="", attrs={"th": columnHeaderAttributes, "td": columnAttributes}) TypeDescription = tables.Column(verbose_name="Type", attrs={"th": columnHeaderAttributes, "td": columnAttributes}) Column3= tables.Column(attrs={"th": columnHeaderAttributes, "td": columnAttributes}) Column4= tables.Column(attrs={"th": columnHeaderAttributes, "td": columnAttributes}) def __init__(self, *args, **kwargs): temp_fontclass = kwargs.pop("FontClass") super(StuffTable, self).__init__(*args, **kwargs) self.FontClass = temp_fontclass input(self.FontClass) # this does show that the variable is being passed -
Hot Reload with django template and react?
Is hot reloading possible while mounting react components into our Django template? As part of improving our UX, we are adding react component to our page to bring dynamic content on every customer interaction. I have successfully set up the react inside our Django and placed bundle.js into a static path using Webpack. Now using Webpack watch we are able to load the latest changes on the page. In this setup, we can't bring hot reloading and source in the browser devtools console to debug and speed up our development. Note: The application is not a SPA also not a Restful design for now. -
How to set initial value for all students to present in College management system | django admin inline
I am building College management system in django including features such as quiz, lms and attendance and so on. I want to set All students default attendance status to Present in django admin inline. So teacher dont have to hammer the status checkbox for every student, every student should be present by default and teacher only have to uncheck the status for whom who are absent. I have googled a lot but having hard time figuring out the solution. This is what I want: My model: class Attendance(models.Model): course = models.ForeignKey(settings.COURSE_MODEL, on_delete=models.CASCADE) date = models.DateField(default=datetime.now) class AttendanceStatus(models.Model): attendance = models.ForeignKey(Attendance, on_delete=models.CASCADE) student = models.ForeignKey(settings.STUDENT_MODEL, on_delete=models.CASCADE) status = models.BooleanField() And here is the admin. class AttendanceStatusInline(admin.TabularInline): model = AttendanceStatus can_delete = False fields = [ 'student', 'status' ] autocomplete_fields = [ 'student' ] @admin.register(Attendance) class AttendanceAdmin(admin.ModelAdmin): list_display = [ 'course', 'date'] autocomplete_fields = ['course'] inlines = [ AttendanceStatusInline ] Thanks in advance. -
envrionment variables with dokcer-compose in bitbucket pipelines
I have a Django app that is dockerized and I want it to deploy it using bitbucket pipelines, but the error is I use env file in docker-compose.yml which I can't put in my repo, so how can I overcome it. docker-compose.yml version: "3.8" services: db: container_name: db image: "postgres" restart: always volumes: - postgres-data:/var/lib/postgresql/data/ env_file: - prod.env app: container_name: app build: context: . restart: always volumes: - static-data:/vol/web env_file: - prod.env depends_on: - db proxy: container_name: proxy build: context: ./proxy restart: always depends_on: - app ports: - 80:8000 volumes: - static-data:/vol/static volumes: postgres-data: static-data: settings.py EMAIL_HOST = os.environ.get('EMAIL_HOST') bitbucket-pipelines.yml image: python:3.7.2 pipelines: default: - step: services: - docker caches: - docker - pip script: - pip install docker-compose - docker-compose -f docker-compose-deploy.yml up --build - pipe: atlassian/aws-code-deploy:0.2.5 variables: AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY COMMAND: 'upload' APPLICATION_NAME: $APPLICATION_NAME ZIP_FILE: 'application.zip' S3_BUCKET: $S3_BUCKET VERSION_LABEL: 'my-app-2.0.0' - pipe: atlassian/aws-code-deploy:0.2.5 variables: AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY COMMAND: 'deploy' APPLICATION_NAME: $APPLICATION_NAME DEPLOYMENT_GROUP: $DEPLOYMENT_GROUP WAIT: 'true' S3_BUCKET: $S3_BUCKET VERSION_LABEL: 'my-app-2.0.0' IGNORE_APPLICATION_STOP_FAILURES: 'true' FILE_EXISTS_BEHAVIOR: 'OVERWRITE' definitions: services: docker: memory: 3072 -
Django structure vs Clean archirecture
We want to create a new project in python language(out project is in digital advertising), we choose the Django framework for developing it, BUT we have a problem for choosing architecture. Some of us want to use the Django default structure for file naming, project structure and etc, but another is like to use a clean architecture structure. We are very happy to know your opinion Django strcture advantage: simple, have a good document, Writing code is much less Clean Architecture advantage: top programmer use this, other python developers(flask/fatapi) comfortable with it -
How to start publish or use my django project that i made on Blogger or wordpress?
I Develop and design Django project , chat site for desktop and mobile app - its my first time! Q - ist possible to use it in blog-spot ? ot word-press ? the files i code it by python and HTML for front-end. -
Sort by nested Embedded Document List
obj = self.get_object() # Need to add sorting here submited_talents_page = paginator.paginate_queryset( obj.doc_list, request ) the list lloks like this: obj.doc_list = [{ "user": ObjectId("12123124"), "viewers": [], "application": ObjectId("34322") } ] application: "timestamp": "<timestamp>", "code": "DEF" } I need to sort the application.timestamp inside obj.doc_list. -
Set id inside filter on serializer automatically
I'm trying to get the total count from specific Model inside a Serialization. "results": [ { "event_id": 24, "unique_visitors": 1, "returned_visitors": 2 }, ] The two value that i retrive in unique_visitors and returned_visitors come from one other module. What i did in serializer.py: unique_visitors = EventCounter.objects.filter(is_unique=True).filter(event_id=24).count() returned_visitors = EventCounter.objects.filter(is_unique=False).filter(event_id=24).count() def get_unique_visitors(self, obj): return self.test1 def get_returned_visitors(self, obj): return self.test2 What i try to do is to have inside the filter(event_id=24) the id of current object automatically. Can you help me please? -
How to have a Save draft option for profile creating form in django
I have view.py and model.py files for user creation, but I want an option for users that he/she can either submit the form and create the profile or can just hit the Save draft button to come later and submit the form. What would be the best way to achieve the above-said thing. -
Django guardian add a group to a user in the admin panel
When I create a group in django guardian's admin integration, how can I add that group to a user's groups in the admin panel -
Nginx auth could not identify password
I'm trying to deploy a Django application to a local Ubuntu server. While following the nginx docs, I encountered an issue while trying to restart nginx after updating the conf file. This is the output from journalctl -xe -- The job identifier is 154. Mar 02 10:43:38 cmac-srv03 systemd[44001]: tracker-extract.service: Succeeded. -- Subject: Unit succeeded -- Defined-By: systemd -- Support: http://www.ubuntu.com/support -- -- The unit UNIT has successfully entered the 'dead' state. Mar 02 10:43:40 cmac-srv03 dbus-daemon[44023]: [session uid=1001 pid=44023] Activating service name='org.freedesktop.secrets' requested by '> Mar 02 10:43:40 cmac-srv03 gnome-keyring-daemon[44513]: couldn't access control socket: /run/user/1001/keyring/control: No such file or dire> Mar 02 10:43:40 cmac-srv03 gnome-keyring-d[44513]: couldn't access control socket: /run/user/1001/keyring/control: No such file or directory Mar 02 10:43:40 cmac-srv03 dbus-daemon[44023]: [session uid=1001 pid=44023] Successfully activated service 'org.freedesktop.secrets' Mar 02 10:43:52 cmac-srv03 pulseaudio[44008]: GetManagedObjects() failed: org.freedesktop.DBus.Error.NoReply: Did not receive a reply. Possi> Mar 02 10:43:58 cmac-srv03 tracker-store[44147]: OK Mar 02 10:43:58 cmac-srv03 systemd[44001]: tracker-store.service: Succeeded. -- Subject: Unit succeeded -- Defined-By: systemd -- Support: http://www.ubuntu.com/support -- -- The unit UNIT has successfully entered the 'dead' state. Mar 02 10:47:56 cmac-srv03 sudo[45528]: pam_unix(sudo:auth): conversation failed Mar 02 10:47:56 cmac-srv03 sudo[45528]: pam_unix(sudo:auth): auth could not identify password for [subhaac] This is my … -
How to check the users and if the user is correct then marked the ordered section tick in Django
I want to check the user and if the user is correct then marked the order other wise make it as False on Boolen Type, I have attached the SS of output and it's code def orderList(request): order_qs = User.objects.get(username=request.user.username) if request.method == "POST": status = request.POST.get("order") if (order_qs): Order.objects.update(ordered = status) else: Order.objects.update(ordered = False) order = Order.objects.get(user = request.user) context = { 'order' : order, } return render(request, 'user_accounts/order_item.html',context)