Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
module 'website.management.commands.updatemodels' has no attribute 'Command'
I am finding a problem while executing this code on my app 'website' using django https://i.stack.imgur.com/rr15N.jpg https://i.stack.imgur.com/LWMP6.jpg -
Working with multiprocessing and Celery tasks
I'm working on a web scraping project in Django. The goal is to scrape advertisement data from 3 websites, create each advertisement as model object, and list them in a view. I've got four scraping functions, for which I've used multiprocessing module in order to run all of them at the same time. All of these functions are ran in this function: @shared_task def run(): ad_list = [] running_tasks = [Process(target=task, args=[ad_list]) for task in [scrape_lento_flats, scrape_lento_houses, scrape_morizon, scrape_gethome]] for running_task in running_tasks: running_task.start() for running_task in running_tasks: running_task.join() return save(ad_list) and then the result is saved: @shared_task(serializer='json') def save(ad_list): for ad in ad_list: location = Location.save( name = ad['location'] ) type = OfferType.save( id = OfferType.types[0] if ad['type'] == 'for sale' else OfferType.types[1] ) category = Category.save( name = ad['type'] ) Advertisement.objects.create( title = ad['title'], description = ad['description'], price = ad['price'], source = ad['source'], url = ad['source_url'], location = location, type = type, category = category, photo_url = ad['photo_url'] ) All of these functions exist in tasks.py file, annotated with Celery's shared_task (except for two util ones, which are simply "polishing" scraped data). I've been following tutorial from https://codeburst.io/making-a-web-scraping-application-with-python-celery-and-django-23162397c0b6, however what I don't understand is that how does Celery … -
redirect_uri mismatch error django heroku app
After deploying a Django google single sign-in app on Heroku I am facing redirect_uri mismatch although I have the correct redirect URI in the google credentials. I don't know where the problem is occurring. The same thing is working perfectly in the local machine. Please help. -
TemplateDoesNotExist when the template does exist
I am receiving TemplateDoesNotExist when i am sure the template exists "TemplateDoesNotExist at /maintenance/1/update/" when just going to /maintenance/ which is the index for that app it's working fine. the template is under the appfolder templates appfolder name then the templates as in the image Here is my settings.py import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-j@g&qm&20_oct_3f*sn-7n117si&1x4+m9cjao%g_&88gtmk9&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'accounts', 'maintenance', 'mptt', 'crispy_forms', 'widget_tweaks', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'nitrofleet.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR/'templates',], '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', ], }, }, ] WSGI_APPLICATION = 'nitrofleet.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', … -
A question about the python Django framework
In the Django REST framework, if the administrator asks the user to enter answers to some questions that can be added by the administrator account, how should the models class that saves the data submitted by the user be defined when the user fills in the unfixed questions added by the administrator? -
Filter most viewed and used objects in previous week(last seven days) - django
I want to be filtering the most viewed and used objects in the previous week(last seven days) in my project. Models class Banner(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=150 , unique=True) description = RichTextField(blank=True, null=True) category = models.CharField(max_length=200) tag = models.CharField(max_length=200) image = models.ImageField(upload_to='banner-images/') updated = models.DateField(auto_now=True) created = models.DateField(auto_now_add = True) banner_users = models.ManyToManyField(User, related_name='banner_users', blank=True) slug = models.SlugField(unique=True, max_length=100) hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') def __str__(self): return self.name def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) return super(Banner, self).save(*args, **kwargs) I used the hit-count package for the viewing count mechanism and use the banner_users in the model above to track the usage of the banner Views def discoverPage(request): context = {} q = request.GET.get('q') if request.GET.get('q') != None else '' searchbar_word = request.GET.get('q') banners = Banner.objects.filter( Q(name__icontains=q) | Q(user__username__icontains=q) | Q(user__full_name__icontains=q) | Q(description__icontains=q) ) most_viewed = Banner.objects.order_by('-hit_count_generic__hits')[:6] most_used = Banner.objects.order_by('banner_users')[:6] context = {'banners':banners, 'most_viewed':most_viewed, 'most_used':most_used, 'searchbar_word':searchbar_word} return render(request, 'discover-banner.html', context) -
Config Nginx with NextJs and Django rest framework
front of my site written with .next and back of my site written with DRF(Django rest framework) how i can configure Nginx to run .next for front and Django for Back? my current Nginx conf is: server { listen 80; listen [::]:80; server_name portal.asem.com www.portal.asem.com; include snippets/letsencrypt.conf; return 301 https://$host$request_uri; } server { listen 443 ssl http2; server_name www.portal.asema.com; ssl_certificate /etc/letsencrypt/live/portal.asem.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/portal.asem.com/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/portal.asem.com/chain.pem; include snippets/ssl.conf; include snippets/letsencrypt.conf; return 301 https://portal.asem.com$request_uri; } server { listen 443 ssl http2; server_name portal.asem.com; ssl_certificate /etc/letsencrypt/live/portal.asem.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/portal.asem.com/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/portal.asem.com/chain.pem; include snippets/ssl.conf; include snippets/letsencrypt.conf; error_page 404 /custom_404.html; location = /custom_404.html { root /usr/share/nginx/html; internal; } location /STATIC/ { root /home/.../asem/static; } location /MEDIA/ { root /home/.../asem; } location / { proxy_pass http://localhost:3000; try_files $uri /index.html =404; } location /admin { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /user { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } my systemd service for nextJs is: [Unit] Description=Asem Front After=syslog.target network.target [Service] Environment=NODE_PORT=3000 Type=simple User=... Group=www-data Restart=on-failure WorkingDirectory=/home/.../asem-frontend ExecStart=npm start [Install] WantedBy = multi-user.target my next.config.js is : const withPWA = require('next-pwa'); const settings = { env: { API_URL : 'http://portal.asem.com/' }, devIndicators: { autoPrerender: false, }, pwa: { dest: 'public', }, }; module.exports = process.env.NODE_ENV === 'development' ? settings … -
Is it possible to store all inputs of login attempts in a file, in django?
I am currently building a local login page in Django (just started) and was wondering: Is it possible to store all login attempts (both succeeded and failed) in a json file for example? If it is, how? -
How to make an absolute url for pictures
models class ProductImage(models.Model): image = models.ImageField(upload_to="images", null=True, blank=True, verbose_name='Картинка') product_id = models.ForeignKey( ProductItem, related_name="product_image", on_delete=models.CASCADE, blank=True, null=True) models class Favorite(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Пользователь", related_name='favorites', null=True, blank=True) products = models.ManyToManyField(ProductItem, verbose_name='Продукты', related_name = 'favorites', null=True, blank=True) class Meta: verbose_name = "Избранное" verbose_name_plural = "Избранные" serializers class ProductItemSerializers(serializers.ModelSerializer): product_image = ProductImageSerializers(many=True, read_only=True) class Meta: model = ProductItem fields = ( "id", "title", "size", "category", "product", "description", "price", "equipment", "is_new", "bouquet_care", "specifications", "discount", "product_image", ) views class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserInfoSerializer @action(methods=['get'], detail=True) def user_favorite(self, request, *args, **kwargs): user = self.get_object() favorite = user.favorites.all() serializer = FavoriteListSerializer(favorite, many=True) return Response(serializer.data) when calling http://127.0.0.1:8000/api/v1/users/1/user_favorite/ functions in the user in the view everything is displayed but the picture becomes not clickable without http { "id": 11, "image": "/media/images/%D0%91%D0%B5%D0%B7_%D0%BD%D0%B0%D0%B7%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F_NE6Swo2.jpeg", "product_id": 3 }, { "id": 12, "image": "/media/images/%D0%91%D0%B5%D0%B7_%D0%BD%D0%B0%D0%B7%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F_j5pAcru.jpeg", "product_id": 3 }, { "id": 13, "image": "/media/images/%D0%91%D0%B5%D0%B7_%D0%BD%D0%B0%D0%B7%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F_gx72p5l.jpeg", "product_id": 3 }, but should be { "id": 11, "image": "http://127.0.0.1:8000/media/images/%D0%91%D0%B5%D0%B7_%D0%BD%D0%B0%D0%B7%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F_NE6Swo2.jpeg", "product_id": 3 }, { "id": 12, "image": "http://127.0.0.1:8000/media/images/%D0%91%D0%B5%D0%B7_%D0%BD%D0%B0%D0%B7%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F_j5pAcru.jpeg", "product_id": 3 }, { "id": 13, "image": "http://127.0.0.1:8000/media/images/%D0%91%D0%B5%D0%B7_%D0%BD%D0%B0%D0%B7%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F_gx72p5l.jpeg", "product_id": 3 }, how to rewrite ProductItemSerializer to make an absolute url, or what generally needs to be done for this -
Getting corrupt zips using Python3 ZipStream in Django
I'm using zipstream from here and have a Django view that returns a zip file of all file attachments which are all hosted on Amazon S3. But the zip files are all coming up as corrupt when I download them, that is, I can't open them. import io import zipstream s = io.BytesIO() with zipstream.ZipFile(s,"w", compression=zipstream.ZIP_DEFLATED) as zf: for file_path in file_paths: file_dir, file_name = os.path.split(file_path) zf.writestr(file_name, urllib.urlopen(file_path).read()) response = StreamingHttpResponse(s.getvalue(), content_type='application/octet-stream') response['Content-Disposition'] = 'attachment; filename={}'.format('files.zip') return response -
Static files doesn't work on heroku when using primary key in url
I have a problem, static files does not work when there is primary key in the url, problem occurs locally and on heroku. I tried many settings configs and always there was one problem or another. you can check it over this link - https://optifolio-dev.herokuapp.com/vispage/6/ from pathlib import Path import django_heroku import dj_database_url import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY ='smth' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['optifolio-dev.herokuapp.com','127.0.0.1','[*]'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'optifolio', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] ROOT_URLCONF = 'OPI.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'OPI.wsgi.application' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ … -
Best Practices for migrating python2 to python3 in django
It will be more helpful if you answer the following questions as well. Dealing with models.CharField. In python2, how the CharField value is stored in the database and how it is different from the value which is going to store in python3. -
How can I return complete object which is created with generic create views?
I'm creating an object. Only two fields are required. Rest of them are not require. The problem is after creating object. i'm only getting serialize version of those two fields. But i want to get complete object that is created.. views.py class CreateProjectAPIView(generics.CreateAPIView): """This endpoint allows for creation of a Project""" permission_classes = [IsAuthenticated,] serializer_class = serializers.ProjectSerializer def create(self, request, *args, **kwargs): request.data.update({'platform_subscriber_owner': request.user.id}) print("request.data :",request.data) serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) print("serializer.data :",serializer.data) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) models.py class Project(models.Model): platform_subscriber_owner = models.ForeignKey(User, verbose_name=_("project owner"), on_delete=models.CASCADE,null=True,blank=True) platform_subscriber_id = models.CharField(_("Project Key"), max_length=64, blank=True) platform_subscriber_entity = models.CharField(_("Project Names"), max_length=64,blank=True) platform_subscriber_secret_key = models.CharField(_("Project Secret Key"), max_length=64,blank=True) update_time = models.DateTimeField(_("Updated Time"), default = timezone.now) create_time = models.DateTimeField(_("Created Time"), default = timezone.now) postman object after creating: { "platform_subscriber_entity": "naae", "platform_subscriber_owner": 2, } expecting object : { "platform_subscriber_entity": "naae", "platform_subscriber_owner": 2, "platform_subscriber_secret_key":sdakjshdjkashdj, "platform_subscriber_id":jjaskdjskakska, "create_time":now, "update_time:null, } -
How to add left sidebar in custom django admin template
I have created one custom page for Django admin, file name is server.html {% extends "admin/base_site.html" %} {% block content %} <h1>Server management</h1> {% if status == 200 and message %} <ul class="messagelist"> <li class="success">Response status: <strong>{{ status}}</strong></li> <li class="success">{{message}}</li> {% if stdout %} <li class="info">{{stdout}}</li> {% endif %} </ul> {% elif status is not 200 and message %} <ul class="messagelist"> <li class="error">Response status: <strong>{{ status}}</strong></li> <li class="error">{{message}}</li> {% if stdout %} <li class="error">{{stdout}}</li> {% endif %} </ul> {% endif %} <form method="post" id="menu_form" novalidate=""> {% csrf_token %} <div> <fieldset class="module aligned "> <div class="form-row field-parent_menu"> <div> <label for="id_parent_menu">Server action:</label> <div class="related-widget-wrapper"> <select name="server_action" id="server_action"> <option value="" selected="">---------</option> <option value="status">Status of the Server</option> <option value="start">Start the Server</option> <option value="stop">Stop the Server</option> <option value="restart">Restart the Server</option> </select> </div> </div> </div> </fieldset> <div class="submit-row"> <input type="submit" style="float: left;" value="Submit" class="default" name="_submit"> </div> </div> </form> {% endblock %} And my base_site.html looks like this {% extends 'admin/base.html' %} {% load i18n static %} {% block title %}{% trans "My admin" %}{% endblock %} {% block branding %} <div class="3a-image-header"> <img src="{% static 'images/admin-logo.svg' %}"> </div> <div class="3a-text-header"> <h1 id="site-name">{% trans 'Admin Dashboard' %}</h1> </div> {% endblock %} {% block extrastyle %}{{ block.super }} … -
Crisp throws an error 'BoundWidget' object has no attribute 'field' when i want to submit
I am trying to do an advanced rendering on my Django crispy forms the form section of my index.html looks like this <form method = "post"> {% csrf_token %} {{ form.organization |crispy}} <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.start_date |crispy}} </div> <div class="form-group col-md-6 mb-0"> {{ form.end_date |crispy}} </div> </div> {{ form.recommend |crispy}} </form> -
Server error in django-heroku app Server Error (500)
after i developed it in heroku and change my DEBUG = False it's throws me an error i try to fix it but i can't cause i'm juniuor web devloper. is somebody can help me fix that please thank you. this is my settings.py file: STATIC_URL = '/static/' #STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIR = (os.path.join(BASE_DIR, 'static'),) STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIR = ( os.path.join(BASE_DIR, 'static'),) STATIC_URL = '/static/' MEDIA_URL ='/images/' STATICFILES_DIR = [ BASE_DIR / 'static' ] MEDIA_ROOT = BASE_DIR / 'static/images' STATIC_ROOT = BASE_DIR / 'staticfiles' this is my profile: web: gunicorn myproject.wsgi this is my logs: 2022-01-11T06:03:20.892917+00:00 heroku[web.1]: Idling 2022-01-11T06:03:20.908352+00:00 heroku[web.1]: State changed from up to down 2022-01-11T06:03:22.072179+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2022-01-11T06:03:22.169474+00:00 app[web.1]: [2022-01-11 06:03:22 +0000] [9] [INFO] Worker exiting (pid: 9) 2022-01-11T06:03:22.169649+00:00 app[web.1]: [2022-01-11 06:03:22 +0000] [10] [INFO] Worker exiting (pid: 10) 2022-01-11T06:03:22.180490+00:00 app[web.1]: [2022-01-11 06:03:22 +0000] [4] [INFO] Handling signal: term 2022-01-11T06:03:22.187455+00:00 app[web.1]: [2022-01-11 06:03:22 +0000] [4] [WARNING] Worker with pid 9 was terminated due to signal 15 2022-01-11T06:03:22.192774+00:00 app[web.1]: [2022-01-11 06:03:22 +0000] [4] [WARNING] Worker with pid 10 was terminated due to signal 15 2022-01-11T06:03:22.281450+00:00 app[web.1]: [2022-01-11 06:03:22 +0000] [4] [INFO] Shutting down: Master 2022-01-11T06:03:22.537454+00:00 heroku[web.1]: … -
Export CSV file in a bulk in Django
I'm creating a custom administration action to download a list of orders as a CSV file. I've this in my orders/admin.py: def export_to_csv(modeladmin, request, queryset): opts = modeladmin.model._meta # opts = options for order in queryset: content_disposition = f'attachment; filename=OrderID-{order.id}.csv' response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = content_disposition writer = csv.writer(response) fields = [field for field in opts.get_fields() if not field.many_to_many and not field.one_to_many] writer.writerow([field.verbose_name for field in fields]) # Write data rows for obj in queryset: data_row = [] for field in fields: value = getattr(obj, field.name) if isinstance(value, datetime.datetime): value = value.strftime('%d/%m/%Y') data_row.append(value) writer.writerow(data_row) return response However, this code doesn't download more than one csv file Even when I've selected more than one. -
Ubuntu 20.04, Django, nginx file permission error 403 -no solution in stackoverflow as of now works
I have deplloyed Django 1.8 application on ubuntu server with gunicorn Ubuntu 20.04 Django 1.8 nginx 1.18.0 Python 2.7 The media files are having following permissions # ls -l total 4 drwxrwxrwx 5 www-data www-data 4096 Apr 18 2021 media Error message I get is 2022/01/11 05:26:30 [error] 4094535#4094535: *152 open() "<full path to media>/media/cache/b3/de/b3def88cd24c122f0e1dcaf96e021ec2.jpg" failed (13: Permission denied), client: 172.68.127.176, server: server.com, request: "GET /media/cache/b3/de/b3def88cd24c122f0e1dcaf96e021ec2.jpg HTTP/1.1", host: "www.server.com", referrer: "http://www.server.com/" the permissions for files are media# ls -l cache/b3/de/b3def88cd24c122f0e1dcaf96e021ec2.jpg -rwxrwxrwx 1 www-data www-data 24008 Jul 22 23:46 cache/b3/de/b3def88cd24c122f0e1dcaf96e021ec2.jpg nginx config is server { server_name server.com www.server.com 192.175.118.100; error_log /var/log/nginx/server_error_log error; location = /favicon.ico { access_log off; log_not_found off; } client_max_body_size 250M; location /static/ { autoindex on; root /home/server/static/; } location /media { autoindex on; alias /home/server/media/media; } location / { include proxy_params; proxy_pass http://unix:/run/server_gunicorn.sock; proxy_set_header X-Forwarded-Protocol $scheme; #proxy_set_header Host $host; #proxy_set_header X-Scheme $scheme; #proxy_set_header X-SSL-Protocol $ssl_protocol; } listen 80; } We are unable to upload files due to permission error -
Django time ordering app, how to loop from database in table
I want to create app for ordering time in the schedule, the total time is divided by 15 minutes, each 15 minutes in one column. rows are defined by date, start time and period. Periods are always divisible by 15 and in minutes. data in sche_table database : id | DATE | TIME | PERIOD | ---------------------------------- 1 | 1.1.2022 | 8:00:00 | 240 | my goal is create loop in table to create row as this: DATE 8:00 8:15 8:30 8:45 ... 12:00 1.1.2022 free free free free ... [null] when Period is less then 240 generare empy <td></td> tag. Question is how generate period / 15 <td></td> tags in table and when period is less then 240 generate empty <td></td> tags becosue <th> is always from 8:00 to 12:00 code <table> <th>Date</th> <th>8:00</th> <th>8:15</th> <th>8:30</th> <th>8:45</th> <th>9:00</th> <th>9:15</th> <th>9:30</th> <th>9:45</th> <th>10:00</th> <th>10:15</th> <th>10:30</th> <th>10:45</th> <th>11:00</th> <th>11:15</th> <th>11:30</th> <th>11:45</th> <th>12:00</th> <tbody> {% for sche in sche_table %} <tr> <td>{{sche.DATE|date:'d.m.Y' }}</td> <td><a href="#">Free</a></td> </tr> {% end for %} </tbody> </table> any ideas ? -
django.db.utils.IntegrityError: UNIQUE constraint failed: account_workexperiance.id
I am getting UNIQUE UNIQUE constraint failed: account_workexperiance.id error when updating list of objects. It has been working fine so far, and I haven't done any changes to this. models.py: class TutorUser(models.Model): tutor_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='tutor') full_name = models.CharField(max_length=255, blank=True) phone_number = models.CharField(max_length=14, blank=True) class WorkExperiance(models.Model): tutor_work = models.ForeignKey(TutorUser, related_name='tutor_work', on_delete=models.CASCADE) organization = models.CharField(max_length=255, blank=True) start_year = models.IntegerField(null=True, blank=True) serializers.py: class WorkExperianceListSerializer(serializers.ListSerializer): def update(self, instance, validated_data): tutor_work_mapping = {tutor_work.id: tutor_work for tutor_work in instance} data_mapping = {item['id']: item for item in validated_data} ret = [] for tutor_work_id, data in data_mapping.items(): tutor_work = tutor_work_mapping.get(tutor_work_id, None) if tutor_work is None: ret.append(self.child.create(data)) else: ret.append(self.child.update(tutor_work, data)) for tutor_work_id, tutor_work in tutor_work_mapping.items(): if tutor_work_id not in data_mapping: tutor_work.delete() class WorkExperianceSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=False) class Meta: list_serializer_class = WorkExperianceListSerializer model = WorkExperiance fields = [ 'id', 'organization', 'start_year', ] def update(self, instance, validated_data): instance.organization = validated_data.get('organization', instance.organization) instance.start_year = validated_data.get('start_year', instance.start_year) instance.save() return instance views:py class TutorWorkExperiance(APIView): def put(self, request): tutor = TutorUser.objects.get(tutor_user__id=request.user.id) tutor_work = WorkExperiance.objects.filter(tutor_work=tutor) serializer = WorkExperianceSerializer(tutor_work, data = request.data, partial=True, many=True) if serializer.is_valid(raise_exception=True): serializer.save(tutor_work=tutor) return Response(serializer.data) It is working for create() but not updating, I think it is trying to create() only instead of update() -
Could not parse the remainder: '${profiles['user']}' from '${profiles['user']}
const data = '{{ search_user }}' const rdata = JSON.parse(data.replace(/&quot;/g, '"')) const input = document.getElementById('user-input_products') let filteredArr = [] input.addEventListener('keyup', (e)=>{ box.innerHTML = "" filterMax = (fn, c) => x => c && fn(x) && c-- filter = profiles=> profiles['full_name'].includes(e.target.value) max = 30 filteredArr = rdata.filter(filterMax(filter, max)) if (filteredArr.length > 0) { filteredArr.map(profiles=>{ box.innerHTML += `<li><a href="{% url 'user_num' ${profiles['user']} %}">${profiles['full_name']}</a></li>` }) } else { box.innerHTML = "No result found" } }) And when i want to pass id to django url inside of innerHTML it's give me this error: Could not parse the remainder: '${profiles["user"]}' from '${profiles["user"]}' How can i fix that? -
Django annotate division does't calculate float numbers correctly
I'm trying to divide numbers that are stored in database in millionth, but when the result is < 1, the decimals are lost. conditions_set.annotate( _amount_from=ExpressionWrapper(F('amount_from')/1000000, output_field=FloatField()), _amount_to=ExpressionWrapper(F('amount_to')/1000000, output_field=FloatField()), _value=ExpressionWrapper(F('value')/10000, output_field=FloatField()) ).values('_amount_from', '_amount_to', '_value').order_by('amount_from') 0 = {dict: 3} {'_amount_from': 0.0, '_amount_to': 1000.0, '_value': 0.0} 1 = {dict: 3} {'_amount_from': 1000.0, '_amount_to': 3000.0, '_value': 0.0} As the 'value' is equal to 6800, I'm expecting that the result of 6800/10000 is 0,68. But I get 0.0. -
Django: foreign key (many-to-many) show value
I have the following simple django model: class Account(models.Model): """ An account is for a team of users, or a single customer """ name = models.CharField(max_length=100, unique=True) admins = models.ManyToManyField('AccountUser', related_name='+', blank=True) metadata = models.JSONField(default=dict, blank=True) def __str__(self): return self.name @property def customers(self): """Accounts linked to this account""" return self.linked_accounts.linked_accounts.all() I am trying to loop through the account table and show the account records in a view: queryset_account = Account.objects.all() for account in queryset_account: logger.warning(account.name) logger.warning(account.admins) the account name is showing but the foreign key admins is returning none. How can I display the content of admins? -
Update multiple resource together in Django DRF
Lets say I have two models in Django: class Inventory(models.Model): created_at = models.DateTimeField(auto_now_add=True) added_by = models.ForeignKey(User, on_delete=models.SET("anonymous"), blank=True, null=True) name = models.CharField(max_length=100, unique=True) nickname = models.CharField(max_length=100, blank=True, null=True) class InventoryProperties(models.Model): key = models.CharField(max_length=100) value = models.CharField(max_length=100) order = models.IntegerField() item = models.ForeignKey(Inventory, on_delete=models.CASCADE, related_name='properties') What if I would like to add an Inventory and some properties to it from the frontend on the same page (form). Then I would have to save the Inventory item first, then save the properties. As I read in REST this should not be done with one resource (because this is a different resource, so now I have /inventory/:id/properties/): How to handle updates in a REST API? What happens if something goes wrong during saving the properties? I can't rollback easily the saved Inventory item, so I end up with a half-saved object. Also this is really hard to manage on the frontend, because if some error occurs during property saving, the frontend should not save the inventory again. -
is the django application can be not working based on the country language or timezone?
I have developed a Django application and it works perfectly in my laptop but when I delivered it to my customer in germany (the application send him 504 Gateway timeout) and when he try with another laptop also it sends him another content of the application(Exist on the same server), Help please is this reliant to the country language or what exactly am stuck on. Thanks in advance