Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 } -
How to display part of django object model?
I'm trying to show a field of my database in Django, when user is not Superuser, given an Field like for Example "GC00 0010 0010 0000 0123 4567 890", the value should be displayed as "---7890" everywhere and This is my code : view.py: def index(request): obj = MyModel.objects.all() if request.user.is_superuser: return render(request, 'app/index.html', {'obj': obj}) else: obj = len(str(obj))-5 return render(request, 'app/index.html', {'obj': obj}) Template: {% for ele in obj %} <tr> <th scope="row">{{ ele.id }}</th> <td>{{ ele }}</td> </tr> {% endfor %} This is error: TypeError at / 'int' object is not iterable Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0 Exception Type: TypeError Exception Value: 'int' object is not iterable .... Could you please help me? Thank you in advance -
Docker compose throws error during build: Service 'postgres' failed to build: exec: \"/bin/sh\": stat /bin/sh: no such file or directory": unknown
I pulled a fresh cookiecutter django template and I want to use docker. When I do docker-compose -f local.yml build I get this error: Service 'postgres' failed to build: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"/bin/sh\": stat /bin/sh: no such file or directory": unknown Researching the problem I found out that it could be corrupted images. So I deleted all containers, images and pruned the system with: docker rm -vf $(docker ps -a -q) docker rmi -f $(docker images -a -q) docker system prune Then I also did: docker-compose -f local.yml down docker-compose -f local.yml up I restarted docker, restarted my computer.... When I list all containers and images they are all gone. Then I build it again and this confuses me, because I get: fc7181108d40: Already exists 81cfa12d39e9: Already exists 793d305ca761: Already exists 41e3ced3a2aa: Already exists a300bc9d5405: Already exists 3c6a5c3830ed: Already exists fb8c79b24338: Already exists fcda1144379f: Already exists 476a22a819cc: Downloading [===============> ] 25.23MB/82.14MB 78b36b49bb24: Download complete 6a096a28591f: Download complete c0cb89b5217b: Download complete 778f1469a309: Download complete 7c4413fcad87: Download complete So there is still something that exists? I assume something is not getting deleted. Then everything fails with: ERROR: Service 'postgres' failed to build: OCI runtime create … -
ValueError: source code string cannot contain null bytes - django
My django project was working fine but all of a sudden I got this error message when trying to runserver. Here's the complete error: C:\Users\Rahul\yantra-front\yantra_packs\yantra_packs>python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001F6DFC80438> Traceback (most recent call last): File "C:\Users\Rahul\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Rahul\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "C:\Users\Rahul\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Rahul\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Rahul\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\checks\registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Rahul\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\Rahul\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\Rahul\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Rahul\AppData\Local\Programs\Python\Python37\lib\site-packages\django\urls\resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Rahul\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Rahul\AppData\Local\Programs\Python\Python37\lib\site-packages\django\urls\resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Rahul\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Rahul\yantra-front\yantra_packs\yantra_packs\yantra_packs\urls.py", line … -
Unable to install mysqlclient using pip (Ubuntu 18.04 LTS)
While installing mysqlclient using pip3 install mysqlclient I am geting an error "Failed building wheel for mysqlclient". I tried using sudo apt-get install python3.6-dev libmysqlclient-dev but didn't work. I am using ubuntu 18.04.2 LTS and python 3.6.8. I was trying to install the mysqlclient in a virtual env. The mysql server is working fine. I used the same method to install on a local windows machine and it worked fine but i can seem to make it work on server. Any ideas on why this happening. Any suggestions will be appreciated. Error Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/d0/97/7326248ac8d5049968bf4ec708a5d3d4806e412a42e74160d7f266a3e03a/mysqlclient-1.4.6.tar.gz Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/abhishek/Django/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-cl9xqcgy/mysqlclient/setup.py'"'"'; __file__='"'"'/tmp/pip-install-cl9xqcgy/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-345d65je --python-tag cp36 cwd: /tmp/pip-install-cl9xqcgy/mysqlclient/ Complete output (31 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.6 creating build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.6/MySQLdb creating build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants … -
Most efficient way to concatenate labelled querysets in Django?
Say I have two Django models Book and Person. A Person can be an author, illustrator, reviewer, or editor for any Book item, as defined by the ManyToMany relationships below. I'm writing a view which shows each person's Books in a list, but I'd like it to be grouped by distinct Book objects annotated with their roles. I'm trying to figure out the most efficient way to: a) retrieve the list of all Books which are associated with a Person in any role, and b) construct a list of roles for the Person in each Book. Here's what I'd like to get: Book 1: My first title (author, illustrator) Book 2: My next title (reviewer) Book 3: My third thing (editor) Here's a simplified model structure: class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) class Book(models.Model): title = models.CharField(max_length=200) authors = models.ManyToManyField('person.Person', related_name='i_wrote', blank=True) illustrators = models.ManyToManyField('person.Person', related_name='i_drew', blank=True) reviewers = models.ManyToManyField('person.Person', related_name='i_reviewed', blank=True) editors = models.ManyToManyField('person.Person', related_name='i_edited', blank=True) I've tried using loops or zipped lists or the | operator, but I think that there must be a faster way to do it with annotate or aggregate, but I just can't figure it out. Any help appreciated :) Thanks! -
How to stop Django if memcached isn't working
I am looking for a way to stop Django at start up if my memcached isn't working. Is there a way or best practice ? I'm using memcached with DRF, specifically with throttling and the throttling mandatory. Thx for reading. Flave -
Is there a way to upload multiple files or folder in Django admin? [closed]
I wish to upload a folder in Django admin itself without using forms. Is it possible? I want it to be something like GitHub where people upload their projects but not using templates or anything, directly into Django admin interface. -
How to run a function multiple times and return different result python
Hello I'm having a problem I don't know if this is doable but what I wanted to do is call a function multiple times. The idea is I am generating a serial number for tickets I have a function that generates a number which is 16 in length def random_number_generator(size=16, numbers=string.digits): return ''.join(random.choice(numbers) for _ in range(size)) now if I run this function like this print(random_number_generator() * 4) it will return something like this 1234567890987654 1234567890987654 1234567890987654 1234567890987654 How do I make this to return different numbers instead of the same numbers? -
How to restrict date hierarchy to years in django administration?
I need to display some data from a table in django administration. Everything is set and working but I was wondering how I could do to restrict the date_hierarchy to years only. Not allowing to show in detail for months and date. Here's the view class HistorySummaryAdmin(admin.ModelAdmin): change_list_template = 'admin/history_summary_change_list.html' date_hierarchy = 'date_and_time' list_filter = ( 'device_type', ) def changelist_view(self, request, extra_context=None): response = super(HistorySummaryAdmin, self).changelist_view( request, extra_context=extra_context, ) try: qs = response.context_data['cl'].queryset except (AttributeError, KeyError): return response metrics = { 'views': Count("date_and_time"), } selectpart = { 'week': "CONCAT(YEAR(DATE_ADD(date_and_time, INTERVAL - WEEKDAY(date_and_time) DAY)),'-',LPAD(WEEK(DATE_ADD(date_and_time, INTERVAL - WEEKDAY(date_and_time) DAY)),2,0))", } response.context_data['summary'] = list( qs .extra(select=selectpart) .values('week') .annotate(**metrics) .order_by('-week') ) summary_over_time = qs.extra(select=selectpart).values('week').annotate(**metrics).order_by('-views') high = summary_over_time.first()['views'] low = summary_over_time.last()['views'] summary_over_time = qs.extra(select=selectpart).values('week').annotate(**metrics).order_by('week') response.context_data['summary_over_time'] = [{ 'week': x['week'], 'views': x['views'], 'pct': x['views'] * 100 / high, } for x in summary_over_time] return response And my template <div class="results"> <h2> Views over time </h2> <div class="bar-chart-graph"> <div class="bar-chart"> {% for x in summary_over_time %} <div class="bar" style="height:{{x.pct}}%"> <div class="bar-tooltip"> <p>{{x.week}}</p> <p>{{x.views | default:0 }} views</p> </div> </div> {% endfor %} </div> </div> <table> <thead> <tr> <th> <div class="text"> <a href="#">Week</a> </div> </th> <th> <div class="text"> <a href="#">Views</a> </div> </th> </tr> </thead> <tbody> {% for row … -
How to count the number of employees based on age groups in Django
I have a problem with writing a code for employee count based on age groups. I have six age groups and would love to render out the total number of employees that falls in-between those ages. For instance: Baby Boomers | 20 Employees Gen Y | 15 Employees And so on... Can someone please help me out with this? I would so much appreciate it if the code can work on both SQLite (development) and Postgres (production). Thanks -
deploying django react on digitalocean with nginx gunicorn
i have bind react build inside django. its working fine on localhost but on server its static files not working. when i run this after activating virtualenv: gunicorn --bind 64.225.24.226:8000 liveimage.wsgi its admin panel working without css: this is my nginx default config: server { listen 80; server_name 64.225.24.226; access_log off; location /media/ { alias /root/liveimage/media/; # change project_name } location /static { autoindex on; alias /root/liveimage/build; } location / { proxy_pass http://127.0.0.1; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } } my seetings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'build')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] STATICFILES_DIRS = [os.path.join(BASE_DIR, 'build/static')] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') gunicorn.service: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/root/liveimage ExecStart=/root/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ liveimage.wsgi:application [Install] WantedBy=multi-user.target my project is in /root/liveimage and virtualenv at /root/venv i dont know what going wrong -
How to save array of values in django rest framework
How to save array of values in django rest framework ,can you help to solve this problem. example: { "user":test{ "category":cat1, "subcategories":sub1 }, { "category":cat2, "subcategories":sub2 } } models.py class SavingCategoryandPreferences(models.Model): user = models.ForeignKey(User, related_name='user') category = models.ForeignKey(Category) subcategories= models.ForeignKey(SubCategory, related_name='sub', default=1) sort_order = models.IntegerField(default=0) slug = AutoSlugField(populate_from='subcategories_id', separator='', editable=True) created_time = models.DateTimeField("Created Date", auto_now_add=True) serializer.py class SavecatsubSerialize(serializers.ModelSerializer): class Meta: model = SavingCategoryandPreferences fields = ('id', 'user', 'category', 'subcategories') views.py class Mobilesavecatsub(viewsets.ModelViewSet): serializer_class = serializers.SavecatsubSerialize queryset = SavingCategoryandPreferences.objects.all() -
Is it possible to use global pip installed modules in virtual environment? [duplicate]
This question already has an answer here: How to import a globally installed package to virtualenv folder 5 answers Is it possible to use global pip installed modules in virtual environment? I mean, I don't have an internet access all the time. So I wonder, if it is possible to use globally installed modules in new created virtual environment. I have somewhere read that, instead pip install it is possible to use pip download. Please help, what I have to do, and how I have to do? -
save raw html data to postgresql database
Can anyone please help me solve this issue. I want to save raw HTML data to the Django PostgreSQL database. I am currently new to both Django and programming and i have been spending lots of time and still could solve it. Any help will be grateful. my error This is the error I get at the web browser. NameError at / name 'models' is not defined Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 2.2.8 Exception Type: NameError Exception Value: name 'models' is not defined Exception Location: D:\Django\TimeSheetProject\morabu_timesheet\views.py in create_timesheet_view, line 18 Python Executable: D:\Django\TimeSheetProject\morabu\Scripts\python.exe Python Version: 3.7.2 Python Path: ['D:\\Django\\TimeSheetProject', 'D:\\Django\\TimeSheetProject\\morabu\\Scripts\\python37.zip', 'D:\\Django\\TimeSheetProject\\morabu\\DLLs', 'D:\\Django\\TimeSheetProject\\morabu\\lib', 'D:\\Django\\TimeSheetProject\\morabu\\Scripts', 'c:\\program files\\python\\Lib', 'c:\\program files\\python\\DLLs', 'D:\\Django\\TimeSheetProject\\morabu', 'D:\\Django\\TimeSheetProject\\morabu\\lib\\site-packages'] Server time: Fri, 13 Dec 2019 16:55:22 +0900 this is the models.py file I have created. from django.db import models # Create your models here. class TimesheetDetails(models.Model): date = models.CharField(max_length = 10) day = models.CharField(max_length = 10) startTime = models.CharField(max_length =10) endTime = models.CharField(max_length =10) breakTime = models.CharField(max_length=3) normalTime = models.CharField(max_length=10) overTime = models.CharField(max_length = 10) holidayTime = models.CharField(max_length = 10) weekType = models.CharField( max_length = 10) attendance = models.CharField( max_length = 10) content = models.TextField( max_length = 10) my views.py code from . models import TimesheetDetails # … -
TypeError: hasattr(): attribute name must be string in djnago rest framework
class RemoveDependentViewSets(CustomModelViewSet): """ This view-set is used for Delete employee dependent """ http_method_names = ('delete',) queryset = EmployeeDependents.objects.filter() permission_classes = (IsAuthenticated, IsEmployeePermission) def destroy(self, request, *args, **kwargs): instance = self.get_object() dependent_del = EmployeeDependents.objects.filter(id=instance.id, created_by=request.user).first() if dependent_del: return instance.delete(dependent_del, request) return custom_error_response(status=status.HTTP_400_BAD_REQUEST, detail=ERROR_CODE['2016']) This is my views.py for deleting the dependent added by employee and employee. what am i doing wrong please tell me. what is up with this problem