Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to mock decorator in django unit test?
I am trying to write simple unit test for my view. I have a decorator which authenticate by sending http request. How to mock decorator of my view and run unit test? my views.py @method_decorator(authentication_decorator, name='post') class AddBlogView(CreateAPIView): serializer_class = BlogSerializer -
How does Django query the tree structure
I am new to Django and I am creating a blog and comment function from django.db import models from django.contrib.auth import get_user_model class Blog(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) title = models.CharField(max_length=200) content = models.TextField(max_length=200) class Comment(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) blog = models.ForeignKey(Blog, on_delete=models.CASCADE) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name="children") content = models.CharField(max_length=200) This is my current test data Comment.objects.all().values() <QuerySet [ {'id': 1, 'user_id': 1, 'blog_id': 1, 'parent_id': None, 'content': '1'}, {'id': 2, 'user_id': 1, 'blog_id': 1, 'parent_id': None, 'content': '2'}, {'id': 3, 'user_id': 1, 'blog_id': 1, 'parent_id': 1, 'content': '1-1'}, {'id': 4, 'user_id': 1, 'blog_id': 1, 'parent_id': 1, 'content': '1-2'} ]> But now I want to find out such a tree structure, what should I do? [ {'id': 1, 'user_id': 1, 'blog_id': 1, 'parent_id': None, 'content': '1', 'children': [ {'id': 3, 'user_id': 1, 'blog_id': 1, 'parent_id': 1, 'content': '1-1'}, {'id': 4, 'user_id': 1, 'blog_id': 1, 'parent_id': 1, 'content': '1-2'} ]}, {'id': 2, 'user_id': 1, 'blog_id': 1, 'parent_id': None, 'content': '2', 'children': [] }, ] -
Is there a way to connect to a bluetooth device by a django web app (so with python)?
I a personal project I was able to connect via Bluetooth to a device that measure body temperature with some python libraries. I want to implement this code in a Django web app to collect data from these Bluetooth devices, is this possible? Can you suggest me, if is it possible, how can I get this work in Django? Thanks in advance, Marco -
How do I style the formset in Django?
I have a problem; I want to put the styles to my formset because it does not inherit them from the main form and the design looks horrible, I don't know how to fix it or if there is a type of widget to make the fields look better. Thank you so much Parte/forms.py from django import forms from django.forms import formset_factory from .models import Parte class ParteForm(forms.ModelForm): class Meta: model=Parte fields=['codigo','descripcion','quantity','unit_price','total_price','tax_free'] Presupuestos/forms.py class PresupuestosParteForm(forms.ModelForm): class Meta: model = Parte fields = '__all__' widgets = { 'codigo': forms.TextInput( attrs={ 'class': 'form-control' } ), 'quantity': forms.NumberInput( attrs={ 'class': 'form-control', } ), 'unit_price': forms.NumberInput( attrs={ 'class': 'form-control', 'onchange': 'multiplicar()', } ), 'total_price': forms.NumberInput( attrs={ 'class': 'form-control', } ), 'tax_free': forms.CheckboxInput( attrs={ 'class': 'form-check-input', 'onclick': 'taxes_free(multiplicar())', } ), 'descripcion': forms.TextInput( attrs={ 'class': 'form-control' } ), 'descuento': forms.NumberInput( attrs={ 'class': 'form-control', 'onchange': 'totales()', } ), 'total': forms.NumberInput( attrs={ 'class': 'form-control', } ), } ParteFormSet = formset_factory(ParteForm, extra=1) Presupuestos/views.py def create_Presupuestos(request): #Crear cada uno de los formularios y reunirlos presupuestosclientesform=PresupuestosClientesForm(request.POST or None) presupuestosvehiculosform=PresupuestosVehiculosForm(request.POST or None) presupuestosparteform=PresupuestosParteForm(request.POST or None) presupuestosmanoobraform=PresupuestosManoObraForm(request.POST or None) presupuestospagosform=PresupuestosPagosForm(request.POST or None) #Creación del formset de parteform if request.method == 'POST': formset = ParteFormSet(request.POST) if formset.is_valid(): # extract name from each form and … -
How to run a Function on a varying schedule in Python/Django? [duplicate]
I have a Django/Python project that I use for work, and one of the most important aspects of the website is that it tracks our equipment location. I am looking to set a custom schedule that will execute the function that gets the current location data. The schedule would look something like this. Monday Through Friday Update Every Hour between the hours of 5AM and 5PM. Update Every 3 Hours between the hours of 5PM and 5AM. Saturday and Sunday Update Every Hour between the hours of 6AM and 10AM. Update Every 4 Hours between the hours of 10AM to 6AM. In addition, if a user generates the locations manually, the counter then gets reset. For example, let's say on a Monday at 630AM, a user generates the locations manually, the next scheduled call gets moved to 730AM rather than 7AM. -
django AWS EB CLI Unable to deploy with mysqlclient
I have been attempting to deploy my Django project up on AWS ElasticBeanstalk via EB CLI n my local Pycharm project with the built in terminal. Having setup IAM/group (through aws web console) I migrated and ran server locally (Pycharm terminal) and all works fine, and then created env/instance and requirements.txt and deployed using EB CLI in Pycharm and this also worked fine. I setup a database connection on RDS (AWS web Console) then changed settings to connect to mysql, pip installed mysqlclient, migrate and ran locally (Pycharm terminal) and again all works fine. However, when I try to deply the project again with mysqlclient installed I get errors and I just cannot figure out why. Platform: arn:aws:elasticbeanstalk:us-west-2::platform/Python 3.7 running on 64bit Amazon Linux 2/3.3.7 Requirements.txt asgiref==3.4.1 awsebcli==3.20.2 boto3==1.20.3 botocore==1.23.3 cement==2.8.2 certifi==2021.10.8 charset-normalizer==2.0.7 colorama==0.4.3 Django==3.2.9 django-storages==1.12.3 future==0.16.0 idna==3.3 jmespath==0.10.0 mysqlclient==2.0.3 pathspec==0.5.9 pypiwin32==223 python-dateutil==2.8.2 pytz==2021.3 pywin32==302 PyYAML==5.4.1 requests==2.26.0 s3transfer==0.5.0 semantic-version==2.8.5 six==1.14.0 sqlparse==0.4.2 termcolor==1.1.0 typing-extensions==3.10.0.2 urllib3==1.26.7 wcwidth==0.1.9 .ebextensions/django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: awsdeploy.wsgi:application aws:elasticbeanstalk:environment:proxy:staticfiles: /static: static container_commands: 01_collectstatic: command: "source /var/app/venv/staging-LQM1lest/bin/activate && python manage.py collectstatic --noinput --clear" 02_migrate: command: "source /var/app/venv/staging-LQM1lest/bin/activate && python manage.py migrate --noinput" leader_only: true EB Error Logs Collecting mysqlclient==2.0.3 Using cached mysqlclient-2.0.3.tar.gz (88 kB) 2021/11/11 02:10:40.712344 [ERROR] An error … -
How to keep the sidebar elements active after reloading the page
I have a sidebar implemented in my base template. The other pages, let's say page1, page2 and page3 inherit the sidebar from the base template: {% extends 'base_generic.html' %} <=== This code is present in page1, page2 and page3 My sidebar contains a <li> with three links to page1, page2 and page3. When I visit my home page, let's say example.com/index.html and the sidebar is loaded, if I click on the sidebar page1 (for example) that will reload the page since I'm calling the view: def page1(request): return render(request, 'page1.html', context=None) But then how can I mark the page1 as 'active' in the sidebar? Every time I click on some page everything is reloading. I have implemented this, but it only works if the sidebar item I click does not reload the page and remains with index.html: $(document).ready(function() { // Get the container element var sidebarContainer = document.getElementById("sidebarLinks"); // Get all li's with class="sidebar-element" inside the container var lis = sidebarContainer.getElementsByClassName("sidebar-element"); // Loop through the li and add the active class to the current/clicked li for (var i = 0; i < lis.length; i++) { lis[i].addEventListener("click", function() { var current = document.getElementsByClassName("active"); // If there's no active class if (current.length … -
Django: is it good to have a model with more then 60 fields? And best way to develop project
I'm working on my first project in Django and I'd really like to have some advice from people with more experience then me since right now I'm a little stuck on what road take to keep developing my project. This is my plan to develop my project: Create a modelsFileFields so that my user can upload one or more standarded excel file Read it and create variables with pandas Create an html page with the graph with chart.js and render it in pdf with ReportLab Store the pdf in my user profile usinig primary key so that they can see it and download it again. My main problem right now is to store or not the information that are in the excel file in my database. Since getting the information in the excel file is what is important to me, my first thought was to import them and the only thing that it keeping me from doing so is the quantity of column that I have. This how my excel file looks like: total partial [...] user1 10 4 user2 18 6 I have more then 60 variable in my excel file (so I'd need a model with more then … -
django postgres :there is no unique constraint matching given keys for referenced table " "
I have 3 tables(models): event,event_type,patient both event_type and patient are foreign keys for event. event fields:id, event_type(foreign key),event_unit, event_value,event_time, patient(foreign key) event_type fields: id, type_name patient fields : patient_id ,patient_name I used Django to build the tables: class Event_type(models.Model): type_name = models.CharField(max_length=40,null=True,unique=True) class Meta: verbose_name = "event_type" verbose_name_plural = verbose_name def __str__(self): return self.type_name class Patient(models.Model): patient_id = models.AutoField(unique=True, primary_key=True) # patient identification patient_name = models.CharField(max_length=30, unique=True, verbose_name='patient_name') class Meta: verbose_name = 'Patient' verbose_name_plural = verbose_name ordering = ['-patient_id'] def __str__(self): return self.patient_name class Event(models.Model): event_id = models.AutoField(unique=True, primary_key=True) event_type = models.ForeignKey(Event_type, null=True, blank=True,on_delete=models.CASCADE, verbose_name='event type',default="",to_field='type_name' ) event_value = models.PositiveIntegerField(default=0, verbose_name='even value', blank=True) event_unit = models.CharField(max_length=100, blank=True, verbose_name='event unit') event_time = models.DateTimeField(auto_now=False, verbose_name='event time') patient = models.ForeignKey(verbose_name='patient', to='Patient', to_field='patient_id', on_delete=models.CASCADE,default="") class Meta: verbose_name = 'Event' verbose_name_plural = verbose_name ordering = ['-event_id'] def __str__(self): return self.event_type.type_name After: python manage.py migrate I received error: django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "patients_event_type" Any friends can help? -
How to make multiple object in one request put or delete? Django Rest
It allow me to pass in json format data to post for creating record after i make def create so that json format like [{data:data,data:data}] can post in. How should i do so that i can also make put request with multiple object in one request or using post method to update? Below is views.py. from django.shortcuts import render from .models import ListForm # Create your views here. from rest_framework import viewsets from .serializers import ListFormSerializer from rest_framework import filters import django_filters.rest_framework from rest_framework.response import Response from rest_framework import status, viewsets class ListFormViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = ListForm.objects.all().order_by('group') serializer_class = ListFormSerializer filter_backends = (django_filters.rest_framework.DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter,) filterset_fields = ['group','key_description'] search_fields = ['group'] def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, many=isinstance(request.data,list)) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) # return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) -
How to pass the values of a given table to a template based on the foreign key within that table that links to a value in another table?
I'm not sure the title is the most accurate way of stating my issue, and I'm very new to Django. I'm displaying speedrun entries. It's set up so users can enter their record information in a form, with a dropdown menu for the game, which is a foreign key to a GameName object. They enter their game on a separate page if it wasn't listed. I wanted people to be able to add their games because there are too many for me to list out in the short amount of time I have to do this. I have a page that displays all games entered into the dB so far. When a user clicks on the game name I would like to redirect to a page that lists all entries entered for that game title. This is where I am having trouble. I need to create a views function that can populate a html table with all relevant values from my object Record but based on the name of the game found in the GameName dB table. I can't come up with the right function to output all records/rows from the Record object that match a specific game_name/GameName pk. models.py … -
Django rename uploaded file: append specific string at the end
I'm restricting the upload button to allow only csv files. I need help please to append _hello at the end of each file uploaded by the user, but before the extension. (e.g. user_file_name.csv becomes automatically user_file_name_hello.csv) Optional: I'd like the original file to be first renamed automatically, then saved to my uploads directory. models.py from django.db import models # validation method to check if file is csv from django.core.exceptions import ValidationError def validate_file_extension(value): if not value.name.endswith('.csv'): raise ValidationError(u'Only CSV files allowed.') # Create your models here. class user_file(models.Model): user_file_csv = models.FileField(upload_to='documents/user_files/', validators=[validate_file_extension]) forms.py from django import forms from .models import user_file from django.forms import FileInput class user_file_form(forms.ModelForm): class Meta: model = user_file widgets = {'user_file_csv': FileInput(attrs={'accept': 'text/csv'})} fields = ('user_file_csv',) Thank you! -
django,postgres error:column " " of relation " " does not exist
I have 3 tables: event,event_type,patient both event_type and patient are foreign keys for event table. event fields:id, event_type(foreign key),event_unit, event_value,event_time, patient(foreign key) event_type fields: id, type_name patient fields : patient_id ,patient_name I used Django to build the tables: class Event_type(models.Model): type_name = models.CharField(max_length=40,null=True,unique=True) class Patient(models.Model): patient_id = models.AutoField(unique=True, primary_key=True) # patient identification patient_name = models.CharField(max_length=30, unique=True, verbose_name='patient_name') class Event(models.Model): event_id = models.AutoField(unique=True, primary_key=True) event_type = models.ForeignKey(Event_type, null=True, blank=True,on_delete=models.CASCADE, verbose_name='event type',default="",to_field='type_name' ) event_value = models.PositiveIntegerField(default=0, verbose_name='even value', blank=True) event_unit = models.CharField(max_length=100, blank=True, verbose_name='event unit') event_time = models.DateTimeField(auto_now=False, verbose_name='event time') patient = models.ForeignKey(verbose_name='patient', to='Patient', to_field='patient_id', on_delete=models.CASCADE,default="") and I have a csv file events.csv: import csv with open(r'/Users/williaml/Downloads/events.csv') as csvfile: spamreader = csv.reader(csvfile, delimiter=',' ,quotechar=' ') for row in spamreader: print(row) the output is: ['"PATIENT ID', 'PATIENT NAME', 'EVENT TYPE', 'EVENT VALUE', 'EVENT UNIT', 'EVENT TIME"'] ['"1', 'Jane', 'HR', '82', 'beats/minute', '2021-07-07T02:27:00Z"'] ['"1', 'Jane', 'RR', '5', 'breaths/minute', '2021-07-07T02:27:00Z"'] ['"2', 'John', 'HR', '83', 'beats/minute', '2021-07-07T02:27:00Z"'] ['"2', 'John', 'RR', '14', 'breaths/minute', '2021-07-07T02:27:00Z"'] ['"1', 'Jane', 'HR', '88', 'beats/minute', '2021-07-07T02:28:00Z"'] ['"1', 'Jane', 'RR', '20', 'breaths/minute', '2021-07-07T02:28:00Z"'] ['"2', 'John', 'HR', '115', 'beats/minute', '2021-07-07T02:28:00Z"'] ['"2', 'John', 'RR', '5', 'breaths/minute', '2021-07-07T02:28:00Z"'] Now I want to insert these rows into database: import psycopg2 conn = psycopg2.connect(host='localhost', dbname='patientdb',user='username',password='password',port='') cur = conn.cursor() import … -
name 'user' is not defined
I'm trying to make a custom registration page without using usercreationform i've made the model and imported it but when i run it I keep encountering this error NameError at /register name 'user' is not defined the line in particular is: if user.password != user.repassword: and i tried changing the method to GET instead of POST and i got a different error MultiValueDictKeyError 'fname' views.py from django.shortcuts import render,redirect from .models import User from django.contrib import messages def home(request): return render(request, 'home.html') def register(request): global user if request.method == 'POST': user = User() user.fname = request.POST['fname'] user.lname = request.POST['lname'] user.email = request.POST['email'] user.password = request.POST['password'] user.repassword = request.POST['repassword'] if user.password != user.repassword: return redirect("register") elif user.fname == "" or user.password == "" : messages.info(request,f"some fields are empty") return redirect("register") else: user.save() return render(request, 'register.html') models.py from django.db import models class User(models.Model): id=models.AutoField(primary_key=True) fname=models.CharField(max_length=100) lname=models.CharField(max_length=100) email=models.CharField(max_length=50) password=models.CharField(max_length=100) repassword=models.CharField(max_length=100) html page {%extends 'base.html'%} {%load static%} {%block content%} <link rel="stylesheet" href="{%static 'css/style.css'%}"> <form method="post"> {%csrf_token%} <label for="fname">First Name</label> <input type="text" name="fname" placeholder="Enter your First Name"><br> <label for="lname">Last Name</label> <input type="text" name="lname" placeholder="Enter your Last Name"><br> <label for="email">Email</label> <input type="email" name="email" placeholder="Enter your Email"><br> <label for="password">Password</label> <input type="password" name="password" placeholder="Enter a password"><br> <label for="repassword">Re … -
Method Not Allowed (POST): /property/like/
My form submit keeps throwing this error Method Not Allowed (POST): /property/like/ <form action="{% url 'property:like-post' %}" method="POST"> {% csrf_token %} <input type="hidden" name="property_id" value="{{obj.id}}"> {% if request.user not in obj.liked.all %} <button class="btn love-badge btn-raised btn-wave btn-icon btn-rounded mb-2 white" type="submit"> <i class="mdi mdi-heart-outline"></i></button> {% else %} <button class="btn love-badge btn-raised btn-wave btn-icon btn-rounded mb-2 teal" type="submit"> <i class="mdi mdi-heart-outline"></i></button> {% endif %} </form> view.py def like_property(request): user = request.user if request.method == 'POST': property_id = request.POST.get('property_id') property_obj = Property.objects.get(id=property_id) if user in property_obj.liked.all(): property_obj.liked.remove(user) else: property_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, property_id=property_id) if not created: if like.value == 'Like': like.value == 'Unlike' else: like.value = 'Like' like.save() return redirect('property:list') urls.py app_name = 'property' urlpatterns = [ path('like/', views.like_property, name='like-post'), ] Any insight on anything I'm doing wrong would be appreciated. -
Django SetPasswordForm doesn't render anything
Django's SetPasswordForm doesn't render anything, please help. This is what I got: views.py from django.contrib.auth.forms import SetPasswordForm @login_required def profile_security(request): template = "profiles/profile_security.html" form = SetPasswordForm print("form.base_fields: %s" % form.base_fields) context = {"profile_index_active": "active", "underline_security": "text-underline", "form": form} return render(request, template, context) html <form method="post">{% csrf_token %} {{ form.as_p }} </form> tried this html as well <form method="post">{% csrf_token %} <div class="form-group field-password1"> {{ form.new_password1.errors }} <label for="id_new_password1">New Password</label> {{ form.new_password1 }} </div> <div class="form-group field-password2"> {{ form.new_password2.errors }} <label for="id_new_password2">Repeat New Password</label> {{ form.new_password2 }} </div> <div class="form-group"> <input class="btn btn-success text-uppercase w-100" type="submit" value="Guardar nueva contraseña"> </div> </form> It does print the fields correctly: form.base_fields: {'new_password1': <django.forms.fields.CharField object at 0x7f49174e2790>, 'new_password2': <django.forms.fields.CharField object at 0x7f49174e2940>} but it doesn't render anything. What am I doing wrong? -
How to implement SSO across multiple sites
We have a couple of websites for which we are looking to implement Single Sign on. These are both Django / Wagtail websites. They both currently are using the standard Django login for authentication. We want to make it so that if a user logs into one of the websites they are automatically logged into the other and the same for logging out. I've done a google search and OpenID Connect seems to come up a lot of times but it seems to have quite a steep learning curve and I suspect a lot of it isn't relevant to my specific situation and I don't want to get lost down a long maze of technical details. It seems like I need to run my own OpenID Connect server which I have not done before. I've even tried looking on Docker Hub for a dockerised solution but I didn't find any of them with adequate documentation. Ideally I would like a solution where I could just add in a new Django authentication backend and perhaps just configure the host and port of the identity server in some settings file. Additionally I need to migrate the user database to the identity server … -
Create Django Form from ForeignKey
I'm trying to create a simple Django app that allows users to create and edit Recipes which consist of Ingredients. models.py class Recipe(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=1000) class Ingredient(models.Model): api_id = models.IntegerField(primary_key=True) # id in Spoonacular database name = models.CharField(max_length=100) # human-readable name units = models.CharField(max_length=10) # unit of measure (e.g. 'oz', 'lb'), includes '' for 'number of' amt = models.PositiveIntegerField() # number of units recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) I have a detail view that displays the Ingredients for a given Recipe, along with buttons to add and remove ingredients. The primary key of the recipe is in the URL. view of detail page with add/remove ingredient buttons I'm trying to get it so that when a user clicks on the 'Remove Ingredients' button, it redirects them to a form where they can select which Ingredients from the given Recipe they want to remove. This is the part I can't get to work. As best I can tell, this requires a ModelChoiceField with a queryset where the ForeignKey of the Ingredient matches the primary key of the Recipe ('recipe_pk'). It seems like I need to pass the primary key of the given Recipe into the Form via **kwargs … -
Django ask for fill a form not required
I've a strange bug with my forms. In a page I must hande 2 separate forms, the 1st one have no problem at all and I can add the record in DB , the 2nd one raise me an error asking to fill a required data of 1st form. The POST dictionary looks ok Here the log: <QueryDict: {'csrfmiddlewaretoken': ['lvt5Ph2SA1xxFK4LMotdHOWk2JuZzYDo0OKWc77rKICYKYmemy3gl0dBphnRNcFb'], 'pk_atto': ['1.1'], 'pk_persona': ['1'], 'capacita': ['11'], 'Aggiungi_persona': ['persona'], 'tipo': ['fondo']}> <ul class="errorlist"><li>pk_particella<ul class="errorlist"><li>This field is required.</li></ul></li></ul> the views: if request.method == 'POST': if("Aggiungi_particella" in request.POST): save_atto = AttiPartenzeParticelleForm(request.POST) else: save_atto = AttiPartenzePersoneForm(request.POST) print(request.POST) print(save_atto.errors) if save_atto.is_valid(): save_atto.save() return redirect('/aggiungi_atto_partenza' + '/' + str(save_atto['pk_atto'].value())) the forms: class AttiPartenzeParticelleForm(ModelForm): pk_atto = forms.ModelChoiceField(queryset=Atti.objects.all(), widget=forms.Select (attrs={'class': 'form-control'})) pk_particella = forms.ModelChoiceField(queryset=Particelle.objects.all(), widget=forms.Select (attrs={'class': 'form-control'})) capacita = forms.CharField(max_length=30, widget=forms.NumberInput (attrs={'class': 'form-control'})) tipo = forms.CharField(max_length=30, initial="fondo", widget=forms.TextInput (attrs={'class': 'form-control'})) class Meta: model = Acquisizioni_Cessioni_particella fields = '__all__' class AttiPartenzePersoneForm(ModelForm): pk_atto = forms.ModelChoiceField(queryset=Atti.objects.all(), widget=forms.Select (attrs={'class': 'form-control'})) pk_persona = forms.ModelChoiceField(queryset=Persone.objects.all(), widget=forms.Select (attrs={'class': 'form-control'})) capacita = forms.CharField(max_length=30, widget=forms.NumberInput (attrs={'class': 'form-control'})) tipo = forms.CharField(max_length=30, initial="fondo", widget=forms.TextInput (attrs={'class': 'form-control'})) class Meta: model = Acquisizioni_Cessioni_particella fields = '__all__' and the HTML <div id="particella" class="content-section d-flex justify-content-center mt-5"> <form action="" method="POST" id="particella_f"> {% csrf_token %} <fieldset class="form-group"> <div style="visibility:hidden"> {{ form.pk_atto|as_crispy_field }} </div> <div … -
Fetch human-readable value of a Django Form field
I have the below code in my forms.py: class MultiFilterForm(forms.Form): review_choice =(('gte', 'Reviews >=',), ('exact', 'Reviews =',), ('lte', 'Reviews <=',)) reviewsign = forms.ChoiceField(choices = review_choice, required = False, widget = forms.Select(attrs={'id': 'reviewSign','class': 'form-control',})) What I need to do, is in my template, display the 2nd value in each tuple. I can write {{form.review.value}} and that'll access the 1st value in each tuple like gte or exact or lte, but how can I access the human readable form in the 2nd position in each tuple? To clarify, I've already read up on the get_FOO_display() for model fields. But again, this is for a form field to be displayed in the template, not the model field. Any pointers, please let me know! I'm at my wits end. Thanks -
Using DRF FlexFields on Extra Actions
I want to use flexfields on viewset extra action serializers.py class FarmSerializer(FlexFieldsModelSerializer): class Meta: model = Farm fields = [ 'id', ... 'varieties', 'conditions', 'created_at', 'updated_at', 'created_by' ] expandable_fields = { 'varieties': ('labels.serializers.VarietySerializer', {'many': True}), 'conditions': ('labels.serializers.ConditionSerializer', {'many': True}), } views.py class GrowerViewSet(BaseViewSet): ... serializer_class = GrowerSerializer @action(detail=True, methods=['GET']) def farms(self, request, pk=None): ... serializer = FarmSerializer(queryset, many=True) return Response(serializer.data) Then, when I request http://localhost:5000/api/labels/grower/3/farms/?expand=varieties,conditions flexfield expand params dont work: -
Django how do you loop using range through two lists simultaneiously
I'm working with Django and would like to iterate through two lists so that the're side by side: my views file: def displayDict(request): data = ["a", "b", "c"] data2 = ["x", "y", "z"] return render(request, 'chattr.html', {'range': range(0,len(data)-1),'dictItems': data, "otherDict" : "other_bot", "dictItems_bot": data2, "otherDict2": "bot" , "duo" : (data, data2)}) my template: {% for i in range %} <p> {{i}} <br> <b>{{otherDict}}:</b> {{dictItems.i}} <br> <b>{{otherDict2}}:</b> {{dictItems_bot.i}} <br> {% comment %} {{a|add:1}} {% endcomment %} </p> {% endfor %} I'd like a webpage that looks like: other_bot: 'a' dictItems_bot: 'x' other_bot: 'b' dictItems_bot: 'y' other_bot: 'c' dictItems_bot: 'z' Currently nothing renders except the bot names: other_bot: dictItems_bot: other_bot: dictItems_bot: I may also be able to do this inner loop using tuples, Django Template: looping through two lists. But this would be a lot more complex,... -
How can I define and refer to custom user groups in Django that I can sort against like user.is_superuser?
I’ver created some custom user groups in my Django app because I want to show them different admin fieldsets. I thought they would work similarly to user.is_superuser. But they don’t. I have this def in my ModelAdmin: def is_approver(user): return user.groups.filter(name='approver').exists() (I don’t know what that’s called, by the way. Do you just call it a “def”?) So this works: def get_fieldsets(self, request, obj=None): if request.user.is_superuser: return self.superuser_fieldset I get the expected fieldset. But this doesn’t work: def get_fieldsets(self, request, obj=None): if request.user.is_approver: return self.approver_fieldset However, this does work: def get_fieldsets(self, request, obj=None): if request.user.groups.filter(name='approvers').exists(): return self.approvers_fieldset So, I guess my basic question is: why don’t my defs work like I expect? (Python 3.9.7, Django 3.1) -
In Django, how do I define a string value for IntegerChoices enum?
I'm using Django 3.2 and Pythnon 3.9. In my model, I define an int enum. I woudl also like to define readable string values for it, so I tried class Transaction(models.Model): class TransactionTypes(models.IntegerChoices): BUY = 0 SELL = 1 labels = { BUY: 'Buy', SELL: 'Sell' } translation = {v: k for k, v in labels.items()} but this definition fails with the error TypeError: int() argument must be a string, a bytes-like object or a number, not 'dict' How would I define strings for each value? I don't mind if hte strings are just the literal variable names (e.g. "BUY", "SELL") -
Django bulk update db table using model from html table
MODEL class BGD(models.Model): #need to update name # id=models.IntegerField(primary_key=True) Workgroup = models.CharField(max_length=50) Center = models.CharField(max_length=50, blank=True, null=True) Description = models.CharField(max_length=250) InsertDate = models.DateTimeField(default=datetime.now, blank=False) Is_Active = models.CharField(max_length=25, blank=True, null=True) # def __str__(self): # return "%s" % (self.id) class Meta: managed = False db_table="table" View def Control_Bidding_Groups (request): B_G_Results=BGM.objects.all() if request.method == 'POST': data = request.POST.dict() data.pop('csrfmiddlewaretoken', None) print('//////',data) for i in data.B_G_Results(): print('???',i) obj = Bidding_Group_Description.objects.get(id=i[0].split("_")[1]) print('55',obj) # Bidding_Group_Description.objects.filter(id=id).update(Is_Active) if not str(obj.Is_Active) == str(i[1]): #here check int or char datatype since 1 not equal "1" obj.Is_Active = i[1] print(obj.Is_Active) obj.save() return render(request, "Control_Bidding_Groups.html", { "B_G_Results": B_G_Results}) else: return render(request, "Control_Bidding_Groups.html", { "B_G_Results": B_G_Results}) #, "edit": edit HTML <section id="golf"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="mainbg padding-all-zero"> <div class="row panelBg"> <label class="parav" for="ddlSubmit"> <button class="btn btn-danger" value="Insert Records"> <span class="glyphicon glyphicon-upload" style="margin-right:5px;"></span>Submit</button> </label> <table class="table table-striped" width="100%"> <thead> <tr> <th>Workgroup</th> <th>Center</th> <th>Bidding Group Description</th> <th style="text-align:left;">Is Active</th> <th>Is Active</th> </tr> </thead> <tbody class="ui-sortable"> {% for d in B_G_Results%} <tr> <td>{{d.Workgroup}}</td> <td>{{d.Center}}</td> <td>{{d.Description}}</td> <td>{{d.Is_Active}}</td> <td><input type="text" value="{{d.Is_Active}}" name="d_{{d.id}}"> </td> </tr> {% endfor %} </tbody> </table> </div> </div> </form> </section> ERROR 'dict' object has no attribute 'B_G_Results' data {'17': '17', '18': '18', '19': '19', '74': '74', '75': '75', '76': '76', '77': …