Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to disable options in form based on current data in database in Django?
I have a form where users can enter a timestamp whenever they have messed up the time they submitted previously. I am changing it so that the timestamp submitted can be either an entry or an exit, based on the button the user clicks. Right now, I have two boxes for the user to enter their timestamp, to know whether is an entry or an exit timestamp, like shown below: <div class="checkbox"> <label for="chk"><input type="checkbox" value="0" id="chk" /> Requires manager approval</label> </div> <div style="padding-top: 10px; text-align: center; display: none" id="appreq"> <input type="checkbox" value="0" id="modinchk" /> Modify Entry <div style="display: none" id="modin"> <label>Time In</label> {% standard_input form.modified_in datetimepicker=True hide_label=True %} </div> <input type="checkbox" value="0" id="modoutchk" /> Modify Exit <div style="display: none" id="modout"> <label>Time Out</label> {% standard_input form.modified_out datetimepicker=True hide_label=True %} </div> </div> Is there a way to change it so that there is some sort of temporary variable, so that I can have only one box where they enter the date/time and when they click either enter or exit, the temporary variable data moves to either modified_in or modified_out? I imagine this second part would be handled in views, but I don;t know how I can have a temporary variable instead … -
Send email to application users via Djano
So, in my case users enter their name, email, motivation letter and so on. When they click button, the users only with status=3 should accept email from admin's email address. I did this task as follows, but can't get any email. index.html: <form action="{% url 'index' %}" method="POST"> {% csrf_token %} <input type="text" name="name" required minlength="3"><br /> <input type="email" name="email" required minlength="10"><br /> <textarea rows="5" name="motivation_letter" required></textarea><br /> <input type="submit" value="Send" class="apply-button"> </form> models.py: class Applicant(models.Model): name = models.CharField(max_length=20) birth_date = models.DateField(blank=False) email = models.EmailField(max_length=40) motivation_letter = models.TextField(max_length=200) status = models.ForeignKey(ApplicantStatus, on_delete=models.CASCADE, default=3) def __str__(self): return self.name views.py: def email(request): if request.method == 'POST': subject = 'Welcome!' message = 'We'll back to you.' email_from = settings.EMAIL_HOST_USER recipient_list = request.POST['sender_email'] send_mail(subject, message, email_from, recipient_list) return redirect('index.html') urls.py: urlpatterns = [ path('', views.index, name='index'), path('', views.email, name='email'), ] -
Use of parameters in URL depending on their existence django rest framework
I'm using DRF and Django, I have uid and full_name in my database, how to insert parameters into the URL depending on their emptiness or on None? For instance if full_name of record is None or is empty string then url should be like this: http://localhost:8000/something/{uid} Else if full_name is okay then url should be like this: http://localhost:8000/something/{full_name} -
Django FullCalendar with Django 2.x or 3.x
Okay, I know that this question has been asked a lot of times, but it seems that I can't understand it by myself. I need to implement FullCalendar into my Django application, and after I downloaded FullCalendar with all the statics and stuff, and after rendered it on my page, I just can't add new Events by any chance. I have my Event model, with start_date, end_date, id, and title, like someone explained it here. After that, I made a function in my views.py called all_events, where event = Event.object.all(), and put that in the context variable. I have no forms at this time, I just want to render it after I enter the data from my admin page - for now. Want to be as simple as possible. This is my code : models.py class Events(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, null=True, blank=True) start = models.DateTimeField(null=True, blank=True) end = models.DateTimeField(null=True, blank=True) class Meta: verbose_name = 'Event' verbose_name_plural = 'Events' def __str__(self): return self.name views.py def events(request): all_events = Events.objects.all() context = { "events": all_events, } return render(request, '.../selectable.html', context) urls.py path('.../add_event', add_event, name='add_event'), And my html page : {% block content_row %} <!DOCTYPE html> <html> <head> <script src="{% … -
What's the best way to handle(or alternative) the use case of creating multiple table from single model in Django
I have a use-case where a client registers to my platform and I have to give them a separate table in a database using a common model in Django. Although I have been able to create multiple tables from a single model on runtime, I don't think its the best solution to the problem and I have seen some issues with it on my testing like when doing migrations of the model and Django admin pages, etc. Are there any other alternatives to this problem? How do other companies handle such issues? -
Loading audio file to template causes ConnectionResetError: [Errno 54] Connection reset by peer (Django, Python)
I am making an audio player webapp using Django. The audio files are uploaded by admin via a model that adds the file to my Media directory. Then in my template the audio files are displayed with an individual audio player. {% for song in songs %} <audio class="player" controls> <source src="{{ song.audio_file.url }}" type="audio/wav"> </audio> {% endfor %} Now, the website works as intended. The audio players all become visible and are working correctly. However in my terminal, every time the page is loaded I get errors of this type (depending on how many audio files that are to be displayed, if there only is one file i get this for example): [13/Dec/2019 12:03:31] "GET /media/ap/song.wav HTTP/1.1" 200 1626112 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 60242) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 639, in process_request_thread self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 361, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 696, in __init__ self.handle() File "/Users/oscarjonsson/python-virtual-environments/django_env/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "/Users/oscarjonsson/python-virtual-environments/django_env/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socket.py", line 586, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer What could be the cause of this? Would appreciate any … -
Converting a String into Datetime with Hour and Minute
In my python project, I have a date field: event_date = models.DateField(auto_now=False, default=None, null=True, blank=True) in the controller, I convert string and save as follows: event_date = body["event_date"] # <- string date = datetime.datetime.strptime(event_date, "%Y-%m-%dT%H:%M:%S.%fZ").date() works fine, but it saves as "2019-02-12" - which is also normal date() function returns only that part. What I want is to save as "2019-02-12 20:05". How can I achieve this with Python? Thank you. -
Show user error message if form is not filled via HttpResponseRedirect
I'm trying to create the functionality so that a user is returned to the url with an error message if they don't fill in the forms. My urls from django.urls import path from content import views urlpatterns = [ path('readerpage/<int:content_id>', views.readerpage, name='readerpage'), path('readerpage/<int:content_id>/add_review', views.add_review, name='add_review'), ] My view def add_review(request, content_id): content = get_object_or_404(Content, pk=content_id) if request.POST['readability'] and request.POST['readability_rating'] and request.POST['actionability'] and request.POST['actionability_rating'] and request.POST['general_comments']: review = Review() review.readability = request.POST['readability'] review.readability_rating = request.POST['readability_rating'] review.actionability = request.POST['actionability'] review.actionability_rating = request.POST['actionability_rating'] review.general_comments = request.POST['general_comments'] review.avg = (float(review.readability_rating) + float(review.actionability_rating)) / 2 review.content = content review.save() return redirect('home') else: return HttpResponseRedirect(reverse('readerpage', args=(content_id,))) Right now the user gets returned but doesn't get an error message I've tried with the return render, instead of the HttpResponseRedirect return render (request, 'content/readerpage', {'error': 'You need to fill in all information'}) But that send the user to the wrong url, creating an error, as it adds the add_review to the to URL http://127.0.0.1:8000/content/readerpage/41/add_review Is there any way to pass along the error with the HttpResponseRedirect? Or is there another alternative? Thanks for reading this -
Django - Model is not defined
With the following I get "Plant is not defined" class Resource(models.Model): resources = models.ForeignKey(Plant,related_name='resources',on_delete=models.PROTECT) class Plant(models.Model): resources = models.ForeignKey(Resource,related_name='plant',on_delete=models.PROTECT) When I turn them around, I get "Resource is not defined" Thank you for any help -
When I save a Django model, I get an error with regards to the date time field requiring bytes or string
I am getting an error "TypeError: expected string or bytes-like object" when saving an object. The view looks like: person = Person.objects.get(id=request.data["person_id"]) firstname = request.data["firstname"] lastname = request.data["lastname"] dateofbirth = request.data["dateofbirth"] datetimeDOB = parser.parse(dateofbirth) try: person.firstname = firstname, person.lastname = lastname, person.dateofbirth = datetimeDOB person.save() The model looks like: class Person(models.Model): firstname = models.CharField(max_length=50,default='',blank=False) lastname = models.CharField(max_length=50,default='',blank=False) dateofbirth = models.DateTimeField(null=False) dateadded = models.DateTimeField(auto_now=True) def __str__(self): return self.firstname I have tried adding the date without the parse function, but that still gets rejected. If I forget about updating the dateofbirth field then it saves, but I get strange characters in the firstname and lastname fields. For example "first", "last" becomes "('first');","('last');". If I change the code to create a new person record to test the database object and the posted data using code as below then it creates a new person correctly, "first","last" and dateofbirth correctly formatted as date time. Person.object.create( person.firstname = firstname, person.lastname = lastname, person.dateofbirth = datetimeDOB ); This is why I am really confused as I use the same method to update other objects and don't get this issue. Also if I can create, why can't I update it without these errors? -
Invalid Requirement ERROR while installing a local git repository of Django
I am trying to install the development version of Django in a virtual environment. A local repo lives inside: "C:\Users\AARYAN DEWAN\Desktop\localdjango\django" I first created a virtual environment inside "C:\Users\AARYAN DEWAN\Desktop\virualenvs" using py -m venv .\djangodev. Then I activated it. Now when I try to follow the Django Docs and install the local django repo inside this virtual environment, using py -m pip install -e C:\Users\AARYAN DEWAN\Desktop\localdjango\django, it throws up an error saying: ERROR: Invalid requirement: 'DEWAN\\Desktop\\localdjango' Hint: It looks like a path. File 'DEWAN\Desktop\localdjango' does not exist. I have tried replacing the path with this: py -m pip install -e C:\Users\AARYAN DEWAN\Desktop\localdjango, but it still does not work!? What should I do? -
AttributeError: module 'allauth.models' has no attribute 'Group'
views.py def teachers(request): group = models.Group.objects.get(name='teachers') list_teachers = group.user_set.all() return render( request, 'teachers.html', { 'list_teachers' : list_teachers } ) Internal Server Error: /teachers/ Traceback (most recent call last): File "C:\python 3.7.4\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\python 3.7.4\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\python 3.7.4\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Homie\Desktop\defenseMilestone\defense\milestone\views.py", line 55, in teachers group = models.Group.objects.get(name='teachers') AttributeError: module 'allauth.models' has no attribute 'Group' [13/Dec/2019 16:50:51] "GET /teachers/ HTTP/1.1" 500 66823 -
Django ArrayField Filtering with contains matching
I'm using Django Postgres ArrayField response_headers = ArrayField(models.TextField(blank=True),blank=True,null=True,default=list) Let's suppose our object has the following data: obj1 : response_headers = ["dubai","sydney","nyc"] obj2 : response_headers = ["mumbai","kerela","dubai"] MyModel.objects.filter(response_headers__contains=['dubai'] would return obj1 & obj2 but MyModel.objects.filter(response_headers__contains=['duba'] won't return any objects <QuerySet []> How do I achieve the ability to search with the partial pattern across all indexes of ArrayField? -
Folder creation in docke-compose volume
I have a Django project running with docker-compose for dev env. I'm struggling with file/folder creation on an aws server (AMI ubuntu-bionic) I mounted a volume on my backend_container with the projects files. On my local computer, file/folder creation from django inside the container and to the volume works well. On the server everything seem to work as expected (no errors whatsoever), but when I ls to find my folders/files, they aren't there. I tried to debug it myself, but so far : when I exec into the container, I can create folders ~/project-backend$ docker exec -it project_backend_container /bin/bash root@d34b85516a59:/code# mkdir test root@d34b85516a59:/code# ls __pycache__ app manage.py static test uploads project when I run the shell with django, I can also create folders root@d34b85516a59:/code# python manage.py shell Python 3.7.4 (default, Sep 12 2019, 15:40:15) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> import os >>> os.makedirs('my/awesome/dirs') >>> now exiting InteractiveConsole... root@d34b85516a59:/code# ls __pycache__/ app/ manage.py my/ static/ uploads/ I tried to override django storage class to log errors, but everything is going fine. From the django side, everything looks alright. My knowledge on docker layers and filesystem management for volume is clearly lacking … -
Django custom middleware not adding custom header
So I'm trying to add a custom header to every request in my Django app, I followed this question, and my setup looks like this: middleware.py: from django.utils.deprecation import MiddlewareMixin class ReverseProxyLocalMiddleware(MiddlewareMixin): def process_request(self, request): request.META['User-Id'] = 1 settings.py: ... MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'myapp.middleware.ReverseProxyLocalMiddleware', ] However, anytime I try and access the new header in a test I get: def list(self, request): > user_id = request.META['User-Id'] E KeyError: 'User-Id' Does anyone have any idea what I'm doing wrong? -
import JSON data to models in Django
I am a bit lost, I have been trying for several hours to understand how deserialization works ... I would like to import the data from this json file: my models: class Company(models.Model): name = models.CharField(max_length=100) sector = models.CharField(max_length=100) siren = models.IntegerField() class Result(models.Model): company = models.ForeignKey('Company', on_delete=models.CASCADE) ca = models.IntegerField() margin= models.IntegerField() ebitda = models.IntegerField() loss = models.IntegerField() year = models.IntegerField() what my JSON file looks like: [{"name":"Reinger Inc","sector":"Services","siren":135694027,"results":[{"ca":2077357,"margin":497351,"ebitda":65952,"loss":858474,"year":2017},{"ca":432070,"margin":427778,"ebitda":290433,"loss":8023406,"year":2016}]}, {"name":"Torphy, Rosenbaum and Rempel","sector":"Electronic","siren":107855014,"results":[{"ca":364921,"margin":61976,"ebitda":960673,"loss":2812728,"year":2017},{"ca":1944186,"margin":738525,"ebitda":846608,"loss":657145,"year":2016}]}] -
Django giving "TypeError: unhashable type:" while creating superuser
I have customized the default User model of Django. While I am creating superuser from the terminal it's giving me this return self._forward_fields_map[field_name] TypeError: unhashable type: 'list' error. The attached image can give you more details of the error. This is my models.py. from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin ) class UserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError(_('The Email must be set')) if not password: raise ValueError(_('The Password must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_staffuser(self, email, password): user = self.create_user( email=email, password=password, ) user.is_staff = True user.save(using=self._db) return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(db_index=True, max_length=255, unique=True) name = models.CharField(max_length=255, null=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) token = models.CharField(max_length=192, null=True, default=None) verified_at = models.DateTimeField(null=True, default=None) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [], objects = UserManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True def is_verified(self): return self.verified_at … -
How to generate composite Schema from Serializers for package drf-yasg?
I am using drf-yasg package in django to generate docs. I want to provide response as a composite of serializers. I am using the type as OBJECT and defining its properties. I am not able to figure out how to do it. My code: openapi.Schema(type=openapi.TYPE_OBJECT, properties={'top_suggestions': top_schema,'mentors_suggestions': UserSkillSerializer}) Here top_schema is manually defined schema and mentor_suggestions will take in the schema generated from UserSkillSerializer. -
Save Future Occurrences W.R.T event_id
class Occurrence(models.Model): last_updated = models.DateTimeField(default=timezone.now) time_modified = models.BooleanField(default=False) start_time = models.DateTimeField(_('start time')) end_time = models.DateTimeField(_('end time')) event = models.ForeignKey(Event, verbose_name=_('event'), editable=False) lead_technician = models.ForeignKey('mbi.Employee', related_name='tasks_lead') team = models.ManyToManyField('mbi.Employee', related_name='assigned_tasks', blank=True) vehicles = models.ManyToManyField('vehicles.Vehicle', related_name='assigned_tasks', blank=True) class EditOccurrenceForm(forms.Form): date = forms.DateField(widget=SelectDateWidget) start_time = forms.TimeField(widget=TimePicker) end_time = forms.TimeField(widget=TimePicker) lead_technician = forms.ModelChoiceField(queryset=Employee.objects.all(), widget=Select2Widget) vehicles = Select2M2MField(queryset=Vehicle.objects.all(), widget=Select2Widget, required=False) team = Select2M2MField(queryset=Employee.objects.all(), widget=Select2Widget, required=False) note = forms.CharField(widget=forms.Textarea(attrs={'cols': 40, 'rows': 2}), required=False) managers_note = forms.CharField(widget=forms.Textarea(attrs={'cols': 40, 'rows': 2}), required=False) managers_extra_billing = forms.DecimalField(widget=forms.NumberInput(attrs={}),decimal_places=2, required=False, min_value=0) def __init__(self, *args, **kwargs): if 'occurrence' in kwargs: self.occurrence = kwargs.pop('occurrence') if 'user' in kwargs: self.user = kwargs.pop('user') if 'save_all' in kwargs: self.save_all = kwargs.pop('save_all') # if 'changed_data' in kwargs: # self.ch_data = kwargs.pop('changed_data') super(EditOccurrenceForm, self).__init__(*args, **kwargs) tz = timezone.get_current_timezone() start = tz.normalize(self.occurrence.start_time) end = tz.normalize(self.occurrence.end_time) self.fields['date'].initial = start.date() self.fields['start_time'].initial = start.time() self.fields['end_time'].initial = end.time() self.fields['lead_technician'].initial = self.occurrence.lead_technician self.fields['team'].initial = self.occurrence.team.all() self.fields['note'].initial = self.occurrence.note self.fields['vehicles'].initial = self.occurrence.vehicles.all() self.fields['managers_note'].initial = self.occurrence.managers_notes self.fields['managers_extra_billing'].initial = self.occurrence.managers_extra_billing def clean(self): try: start_time = datetime.datetime.combine(self.cleaned_data['date'], self.cleaned_data['start_time']) end_time = datetime.datetime.combine(self.cleaned_data['date'], self.cleaned_data['end_time']) except KeyError: # user will not see this error. # error will be displayed in the view raise ValidationError("Time is invalid. Please re-enter in a valid format (HH:MM OR H:MM AM/PM)") logger.debug("EditOccurrenceForm dates: %s - %s", start_time, … -
Passing kwargs to parent class from inheritance relationship in child class
I have a parent class RestResponse and inheritance relationship with child class AccessDeniedResponse like this: class RestResponse(Response): def __init__(self, data=None, content_type=None, message=None, count=None, data_status=True, **kwargs): data_content = { 'status': data_status, 'message': message, 'data': data, } if count: data_content.update({ 'count': count }) super(RestResponse, self).__init__( data=data_content, content_type=content_type, **kwargs ) class AccessDeniedResponse(RestResponse): status_code = 401 when i call AccessDeniedResponse(errorMessage= 'You are not authorised to download.') It will give this error: Traceback (most recent call last): File "/home/ram/goenv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/ram/goenv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/ram/goenv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ram/goenv/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/ram/goenv/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/ram/goenv/lib/python3.7/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/home/ram/goenv/lib/python3.7/site-packages/rest_framework/views.py", line 462, in handle_exception response = exception_handler(exc, context) File "/home/ram/gomech/crapp/crapp/handlers/exception.py", line 10, in cr_exception_handler raise exc File "/home/ram/goenv/lib/python3.7/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/home/ram/gomech/crapp/crapp/rest_api_views/orders.py", line 439, in get return AccessDeniedResponse(errorMessage= 'You are not authorised to download.') File "/home/ram/gomech/crapp/crapp/responses.py", line 20, in __init__ **kwargs TypeError: __init__() got an unexpected keyword argument 'errorMessage' -
Getting error : Unknown MySQL server host 'db' (-2) in django python for docker
i am new here in docker, i am working on django python, when i am trying to run this command, docker-compose run app sh -c "python app/manage.py migrate" I am getting error Unknown MySQL server host 'db' (-2) , can anyone please help me how to resolve this issue ? Here i have added my whole dockerfile and db connection Dockerfile FROM python:3.7 ENV PYTHONUNBUFFERED 1 RUN apt-get update && apt-get install -y --no-install-recommends \ python-dev \ default-libmysqlclient-dev \ && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* COPY requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app COPY ./ /app docker-compose.yml version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - ./:/app command: > sh -c "python app/manage.py runserver 0.0.0.0:8000" # Services db: image: mysql:5.7 #restart: no environment: # Password for root access MYSQL_ROOT_PASSWORD: '12345678' MYSQL_DATABASE: 'trail_risk_inc_backend' ports: # <Port exposed> : < MySQL Port running inside container> - '3306' expose: # Opens port 3306 on the container - '3306' # Where our data will be persisted volumes: - ./db-init:/docker-entrypoint-initdb.d settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'trail_risk_inc_backend', 'USER': 'root', 'PASSWORD': '12345678', 'HOST': 'db', # Or an IP Address that your DB is hosted … -
No file was submitted error when uploading data to Django REST API
Im using angular/typescript where I upload a form of data to my Django REST API. With the data all is correct, because I can log my whole form and I get back all my data. But when it comes to upload the data I get this error: {src: ["No file was submitted."], tag: ["This field is required."]} so somehow it does not recognize my data because Im actually submitting data. frontend code upload.service const httpOptions = { headers: new HttpHeaders({'Content-Type': 'multipart/form-data'}) }; ... uploadPost(src: File, tag: string) { return this.http.post<any>(`{this.url}/posts/`, {src, tag}, httpOptions); } post.page ngOnInit() { this.storage.get('image_data').then((imageFile) => { console.log(imageFile) this.categoryForm.patchValue({ 'image': this.storage.get('image_data') }); }); this.categoryForm = new FormGroup({ 'category': new FormControl('', Validators.compose([ Validators.maxLength(25), Validators.minLength(1), Validators.required ])), 'image': new FormControl(null), }); apiSubmit() { console.log('logged') console.log(this.f.image); this.submitted = true; if (this.categoryForm.invalid) { return; } this.isLoading = true; this.loadingEl.present(); this.uploadService.uploadPost( this.f.image, this.f.category ) .pipe(tap(x => this.loadingEl.dismiss()) ) .subscribe( data => { this.router.navigate(['one']); }, error => { this.error = error; } ); } Django: models.py class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='posts', on_delete=models.CASCADE) src = models.ImageField(blank=False, null=False, editable=False, upload_to=utils.get_file_path,) date_posted = models.DateTimeField(auto_now_add=True, editable=False) last_modified = models.DateTimeField(auto_now=True) when = models.FloatField(blank=True, null=True) lock = models.BooleanField(default=False) des = models.CharField( max_length=100, validators=[ RegexValidator( regex='^[-_a-zA-Z0-9\.]+$', message='only 1 to … -
ProcessPoolExecutor: A process in the process pool was terminated abruptly while the future was running or pending
Background: Python 3.6.5, Django 1.10 I am trying to reduce the response times using ThreadPoolExecutor and ProcessPoolExecutor to speed up my APIs. Adding sample code: from django import db db.connections.close_all() with ProcessPoolExecutor(max_workers=4) as executor: executors_list.append( executor.submit(self.get_investment_data_table, current=current) ) executors_list.append( executor.submit(self.get_scheme_wise_cashflow_sum, current=current) ) executors_list.append( executor.submit(self.get_scheme_wise_xirr, current=current) ) executors_list.append(executor.submit(self.scheme_wise_transactions)) executors_list = list(executors_list) all_investment_list = executors_list[0].result() scheme_wise_cashflow_sum = executors_list[1].result() scheme_wise_xirr = executors_list[2].result() transactions = executors_list[3].result() # club all 4 and return as response Issue: While trying out ThreadPoolExecutor and ProcessPoolExecutor for different functions, I found that Threadpool is working fine but when I am trying ProcessPoolExecutor, I am getting this error: concurrent.futures.process.BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending. The weird thing is that the api call succeeds for 2-3 times and after that it starts failing continuously. The response size is around 5 MB. All the underlying functions contain db call and at least some amount of processing. Can somebody help me out or point me in the right direction as to how to debug and fix the issue. -
How get data from other table in in serializer class
I have models class Event(models.Model): main_image = models.ImageField(upload_to='events/images', default="") event_name = models.CharField(max_length=100, default="") is_active = models.BooleanField(default=True) is_approved = models.BooleanField(default=True) created_at = models.DateTimeField(default=timezone.now) created_by = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) def __str__(self): return self.event_name and the other is class Favourite(models.Model): event = models.ForeignKey( Event, on_delete=models.CASCADE, limit_choices_to={'is_active': True}, related_name="fav_data", related_query_name="fav_data") user_token = models.TextField(blank=True) is_fav = models.BooleanField(default=True) this is a serializer class class FavSerializer(serializers.ModelSerializer): class Meta: model = Favourite fields = ['id', 'event', 'user_token', 'is_fav'] and other is class eventSerializer(serializers.ModelSerializer): additional_images = additionalImagesSerializer(many=True, read_only=True) fav_data = FavSerializer(many=True,read_only=True) class Meta: model = Event fields = ['id', 'main_image', 'event_name', 'additional_images', 'fav_data'] and my view method is class eventList(ListAPIView): serializer_class = eventSerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter] search_fields = ['event_name'] filterset_fields = ['event_name'] ordering_fields = '__all__' ordering = ['-id'] def get_queryset(self): token = self.kwargs['token'] return Event.objects.all().filter(is_active=1, is_approved=1) this give the result { "count": 12, "next": "http://192.168.0.104:8000/event/allEvents/token1/?limit=10&offset=10", "previous": null, "results": [ { "id": 16, "main_image": "http://192.168.0.104:8000/media/events/images/1569666693-6th-pakistan-mega-leather-show.jpg", "event_name": "6th Pakistan Mega leather show", "event_tag": [ 5, 6, 7 ], "additional_images": [], "fav_data": [ { "id": 6, "event": 16, "user_token": "token1", "is_fav": true }, { "id": 7, "event": 16, "user_token": "token2", "is_fav": true }, { "id": 8, "event": 16, "user_token": "token3", "is_fav": true }, { "id": 9, "event": 16, "user_token": "token4", … -
Using filter for count annotation with Djongo
Currently I'm using Django and a MongoDB configured with Djongo. These are my 2 classes: class Machine (models.Model): machine_type = models.ForeignKey(MachineType, related_name ='machine_types', on_delete = models.CASCADE) machine_customer = models.ForeignKey(Customer, related_name='machine_customers', on_delete = models.CASCADE) machine_serial_number = models.CharField(max_length = 255) # def str(self): return self.machine_serial_number class Part (models.Model): part_id = models.CharField(max_length = 255) machine_serial_number = models.ForeignKey(Machine, related_name='parts', on_delete = models.CASCADE) machining_start = models.DateTimeField() machining_end = models.DateTimeField() quality = models.CharField(max_length = 3) # def __str__(self): return self.part_id I've been trying to perform the following query to find the number of not OK parts produced on each machine. results=Machine.objects.values('machine_serial_number') .annotate(part_nok=Count('parts', filter=Q(parts__quality__icontains='NIO'))) But I keep receiving the following error message: COUNT(CASE WHEN "eda_main_part"."quality" iLIKE %(0)s THEN "eda_main_part"."id" ELSE NULL END) AS "part_nok" FROM "eda_main_machine" LEFT OUTER JOIN "eda_main_part" ON ("eda_main_machine"."id" = "eda_main_part"."machine_serial_number_id") GROUP BY "eda_main_machine"."machine_serial_number" LIMIT 21 Version: 1.2.31 Ideally I would like to receive something like: {machine1:#111222, part_nok:121, part_ok:68, ... and so on }