Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'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! -
Installing html5lib for Python on Ubunto
I am attempting to implement my selenium test suite for my Django app, but first want to install crispy forms. Apparently crispy forms has a dependency on html5lib, but for some reason when I attempt to pip install that I receive the below error. How do I adjust my system to grab and install html5lib? Traceback (most recent call last): File "/home/satch/.local/bin/pip", line 8, in <module> sys.exit(main()) File "/usr/lib/python3/dist-packages/pip/_internal/cli/main.py", line 73, in main command = create_command(cmd_name, isolated=("--isolated" in cmd_args)) File "/usr/lib/python3/dist-packages/pip/_internal/commands/__init__.py", line 104, in create_command module = importlib.import_module(module_path) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/usr/lib/python3/dist-packages/pip/_internal/commands/install.py", line 24, in <module> from pip._internal.cli.req_command import RequirementCommand, with_cleanup File "/usr/lib/python3/dist-packages/pip/_internal/cli/req_command.py", line 16, in <module> from pip._internal.index.package_finder import PackageFinder File "/usr/lib/python3/dist-packages/pip/_internal/index/package_finder.py", line 21, in <module> from pip._internal.index.collector import parse_links File "/usr/lib/python3/dist-packages/pip/_internal/index/collector.py", line 14, in <module> from pip._vendor import html5lib, requests ImportError: cannot import name 'html5lib' from 'pip._vendor' (/usr/lib/python3/dist-packages/pip/_vendor/__init__.py) -
Populate model instance with another model data during instance creation
I have creating an app as my learning project in Django. There are 3 model classes: # MOC class class Moc(models.Model): name = models.CharField(max_length=128, blank=True, null=True) my other fields... def __str__(self): return str(self.id) def save(self, *args, **kwargs): created = not self.pk super().save(*args, **kwargs) if created: CheckList.objects.create(moc=self) # Pre Implement class class CheckList(models.Model): moc = models.OneToOneField(Moc, related_name='checklist', on_delete=models.CASCADE, default='1') name = models.CharField(max_length=128, blank=True, null=True) def __str__(self): return str(self.id) def save(self, *args, **kwargs): created = not self.pk super().save(*args, **kwargs) if created: CheckListItem.objects.create(checklist=self) # Pre Implement Items class class CheckListItem(models.Model): checklist = models.ForeignKey(CheckList, related_name='checklistitems', on_delete=models.CASCADE, default='1') action_item = models.TextField(max_length=128, blank=True, null=True) actionee_name = models.ForeignKey(User, related_name='actionee_ready_pre_implements', on_delete=models.CASCADE, default='1') action_due = models.DateField(blank=True, null=True) def __str__(self): return str(self.id) I am creating Moc instance and on post save signal creating my CheckList class instance and consequently my CheckListItem class instances. However, imaging that my CheckList once created always should have 10 CheckListItem objects as a pre populated list (like an initial data). I could not figure-out if this is something doable (at least how I am trying to achieve it as per my model relationships). I do not want to hard code thus items in my HTML, I want to control add/delete of thus CheckListItems for related … -
MySql Client pip package isn't installing / is broken
When I run the command: pip3 install mysqlclient or pip install mysqlclient I get the following error: Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [16 lines of output] /bin/sh: 1: mysql_config: not found /bin/sh: 1: mariadb_config: not found /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-install-jpxeffqw/mysqlclient_fed1a50532b74bc1aeaab814d12b88df/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-jpxeffqw/mysqlclient_fed1a50532b74bc1aeaab814d12b88df/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-jpxeffqw/mysqlclient_fed1a50532b74bc1aeaab814d12b88df/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. The package is broken I guess but I need to run this now to make it work with my Django project. Any suggestions on any alternates or other command I could run … -
Updating data without redirecting to an update template
I'm learning django and trying to make a to-do app. I want to be able to change the status of a task from 'active' to 'finish' without redirecting the user to a different page just to update the status of a task. i've been reading the docs for the UpdateView class to see if there was a method that allow me to update the value of the status directly but couldn't find anything. -
Custom User Manager is not working in django
I have problem with custom user manager. It's not working properly, i mean it was working well but it stopped for some reason that i don't know (maybe i broke something). I can create user through my register page, but if i delete whole UserManager class nothing changes. It doesnt raise errors even if it should, normalize class for email is not working etc. What's more when i create superuser via "python manage.py createsuperuser" command everything is working fine. Models.py class CustomUserManager(BaseUserManager): def _create_user(self, email, user_name, password, first_name, last_name, **extra_fields): if not email: raise ValueError("Email must be provided") if not password: raise ValueError("Password is not provided") user = self.model( email=self.normalize_email(email), user_name = user_name, first_name = first_name, last_name = last_name, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, user_name, password, first_name, last_name, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) extra_fields.setdefault('is_superuser', False) return self._create_user(email, user_name, password, first_name, last_name, **extra_fields) def create_superuser(self, email, user_name, password, first_name, last_name, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) extra_fields.setdefault('is_superuser', True) return self._create_user(email, user_name, password, first_name, last_name, **extra_fields) class MyUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(db_index=True, unique=True, max_length=254) user_name = models.CharField(max_length=50, unique=True) first_name = models.CharField(max_length=240) last_name = models.CharField(max_length=240) friends = models.ManyToManyField('self', blank=True) date_joined = models.DateTimeField(auto_now_add=True) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_superuser = … -
I have a problem with MySQL and Django on Docker: "sql_mode=only_full_group_by"
"Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'database_name.i.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by" Hi, sorry for me English. I have a problem with MySQL and Django when I dockerize my project. I'm new with this technologies. This is part of my docker-compose file: db_mysql: image: mysql:8 container_name: db_mysql restart: always environment: MYSQL_ROOT_PASSWORD: password MYSQL_DATABASE: database_name MYSQL_USER: user MYSQL_PASSWORD: password ports: - '3306:3306' expose: - '3306' volumes: - dbdata:/var/lib/mysql The problem appears when I deploy my project and enter a section. The message I showed initially appears. I tried to apply what is mentioned in this post, but the problem persists. SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by I did the following: I entered the container of my db: docker exec -it db_mysql bash I logged in to MySQL with the root user: mysql -u root -p I placed the command to change the value of SQL_MODE: SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY','')); I checked that the change has been made: SELECT @@sql_mode; I exited the container and restarted it with: docker restart db_mysql When … -
Expecting to get "non_field_errors: Unable to log in with provided credentials", but not getting it
Expectation: when wrong login credentials are provided, "non_field_errors: Unable to log in with provided credentials" is returned, such as below (screenshot from a tutorial which I'm following verbatim) Reality: instead I'm getting the error below. This gets printed to the console: POST http://127.0.0.1:8000/api/v1/token/login 400 (Bad Request) Interestingly I get this same error when I try to create users with passwords that are too short. I'm not having any issues with axios or the server when I provide the right credentials for log in, or use passwords of sufficient length when creating new users. When trying to catch errors such as these that I'm failing to get the expected result. My code for catching the error is the same as in the tutorial: methods: { submitForm() { axios.defaults.headers.common['Authorization'] = '' localStorage.removeItem('token') const formData = { username: this.username, password: this.password } axios .post('/api/v1/token/login', formData) .then(response => { const token = response.data.auth_token this.$store.commit('setToken', token) axios.defaults.headers.common['Authorization'] = 'Token ' + token localStorage.setItem('token', token) this.$router.push('/dashboard/my-account') }) .catch(error => { if (error.response) { for (const property in error.response) { this.errors.push(`${property}: ${error.response.data[property]}`) } } else if (error.message) { this.errors.push('Something went wrong. Please try again!') } }) } } Is there something in the server settings that I … -
Is there a way to use django url template in json_script?
trying to find a way to save a url into a json script but its not rendering and reading it literally unlike other values: Tried this way {{ "{% url 'tutorhomepage:tutorSelectedDay' tutor_id selected_date%}" | json_script:"url_test"}} And this way: {{ url_test | json_script:"{% url 'tutorhomepage:tutorSelectedDay' tutor_id selected_date%}"}} But still comes out like this: <script id="url_test" type="application/json">"{% url 'tutorhomepage:tutorSelectedDay' tutor_id selected_date%}"</script>