Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Show other contents besides a form in FormView?
I really dislike django CBS design which makes things without flexibility. I would like to have a page whose upper part showing the content of objects and lower part has a form to be posted. CBS formview class EditStudent(FormView): template_name = "editstudent.html" model = models.Student success_url = "/home" How can I retriev objects of studens and show them on the template. Thanks. -
i have a django data of time, i can't add it as time input field value
I have a django model with a field of time. also I created a custom form with an input field so user can edit. If I parse this time as text input valur it show, but if it is time input and given the value time in it, the value is not shown how to solve this? -
"from captcha.fields import RecatchaFields" Is not recognized by Pylance
making a Django project and wanted to use Google's Recaptcha API in order to fight off bots. I've followed several installation KBs, watched tutorials, and I'm using these two as my installation guide: https://pypi.org/project/django-recaptcha/ https://django-simple-captcha.readthedocs.io/en/latest/usage.html Despite following their instructions, none of them seem to be importing correctly, Pylance doesn't recognize 'captcha' when importing in a form.py file. I'm even copying and pasting from their website just for this post's sake. from captcha.fields import CaptchaField These seem to be what I need in order to properly set up the API - I've even placed in the correct secret keys. The problem seems to be when I attempt to use it on a form/model .py file. Yes, I have installed in in installed apps - it's simple: INSTALLED_APPS = [ ... "captcha", ] I have even tried: INSTALLED_APPS = [ ... 'captcha', ] Not sure if load order has anything to do with the issue, and most tutorials seem to have the widget working right after this step. I have also made sure to set the urls.py files up according to the KB: urlpatterns += [ ..., path('captcha/', include('captcha.urls')), ..., ] I've uninstalled and reinstalled the plugin several times now, that isn't … -
Django: Multiple inputs with foreign key
I wanted to add more users for a shift. But it's a foreign key. How to do I make it? It does add, but if I choose more than one user, it shows this. Field 'id' expected a number but got ['1', '2'] Should I convert it to string? I don't know how to do it. Below is my code. models.py class User(models.Model): user_name = models.CharField(max_length=32, unique=True) pass_word = models.CharField(max_length=150,) email = models.EmailField(blank=True, unique=True) phone = models.CharField(max_length=32, unique=True) is_active = models.BooleanField(default=True,) class Attendance(models.Model): RosteringUserDate = models.ForeignKey(RosteringUserDate, on_delete=models.CASCADE, null=True) date = models.DateField() user = models.ForeignKey(User, on_delete=models.CASCADE) begin_time = models.TimeField(default="") end_time = models.TimeField(default="") work_time = models.CharField(max_length=64, default='') views.py def shift_add(request): queryset = User.objects.all() if request.method == 'GET': return render(request, 'attendance/shift_add.html', {'queryset': queryset}) if request.method == "POST": Attendance.objects.create( user_id = request.POST.getlist('user_name',[]), date = request.POST.get('date'), RosteringUserDate_id = request.POST.get('RosteringUserDate_id'), begin_time = request.POST.get('begin_time'), end_time = request.POST.get('end_time'), work_time = request.POST.get('work_time'), ) return redirect('/user/attendance/') forms.py <form method="post" action="/user/attendance_administrators/shift/add/"> <div class="form-group"> <input type="text" name="name" class="form-control" required> </div> <div class="form-group"> <input type="date" name="date" class="form-control" required> </div> <div class="form-group"> <input type="text" name="RosteringUserDate_id" class="form-control" required> </div> <div class="form-group"> <input type="time" name="begin_time" class="form-control" required> </div> <div class="form-group"> <input type="time" name="end_time" class="form-control" required> </div> <div class="form-group"> <input type="text" name="work_time" class="form-control" required> </div> <div class="form-group"> … -
Unit Testing Python Google Sheet
How would I unit test this part of my code?: creds = Credentials.from_service_account_info( json.loads(json.loads(creds_service_account)), scopes=scope ) class GoogleSheet: def __init__( self ): self.authenticate() def authenticate(self): scope = [ "https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive", ] # b64 decode, then utf decode, then jsonload. Super straightforward decoded = base64.b64decode(settings.PAYMENT_GOOGLE_SHEET_CREDS) creds_service_account = decoded.decode("utf8") creds = Credentials.from_service_account_info( json.loads(json.loads(creds_service_account)), scopes=scope ) client = gspread.authorize(creds) # self.sheet = client.open(GOOGLE_SHEET_TITLE).sheet1 self.sheet = client.open(GOOGLE_SHEET_TITLE).worksheet( GOOGLE_SHEET_WORKSHEET_NAME ) I tried this, but I might be off track here as it's not working, it still wants the proper json.loads(json.loads(creds_service_account)), scopes=scope: with patch('google.oauth2.service_account.Credentials.from_service_account_info', new=Mock(return_value=True)): -
'CourseTake' object has no attribute 'points'
class SimpleCourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ['title','credit_hours'] class CourseTakeSerializer(serializers.ModelSerializer): course = SimpleCourseSerializer() points = serializers.SerializerMethodField() grade_points = serializers.SerializerMethodField() class Meta: model = CourseTake fields = ['id','course', 'grade', 'points', 'grade_points'] def get_points(self, coursetake: CourseTake): if coursetake.grade >= 90: return '4' elif coursetake.grade >= 70: return '3' elif coursetake.grade >= 50: return '2' return '1' #TRY AND ERROR #Terminal: 'CourseTake' object has no attribute 'points' def get_grade_points(self, coursetake: CourseTake): return coursetake.course.credit_hours * coursetake.points I want to calculate grade points, which will be used later to calculate each student's GPA score. So the get_grade_point() will return the credit_hours * points. My problem is that the points field is not part of the model or serializer. I created a function to calculate the points for each course. Because I defined the points, Django keeps saying it's not an attribute anytime I try to access the point values. Is there a way to access the points value inside the get_grade_function? Image for better view -
Django annotate multiple aggregators over grouped values
Due to the structure of my project, I need to have multiple aggregations over three interlocked tables. With structure looking somewhat like this: class ItemMeta(models.Model): item = models.ForeignKey( Item, on_delete=models.SET_NULL, null=True ) class = models.CharField(max_length=2048, null=True, blank=True) department = models.CharField(max_length=2048, null=True, blank=True) class Item(models.Model): amount = models.DecimalField(max_digits=18, decimal_places=2) status = models.CharField(max_length=2048, null=True, blank=True, choices=ItemStatus.choices) class CartItem(models.Model): author = models.ForeignKey(to=UserModel, on_delete=model.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) class ItemStatus(models.TextChoices): UNDER_CONSIDERATION = 'UNDER_CONSIDERATION', 'Under consideration' IMPOSED = 'IMPOSED', 'Imposed' PAID = 'PAID', 'Paid' And I need to have item grouping by class, department and status both in cart and outside of it. I also need to have aggregations of prices of items in different statuses, as well as amount of different items in cart and existing. So the structure of the response has to always contain 5 values: sum of paid, imposed and considered items, and count of items existing and in cart of the calling user. I inherited from last poor sod this piece of code to do these: def _sum(self, status): return Coalesce(Sum('amount', filter=Q(status=status)), 0.0, output_field=FloatField()) def annotate_kwargs(self): return { 'under_consideration_amount': self._sum(ItemStatus.UNDER_CONSIDERATION), 'imposed_amount': self._sum(ItemStatus.IMPOSED), 'paid_amount': self._sum(ItemStatus.PAID), 'count': Count('pk', distinct=True), 'in_cart': Count('pk', distinct=True, filter=Q(cartitem__author=self.user)), } def get(self): return self.queryset \ .values(*self.group_by) \ .annotate(**self.annotate_kwargs()) … -
How to get rid of dict_keys() in my django template?
I am trying to print comma separated key values after drilling into a dictionary. But I am unable to get rid of dict_keys() that shows in my output. Here is my template: metrics.html <h1>Accessing values</h1> <p>{{ final_metrics.values }} </p> <p>{{final_metrics.data.0.13.browser.Chrome}}</p> <h1>{{ final_metrics.month }} Clicks Statistics</h1> <p>Short Url: {{final_metrics.short_url }}</p> <p>Date Accessed: {{ final_metrics.data.0.keys }}</p> <p>Browser: {{final_metrics.data.0.13.browser.keys}}</p> <p>Platform: {{final_metrics.data.0.13.platform.keys}}</p> and on the output screen it shows as follows Is there a way to get rid of the dict_keys() and have those values in a comma separated format? I have tried the solutions from https://stackoverflow.com/a/8000091 and https://stackoverflow.com/a/34542858 but does not seem to work for me. -
'bytes' object has no attribute '_committed' no da error en el save()
tengo un problema curioso. Estoy intentando editar un formulario con campos files,date,text,number pero al momento de actualizar me sale el siguiente error 'bytes' object has no attribute '_committed'y pensaba que era al principio lo files, pero cuando los quite de mi modelo forms me seguia el mismo error, les agradeceria una ayuda pues soy novato y no doy con la solucion. este es mi views: @login_required def editarCrudGestor(request,id): caso=Casos.objects.get(pk=id) if request.method == 'GET': forma_persona = EditarFormGestor(instance=caso) else: forma_persona = EditarFormGestor(request.POST,instance=caso) # files=request.FILES.getlist('formula_medica') if forma_persona.is_valid(): forma_persona.save() return redirect('busqueda') mi modelo forms: class EditarFormGestor(forms.ModelForm): def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['id_comple_info'].required=False self.fields['id_seguimiento'].required=False class Meta: model=Casos fields =['id_usuario','id_gest','estado','fecharesgistrocaso','fechaatenproceso','fechaatenfinalizado','fechaatenabierto','numeroradicado','descripcioncaso', 'enfermedad','fechaatencioneps','hora','id_comple_info','id_seguimiento','formula_medica','adjunto_seg','adjunto_terc' ,'id_barrera'] #'id_comple_info','id_seguimiento','formula_medica','adjunto_pri' labels={ # 'id_caso':'Caso', 'id_gest':'Gestor', 'estado':'Estado', 'hora':'Hora', 'fecharesgistrocaso':'Fecha registro', 'fechaatenproceso':'Fecha Proceso', 'fechaatenfinalizado':'Fecha Finalizado', 'fechaatenabierto':'Fecha Abierto', 'id_usuario':'Usuario', 'numeroradicado':'Numero de radicado', 'fechaatencioneps':'Fecha de atencion de EPS', 'descripcioncaso':'Descripcion del caso', 'enfermedad':'Enfermedad', 'formula_medica':'Agregar Formula medico', 'adjunto_seg':'Adjunto Segundo', 'adjunto_terc':'Adjunto Tercero', 'id_comple_info':'Información Complementaria', 'id_seguimiento':'Seguimiento', 'id_barrera':'Barrera', } widgets={ # 'id_caso':forms.NumberInput(attrs={'class':'form-control'}), 'id_usuario':forms.Select(attrs={'class':'form-control'}), 'id_gest': forms.Select(attrs={'class':'form-control'}), 'estado': forms.Select(attrs={'class':'form-control'}), 'fecharesgistrocaso':forms.DateTimeInput(attrs={'class':'form-control datetimepicker-input','type':'datetime-local','placeholder':'ingrese fecha'},format='%Y-%m-%d %H:%M'), 'fechaatenproceso':forms.DateTimeInput(attrs={'class':'form-control datetimepicker-input','type':'datetime-local','placeholder':'ingrese fecha'},format='%Y-%m-%d %H:%M'), 'fechaatenfinalizado':forms.DateTimeInput(attrs={'class':'form-control datetimepicker-input','type':'datetime-local','placeholder':'ingrese fecha'},format='%Y-%m-%d %H:%M'), 'fechaatenabierto':forms.DateTimeInput(attrs={'class':'form-control datetimepicker-input','type':'datetime-local','placeholder':'ingrese fecha'},format='%Y-%m-%d %H:%M'), 'numeroradicado':forms.NumberInput(attrs={'class':'form-control '}), 'fechaatencioneps':forms.DateTimeInput(attrs={'class':'form-control datetimepicker-input','type':'datetime-local','placeholder':'ingrese fecha'},format='%Y-%m-%d %H:%M'), 'descripcioncaso':forms.Textarea(attrs={'class':'form-control '}), 'enfermedad':forms.Select(attrs={'class':'form-control '}), 'formula_medica':forms.FileInput(attrs={'class':'form-control','multiple':True}), 'adjunto_seg':forms.FileInput(attrs={'class':'form-control','multiple':True}), 'adjunto_terc':forms.FileInput(attrs={'class':'form-control','multiple':True}), 'id_comple_info':forms.Select(attrs={'class':'form-control'}), 'id_seguimiento':forms.Select(attrs={'class':'form-control','default':'0'}), 'id_barrera':forms.Select(attrs={'class':'form-control'}), 'hora':forms.TimeInput(attrs={'class':'form-control'}), } mi modelo: class Casos(models.Model): id_caso = models.AutoField(primary_key=True,db_column='id_caso') id_usuario = models.ForeignKey('DatosUsuario', models.DO_NOTHING, db_column='id_usuario') id_gest = … -
ASGI_APPLICATION not working with Django Channels
I followed the tutorial in the channels documentation but when I start the server python3 manage.py runserver it gives me this : Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). October 17, 2022 - 00:13:21 Django version 4.1.2, using settings 'config.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. when I expected for it to give me this : Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). October 17, 2022 - 00:13:21 Django version 4.1.2, using settings 'config.settings' Starting ASGI/Channels version 3.0.5 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. settings.py INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ... ] ASGI_APPLICATION = 'config.asgi.application' asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') application = ProtocolTypeRouter({ 'http': get_asgi_application(), }) It doesn't give any errors even when I change the ASGI_APPLICATION = 'config.asgi.application to ASGI_APPLICATION = ''. -
How do I return the lasso selected groups of a plotly plot in django?
I am trying to take the users lasso select in django to do something with the data they select. The user selects points on plotly graph They press a button on the webpage and the selected points are submitted The data is processed in python I currently have the plot on my web page but cannot get the data out. My view is set up like so. from django.shortcuts import render from plotly.offline import plot import plotly.graph_objects as go import numpy as np def demo_plot_view(request): x = [i for i in range(-10, 10)] y = [np.random.rand()*i for i in range(-5,5) graphs = [go.Scatter(x=x, y=y, mode='markers')] layout = { 'title': 'Title of the figure', 'xaxis_title': 'X', 'yaxis_title': 'Y', 'height': 420, 'width': 560, } plot_div = plot({'data': graphs, 'layout': layout}, output_type='div') return render(request, 'my_app/demo-plot.html', context={'plot_div': plot_div}) The demo-plot.html is <!DOCTYPE HTML> <html> <head> <title>Demo plot</title> </head> <body> {% autoescape off %} {{ plot_div }} {% endautoescape %} </body> </html> -
How to convert string to uniqueidentifier in Django?
I'm trying to insert a pre-generated GUID to MS SQL database from another MS SQL database via Django ORM, but keep getting Conversion failed when converting from a character string to uniqueidentifier. I've already changed my field in model to UUID field and started creating UUID object from my UUID character string, but still I get this mistake. What can I do to effectively insert this data to DB? Part of model: class KmList(models.Model): project_guid = models.UUIDField(primary_key=True) Insertion code: km_objects = [ KmList( project_guid=uuid.UUID(entry.projuid), km_no=entry.projectname, old_id=None, kp_name=entry.kp_name, rev_name=entry.nameproject, chief_name=entry.projectownername, department=entry.department, ) for entry in data ] KmList.objects.bulk_create(km_objects) -
How can I encrypt/decrypt a text field on the fly with django
To simplify, I have a model called Entry with the following fields entry_date description I have a form created with both the fields mapped to it. I want to encrypt the description field while storing in a sqlite database, and decrypt it when retrieving it and displaying for the user interface. I read that I need to create a custom class and implement the encryption and decryption methods in that class. I created a custom class called EncryptedDescription, and added the get_prep_value and from_db_value that saves/retrieves the new field from the database. But should this new custom class (e.g. encrypted_description) be an additional field in my Entry model? Or should I replace the description field with the encrypted_description field? Additionally, how do I map this custom class to a django model form? When I try to add the encrypted_description it gives me an error "encrypted_description cannot be specified for model form as it is a non-editable field" I've browsed through so many examples but I'm still confused about the above two questions. Appreciate your guidance. -
nginx how to host both react and django
i have a react frontend imported inside a django backend. communication between the two is done through django-rest-framework. on the react's side, fetching is done through relative paths therefore in my package.json i have added the line: "proxy": "http://127.0.0.1:8000", django is hosting react-app locally without problems when i run: python3 manage.py runserver. on the remote i am trying to use nginx with gunicorn to deploy this app on aws ubuntu instance and run into the problem: first, i'm running python3 manage.py collectstatic later, i'm pointing nginx to that static_files for the index.html success! nginx serves react static files use gunicorn myapp.wsgi -b 127.0.0.1:8000 to run django problem! nginx served react files do not fetch anything. fetch does not call for this local path but instead calls public ip of aws instance. also, i cannot simulate get/post requests to the django backend because i think nginx "covers" django's gunicorn generated paths. please tell how can i connect nginx-served react frontedn to gunicorn run django my nginx sites-enabled/example server { listen 80 default_server; listen [::]:80 default_server; root /home/ubuntu/fandigger/frontend/build/; server_name public_ip_without_port; location / { try_files $uri $uri/ =404; } } -
ECONNREFUSED when fetching from localhost:3000 to localhost:8000 (Nextjs - DjangoApp)
When trying to make a 'POST' request using the 'fetch' node function, between the frontend and the backend (React Next.js and Django), I got an 'ECONNREFUSED' error. Backend requests using Postman worked as expected. Django is on port: 8000 and Next.js is on port: 3000. It was working until I installed the XCode, Ionic and Capacitor packages (I don't really know if they are the reason I'm getting this error). Here is the error: TypeError: fetch failed at Object.fetch (node:internal/deps/undici/undici:11118:11) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async __WEBPACK_DEFAULT_EXPORT__ (webpack-internal:///(api)/./src/pages/api/account/login.js:18:28) at async Object.apiResolver (/Users/tomas.leblanc/Dev/HermesApp/frontend/node_modules/next/dist/server/api-utils/node.js:185:9) at async DevServer.runApi (/Users/tomas.leblanc/Dev/HermesApp/frontend/node_modules/next/dist/server/next-server.js:395:9) at async Object.fn (/Users/tomas.leblanc/Dev/HermesApp/frontend/node_modules/next/dist/server/base-server.js:496:37) at async Router.execute (/Users/tomas.leblanc/Dev/HermesApp/frontend/node_modules/next/dist/server/router.js:226:36) at async DevServer.run (/Users/tomas.leblanc/Dev/HermesApp/frontend/node_modules/next/dist/server/base-server.js:606:29) at async DevServer.run (/Users/tomas.leblanc/Dev/HermesApp/frontend/node_modules/next/dist/server/dev/next-dev-server.js:450:20) at async DevServer.handleRequest (/Users/tomas.leblanc/Dev/HermesApp/frontend/node_modules/next/dist/server/base-server.js:321:20) { cause: Error: connect ECONNREFUSED ::1:8000 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16) { errno: -61, code: 'ECONNREFUSED', syscall: 'connect', address: '::1', port: 8000 } } Would be nice if someone could help me dealing with this error! If you need more details or project files, please fill free to ask :D -
Prevent Django to save an specific form from a formset
I'm working with a Django formset and I'm trying to prevent certain forms that could be partially filled to be saved. Form: class WeeksForm(forms.ModelForm): monday = forms.DecimalField(required=False) tuesday = forms.DecimalField(required=False) wednesday = forms.DecimalField(required=False) thursday = forms.DecimalField(required=False) friday = forms.DecimalField(required=False) saturday = forms.DecimalField(required=False) sunday = forms.DecimalField(required=False) class Meta: model = Weeks fields = ('activity', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday') Formset: WeeksFormset = modelformset_factory(Weeks, form=WeeksForm, extra=10, can_delete=True) I'm dynamically generating the forms using JS and it automatically fills the field 'activity' but the problem is that sometimes the user might decide to not complete the other fields (those named with weekdays, "monday", "tuesday", etc...). If that is the case I end up with an "empty" form (not really empty because the field "activity" was filled) that I'm not interested in saving. I'm trying to somehow prevent in my view that these forms are saved: views.py if request.method == 'POST': formset = WeeksFormset(request.POST) if formset.is_valid(): for form in formset.forms: # From here is pseudocode, I want that if a form has all the weekdays empty that form is not saved if form.instance.monday and form.instance.tuesday and ... form.instance.sunday == None: form.delete() # End of pseudocode, this approach didn't work form.instance.user = request.user … -
django application code in @staticmethod or class?
I have long functions in my Django application like process staff pay, I dont want these functions directly in the view, so I moved them out to their own python files but the only way I could call the functions from the view was to make them @staticmethod, this seems wrong. How do I create a module and then call the functions without making the functions static? -
Django - constraint that uses related field value
As of now, it isn't possible to create constraints that use joins so I'm trying to figure out how I can do this. I want to make sure (on a DB level) that ResponseDetail.object is NOT null if response__action=='added' and IS null if response__action=='removed'. I can't modify Response model. class Response(..): action = CharField # added/removed class ResponseDetail(..): response = OneToOneField.. object = OneToOneField... class Meta: constraints = [ # CheckConstraint( # check=Q( # Q(response__action="added", object__isnull=False) # | Q(response__action="removed", object__isnull=True) # ), # name="object_only_if_action_added", # ) ] The CheckConstraint would work if Postgres and Django supported joins in constraints. Another solution is to add ResponseDetail.response_action field but I'm curious if there is a solution that doesn't expect me to add such field. -
Django rest framework - using SerializerMethodField with ModelSerializer
I have the following models. models.py class Language(models.Model): name = models.CharField(max_length=255, unique=True) class Subject(models.Model): name = models.CharField(max_length=255, unique=True) class Term(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) language = models.ForeignKey(Language, on_delete=models.CASCADE) name = models.CharField(max_length=255) definition = models.TextField() image = models.ImageField(default='', blank=True) I want to write a Serializer that will return a list of subjects. Each subject has a term field, which contains None or a single object, depending on the condition. serializers.py class TermSerializer(serializers.ModelSerializer): language = serializers.CharField(source='language.name') def to_representation(self, data): data = data.get(language=self.context['language']) return super(TermSerializer, self).to_representation(data) class Meta: model = Term fields = ('id', 'language', 'name', 'definition', 'image') class FilteredSubjectSerializer(serializers.ListSerializer): def to_representation(self, data): if self.context['condition']: terms = Term.objects.filter(language=self.context['language']) data = data.filter(term__in=terms) return super(FilteredSubjectSerializer, self).to_representation(data) class SubjectSerializer(serializers.ModelSerializer): term = serializers.SerializerMethodField() def get_term(self, term): if self.context['condition']: return TermSerializer(many=False, source='term_set').data return None class Meta: model = Term list_serializer_class = FilteredSubjectSerializer fields = ('id', 'name', 'definition', 'image', 'term') The problem is that when condition == True, the ViewSet returns incorrect data. All fields inside term have a default value. It works fine if I write SubjectSerializer like this: class SubjectSerializer(serializers.ModelSerializer): term = serializers.TermSerializer(many=False, source='term_set') class Meta: model = Term list_serializer_class = FilteredSubjectSerializer fields = ('id', 'name', 'definition', 'image', 'term') But the case when condition == False doesn't … -
Django render many to many in template
I have this models: class roles(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255, blank=False) company = models.ForeignKey(Company, blank=True, null=True, on_delete=models.SET_NULL) def __str__(self): return self.name class freelancers(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) company = models.ForeignKey(Company, blank=True, null=True, on_delete=models.SET_NULL) user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) role = models.ManyToManyField(roles) I try to get the name that is related to the user at the roles table. In my view.py It looks like this: def company_details(request,id): obj = Company.objects.get(id=id) pro = Projects.objects.filter(company=id) free = freelancers.objects.filter(company=id) #free = freelancers.objects.all() return render(request, 'company/company_details.html', { 'obj':obj, 'pro':pro, 'free':free, } ) And in the HTML: {% for f in free %} {{ f.user }} // <br/> {% endfor %} {{ f.role.all }} {% endfor %} I have been trying different ways to get the name to show up. Like: {{ f.role.name }}. So any tips to make this work? -
can't compare datetime.datetime to datetime.date django
I'm trying to build reservation app. I tried to find the solution but I have no idea. import datetime def check_availability(room, check_in, check_out): avail_list = [] booking_list = Booking.objects.filter(room=room) for booking in booking_list: if booking.check_in > check_out or booking.check_out < check_in: avail_list.append(True) else: avail_list.append(False) return all(avail_list) from hotelbooking.booking_funkctions.availibility import check_availability class BookingView(FormView): form_class = AvalilabilityForm template_name = 'availability_form.html' def form_valid(self, form): data = form.cleaned_data room_list = Room.objects.filter(category=data['room_category']) available_rooms=[] for room in room_list: if check_availability(room, data['check_in'], data['check_out']): available_rooms.append(room) if len(available_rooms)>0: room = available_rooms[0] booking = Booking.objects.create( user = self.request.user, room = room, check_in = data['check_in'], check_out = data['check_out'] ) booking.save() return HttpResponse(booking) else: return HttpResponse('this category of rooms are booked') class AvalilabilityForm(forms.Form): ROOM_CATEGORIES = ( ('YAC', 'AC'), ('NAC', 'NON-AC'), ('DEL', 'DELUXE'), ('KIN', 'KING'), ('QUE', 'QUEEN'), ) room_category = forms.ChoiceField(choices=ROOM_CATEGORIES, required=True) check_in = forms.DateField(required=True, input_formats=["%Y-%m-%dT%H:%M", ]) check_out = forms.DateField(required=True, input_formats=["%Y-%m-%dT%H:%M", ]) -
docker containers can not connect to each other
I have a django-rest-framwork app which uses PosgreSql as db. So I am using docker containers for them one image for django-rest-framwork and one for PosgreSql, and then docker compose file to handle them. db service refrese to PostgreSQL backend refers to Django Rest app I have a docker-compose file version: '3.9' services: db: image: postgres:latest restart: always ports: - "5432:5432" environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=85842475DB - POSTGRES_DB=sports_center_db - POSTGRES_PORT=5432 backend: build: ./api depends_on: - db ports: - "8000:8000" environment: - DB_NAME=sports_center_db - DB_USER_NAME=postgres - DB_PASSWORD=85842475DB - DB_HOST=db - DB_PORT=5432 It builds correctly but when I ran docker compose up I got following logs [+] Running 2/2 ⠿ Container sports_center-db-1 Created 0.1s ⠿ Container sports_center-backend-1 Created 0.1s Attaching to sports_center-backend-1, sports_center-db-1 sports_center-db-1 | The files belonging to this database system will be owned by user "postgres". sports_center-db-1 | This user must also own the server process. sports_center-db-1 | sports_center-db-1 | The database cluster will be initialized with locale "en_US.utf8". sports_center-db-1 | The default database encoding has accordingly been set to "UTF8". sports_center-db-1 | The default text search configuration will be set to "english". sports_center-db-1 | sports_center-db-1 | Data page checksums are disabled. sports_center-db-1 | sports_center-db-1 | fixing permissions on existing … -
Django inlineformset_factory. Request.FILES not returning filename to form when formset.is_valid() = False
I'm trying to allow the user to upload images tied to a project. I'm doing this via an inlineformset_factory. Im serving the form to the user trough a function based view. When the user fails to fill in one (or more) of the formsets correctly formset.is_valid() returns false and the bound formsets get returned to the user along with error messages. What i'm having trouble with is that the imagefield is not returned to the bound form. So if the user has filled in 2 out of 3 forms correctly then neither of the formsets have a bound imagefield after the failed validation. I can't manage to figure out if this is working as intended or if i'm doing something wrong. If i print out request.FILES i get the following: <MultiValueDict: {'image_set-0-filename': [<InMemoryUploadedFile: IMG_0017.jpg (image/jpeg)>], 'image_set-1-filename': [<InMemoryUploadedFile: sprite.svg (image/svg+xml)>]}> I would like the imagefield to be bound and show the user what value the field has. before incorrect form submission after incorrect form submission Hopefully you can see where my mistake is or tell me if i'm thinking about this the wrong way. Thank you in advance forms.py class EndUserImageForm(forms.ModelForm): class Meta: model = Image fields = ["filename", "description"] widgets … -
Django - Optimize grouping
I have a model: from django.db import models class Product(models.Model): sku = models.IntegerField() plu = models.CharField() pack_type = models.ForeignKey(PackTypes, on_delete=models.CASCADE) I need to group them into data structure: { < plu_1 >: { < sku_1 >: [ < pack_type_id_1 >, < pack_type_id_2 >, ... ], < sku_2 >: [], ... }, <plu_2>: { ... } } The code that does it: def dict_with_list(): return defaultdict(list) result = defaultdict(dict_with_list) products = Product.objects.values_list('sku', 'plu', 'pack_type_id') for (plu, sku, pack_type_id) in products: result[plu][sku].append(pack_type_id) The problem with it is because there are a lot of records in model Product the code is slow (> 5 seconds). How could I optimize the code to be faster? -
Unable to load multiple content blocks in Django 4.0 using TailwindCSS
Folder Structure: mysite -theme --templates ---main_base.html ---theme_footer.html ---theme_menu.html -home --templates ---home ----main.html main.html: {% extends "main_base.html" %} {% block content %} blah blah {% end content %} main_base.html: {% load static tailwind_tags %} <!DOCTYPE html> <html lang="en"> <head> {% tailwind_css %} </head> <body class="bg-blue-100"> <nav> {% block navbarn %} {% endblock %} </nav> {% block content %} {% endblock %} <footer> {% block footer %} {% endblock %} </footer> </body> </html> theme_menu.html: {% extends "main_base.html" %} {% block navbarn %} home {% endblock %} theme_footer.html {% extends "main_base.html" %} {% block footer %} <h1>this is a footer</h1> {% endblock %} So I was able to setup Django with Tailwind following the instructions on the plugin page. But I can't get the base theme to show multiple blocks. It doesn't show the menu nor the footer, just the base html template with content from main.html. Can't get it to work!