Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
FileNotFoundError: [Errno 2] No such file or directory in react with docker | python manage.py collectstatic is not working inside docker container
This is my django backend Dockerfile: FROM python:3.9.5-slim ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip RUN apt-get update && apt-get install build-essential python-dev -y COPY requirements.txt /var/www/html/requirements.txt RUN pip install -r /var/www/html/requirements.txt && pip install uwsgi WORKDIR /var/www/html COPY . . EXPOSE 8000 CMD ["uwsgi", "--http", ":9090", "--wsgi-file", "IMS/wsgi.py", "--master", "--processes", "4", "--threads", "2"] And this is my react Docker file: FROM node:13.12.0-alpine WORKDIR /var/www/html COPY package.json package-lock.json ./ RUN npm install COPY . . RUN npm run build EXPOSE 3000 And here is my docker-compose.yml file version: "3.3" services: backend: build: context: ./backend command: gunicorn IMS.wsgi --bind 0.0.0.0:8000 ports: - "8000:8000" frontend: build: context: ./frontend/ims volumes: - react_build:/frontend/ims/build/static nginx: image: nginx:latest ports: - "8089:8080" volumes: - ./nginx/nginx-setup.conf:/etc/nginx/conf.d/default.conf:ro - react_build/frontend/ims/build/static depends_on: - backend - frontend volumes: react_build: -
can I call a function to set my USERNAME_FIELD = ''?
can I call a function in USERNAME_FIELD = '' to create an optional choice for login, using email or phone number? if yes how? -
Linking cart model to stripe checkout
How can I link price and items from cart Model to the Stripe checkout in Django Web Framework? I get and ValueError at /create_checkout_session when I changed default settings to the code below. When I leave it unchanged as default from the Stripe page it worked but of course it was a test example of checkout.. views.py @csrf_exempt def create_checkout_session(request): MY_DOMAIN = 'localhost:8000' cart = Cart.objects.get(order_user=request.user) try: session = stripe.checkout.Session.create( line_items=[ { 'price_data': { 'currency': 'usd', 'unit_amount': cart.total, 'product_data': { 'name': cart.order_items.title } }, 'quantity': 1, }, ], payment_method_types=[ 'card', 'p24', ], mode='payment', success_url= request.build_absolute_uri(reverse('success-page')) + '?session_id={CHECKOUT_SESSION_ID}', cancel_url= request.build_absolute_uri(reverse('cancel-page')), ) except Exception as e: return print(e) return redirect(session.url, code=303) models.py class OrderItem(models.Model): order_item = models.ForeignKey(Item, on_delete=CASCADE, null=True) quantity = models.IntegerField(default=1) class Cart(models.Model): order_user = models.OneToOneField(User, on_delete=CASCADE) order_items = models.ManyToManyField(OrderItem) ordered = models.BooleanField(default=False) total = MoneyField( default=0.00, decimal_places=2, max_digits=11, default_currency='USD') class Item(Visits, models.Model): title = models.CharField(max_length=150) price = MoneyField( decimal_places=2, default=0, default_currency='USD', max_digits=11, ) image = models.ImageField(upload_to='pictures', default='static/images/man.png') description = models.TextField(default="Item") visits = models.IntegerField(default=0) urls.py urlpatterns = [ path('create_checkout_session', views.create_checkout_session, name='checkout-page'), path('success', views.success, name='success-page'), path('cancel', views.cancel, name='cancel-page') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) HTML form to get into the checkout: <form action="{% url 'checkout-page' %}" method="GET"> <button type="submit">Checkout</button> </form> -
Why oauth2 url is not opened on my client side?
I have a problem about my google drive oauth2. I have this code : def getService(creds): service = build('drive', 'v3', credentials=creds) return service def getCredentials(): # If modifying these scopes, delete the file token.json. SCOPES = ['https://www.googleapis.com/auth/drive'] """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'code_clientXXX.json', SCOPES) creds = flow.run_local_server(port=0) print(creds) # Save the credentials for the next run with open('token.json', 'w') as token: token.write(creds.to_json()) return creds When I run in localhost, i works very well, this url is automatically opened on my browser: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=XXXX&[..............] But, when I deploy my front (angular app) and my back (django app) on a distant server, using docker. There is a problem. 1 - If my token.json is already generated : It works … -
Is editable=False required?
I am developing a model, the only actions that can be performed on an instance of it are view and delete. Moreover, all these actions must take place in the StackedInline, which is bound to the ModelAdmin class of another model. Model example: class IncludingModel(models.Model): ... class ReadAndDeleteOnlyModel(models.Model): field1 = models.TextField(verbose_name="First field", editable=False) field2 = models.TextField(verbose_name="Second field", editable=False) including_model_instance = models.ForeignKey(IncludingModel, related_name="read_and_delete_only_instances") Admin example class ReadAndDeleteOnlyModelInline(admin.StackedInline): model = ReadAndDeleteOnlyModel readonly_fields = ("field1", "field2") def has_add_permission(self, request, obj): return False @admin.register(IncludingModel) class IncludingModelAdmin(admin.ModelAdmin) inlines = (ReadAndDeleteOnlyModelInline,) Interaction with ReadAndDeleteOnlyModel instances occurs only in IncludingModelAdmin. After removing editable = False, my fields are still read-only due to the fact that I specified them in readonly_fields. This begs the question, is editable = False needed in my case? -
Conversion failed when converting from a character string to uniqueidentifier in react-redux
I am using Django and GraphQl for backend and React-redux for front end. I have implemented a save button but I get an error whenever the save action is triggered. I am trying to pick two foreign keys using their UUid's. This is the error ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Conversion failed when converting from a character string to uniqueidentifier. (8169) (SQLExecDirectW)') -
Override Wagtail delete confirmation message
I would like to override the delete message (to make it more informative, like “if you delete, you will lose 5 items belong to your account”). My idea is whenever someone deletes my “Member”, it will also delete all the items belong to that member, and the confirmation message should provide more information. I find that the confirmation message comes from a function named “confirmation_message” in wagtail.contrib.modeladmin.views, at DeleteView class. This function will provide the message for Wagtail delete's template. This is my Member class: class Member(ClusterableModel): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) phone = PhoneNumberField(blank=True) phone_2 = PhoneNumberField(blank=True) inside_scoop = models.TextField(blank=True) lifetime_member = models.BooleanField(default=False) activation_date = models.DateField(null=True, blank=True, default=timezone.now) deactivation_date = models.DateField(null=True, blank=True) points_balance = models.IntegerField(default=0) favorite_properties = models.ManyToManyField( PropertyPage, blank=True, related_name="favorite_properties" ) base_form_class = MemberFormAdmin def delete(self: object, *args: list, **kwargs: dict) -> None: PropertyPage.objects.filter(owner=self.user).delete() self.user.delete() return super(self.__class__, self).delete(*args, **kwargs) This is the default confirmation message that comes from Wagtail: this lies in wagtail -> contrib -> modeladmin -> views.py And this is the delete template: this lies in wagtail -> contrib -> modeladmin -> templates → modeladmin → delete.html This is the message for staff in admin portal: Please help me with this case, thank you. -
RelatedObjectDoesNotExist error in save method in Django
I was writing a save method in OrderCompleteStatus model. I want to make , in any order , if the order's OrderCompleteStatus.pickup is True then , for the items of that same order , and for OrderItemCompleteStatus of that item , i want to make OrderItemCompleteStatus.pickup = True. I have tried but i get RelatedObjectDoesNotExists error in line 458 . My models are : class OrderCompleteStatus(models.Model): order = models.OneToOneField('Order', on_delete=models.SET_NULL , null=True) warehouse =models.BooleanField(default=False) pickup = models.BooleanField(default=False) delivered = models.BooleanField(default=False) received_by_customer = models.BooleanField(default=False) def __str__(self): return "Order" + " " + str(self.order) class Meta: verbose_name_plural = 'Order Complete Status' def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.warehouse and self.pickup and self.delivered : self.order.complete = True self.order.save(update_fields=['complete']) if self.pickup : order = self.order orderitems = order.orderitem_set.all() for item in orderitems: item.orderitemcompletestatus.pickup = True item.orderitemcompletestatus.save(update_fields=['pickup']) class OrderItemCompleteStatus(models.Model): order_item = models.OneToOneField('OrderItem', on_delete=models.SET_NULL , null=True) seller = models.BooleanField(default=False) warehouse = models.BooleanField(default=False) pickup = models.BooleanField(default=False) delivered = models.BooleanField(default=False) received_by_customer = models.BooleanField(default=False) def __str__(self): return "Order Item " + " " + str(self.order_item) class Meta: verbose_name_plural = 'Order Item Complete Status' def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.seller and self.warehouse and self.pickup and self.delivered : self.order_item.complete = True self.order_item.save(update_fields=['complete']) class OrderItem(models.Model): product = models.ForeignKey('Product' , … -
TypeError: serve() got an unexpected keyword argument 'ducoment_root'
Internal Server Error: /media/productimg/1.png Traceback (most recent call last): File "C:\Users\sajja\Envs\fyp\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\sajja\Envs\fyp\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: serve() got an unexpected keyword argument 'ducoment_root' [01/Sep/2021 03:39:53] "GET /static/app/webfonts/fa-solid-900.woff2 HTTP/1.1" 404 1852 [01/Sep/2021 03:39:53] "GET /media/productimg/1.png HTTP/1.1" 500 60242 -
Django Serializer def validate validation error
In def validate i have unauthorized request error. When i check these conditions separately, they are okay. But when i try to use them both, it raises ValidationError. Am i doing something wrong? class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) public_profile = models.BooleanField(default=True) class UserFollowSerializer(serializers.ModelSerializer): class Meta: model = UserFollow fields = ('id',"author","profile") def validate(self, attrs): attrs = super().validate(attrs) if (attrs['author'].id == self.context['request'].user) and (attrs['profile'].public_profile == False): return attrs raise ValidationError('Unauthorized Request') -
ImportError: No module named 'django'
I am using django to make my site on server. But, I get the error. I have checked out if Django was installed. I try to add some code in wsgi.py, but I still can't fix it. import os, sys sys.path.append('<PATH_TO_MY_DJANGO_PROJECT>/ueuuop8591_project') sys.path.append('<PATH_TO_VIRTUALENV>/Lib/site-packages') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ueuuop8591.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Here is the error log [Wed Sep 01 18:28:26.950872 2021] [wsgi:error] [pid 21176] [remote 223.141.158.212:57146] mod_wsgi (pid=21176): Target WSGI script '/home/ueuuop8591/Django/ueuuop8591_project/ueuuop8591_project/wsgi.py' cannot be loaded as Python module. [Wed Sep 01 18:28:26.950969 2021] [wsgi:error] [pid 21176] [remote 223.141.158.212:57146] mod_wsgi (pid=21176): Exception occurred processing WSGI script '/home/ueuuop8591/Django/ueuuop8591_project/ueuuop8591_project/wsgi.py'. [Wed Sep 01 18:28:26.951114 2021] [wsgi:error] [pid 21176] [remote 223.141.158.212:57146] Traceback (most recent call last): [Wed Sep 01 18:28:26.951180 2021] [wsgi:error] [pid 21176] [remote 223.141.158.212:57146] File "/home/ueuuop8591/Django/ueuuop8591_project/ueuuop8591_project/wsgi.py", line 18, in <module> [Wed Sep 01 18:28:26.951190 2021] [wsgi:error] [pid 21176] [remote 223.141.158.212:57146] from django.core.wsgi import get_wsgi_application [Wed Sep 01 18:28:26.951224 2021] [wsgi:error] [pid 21176] [remote 223.141.158.212:57146] ImportError: No module named 'django' -
django pillow loading multiple images is slow
I am fetching images from an api and rendering in django app. Loading images this way is really slow. template tag def url(id): url = f'http://api.com/image?id={id}' response = requests.get(url) img = Image.open(BytesIO(response.content)) data = BytesIO() img.save(data, "PNG") data.seek(0) encoded_img_data = base64.b64encode(data.getvalue()) return encoded_img_data.decode('utf-8') html <img src="data:image/png;base64,{{row.image_md5|url}}" /> it works, but it's 1 second for loading an image. Is there a way to load all images faster this way? -
django orm filter datetime by integer of days
I have a model called with AccessDuration with two important fields are duration (int), and lab_start_date (datetime). bassed on both fields, I want to check whether the access duration is expired or yet. It's done by using model functions. class AccessDuration(models.Model): .... duration = models.PositiveIntegerField(default=30, help_text=_('In days')) lab_start_date = models.DateTimeField(verbose_name=('Start Date'), null=True) @property def expiration_date(self) -> Union[timezone.datetime, None]: if self.lab_start_date: return self.lab_start_date + timezone.timedelta(days=self.duration) return None @property def is_expired(self) -> bool: """ to check whether duration already expired or yet """ if self.expiration_date: return timezone.now() > self.expiration_date return False But, I need this filter to can be use in my django admin page. I have tried with this, but seems still doesn't working: from django.db import models from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from .models import AccessDuration class AccessListFilter(admin.SimpleListFilter): title = _('Is Expired') parameter_name = 'is_expired' def lookups(self, request, model_admin): return [ ('true', _('True')), ('false', _('False')) ] def queryset(self, request, queryset): value = self.value() expiration_date = models.ExpressionWrapper( models.F('lab_start_date') + (timezone.timedelta(days=1) * models.F('duration')), output_field=models.DateTimeField() ) if value == 'true': return queryset.annotate(expiration_date=expiration_date)\ .filter(expiration_date__lt=timezone.now()) elif value == 'false': return queryset.annotate(expiration_date=expiration_date)\ .filter(expiration_date__gte=timezone.now()) return queryset class AccessAdmin(admin.ModelAdmin): list_filter = (AccessListFilter, 'lab_start_date') admin.site.register(AccessDuration, AccessAdmin) The error I found; -
How to apply user specific permission?
I am new in Python Django.I have a question in one situation.As you see in the photos,I have an application.Firstly Users can login system and they can add new item to list.Problem is that when all users login,they are adding items to the same database.For example when 2 users login,they will see same items.I want apply specific list for each user.When each user login,they should see their own list.I know that I have to apply one to many relationship but I don't know how can I do this.I am adding screenshots of related codes. note: my item's model name is Student Application view Item database registered user for authentication from django.db import models class Student(models.Model): sid=models.CharField(max_length=7) sname=models.CharField(max_length=255) scontact=models.CharField(max_length=15) def __str__(self): return self.sname -
AttributeError: 'QuerySet' object has no attribute 'tags' when trying to save quotes and tags with ClusterableModel and ClusterTaggableManager
I am trying to save some quotes from a csv file to my django model using python manage.py shell because I could not use django-import-export to do it. I asked about it at Tags imported but relationship not imported with django-import-export but nobody answered and I could not find more things to try after googling. After reading the documentation and previous answers here about django querysets and tagging, I managed to save most of each quote but the tags are not saved. The query set does not return tags field, which causes the AttributeError. Please see shell output q: <QuerySet... below My tag model follows https://docs.wagtail.io/en/stable/reference/pages/model_recipes.html#custom-tag-models. From django-admin, the relationships are working. So the missing piece of the puzzle is saving the tags. What query should I use to locate the tags field or what method should I use to save the tags? #The script I'm trying to run in python manage.py shell import csv from quotes.models import Quote, TaggedQuote with open("test_import1.csv", "r", encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: if row["book"]: item = Quote( text=row["text"], author=row["author"], source_url=row["url"], book=row["book"], ) elif not row["book"]: item = Quote(text=row["text"], author=row["author"], source_url=row["url"]) item.save() for each in row["tags"].split(", "): each = str(each).strip("'") … -
Gunicorn erros in gunicron.service gile
I have got my gunicorn.service file which doesnt seem to be starting when i run it, I have checked my django project for erros but it seems to be running fine [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/ubuntu/env/Django ExecStart=/home/ubuntu/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/env/Django/demo.sock demo.wsgi:application> [Install] WantedBy=multi-user.target when I run systemctl status gunicorn i get the following error: ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Wed 2021-09-01 10:15:43 UTC; 9min ago Main PID: 30119 (code=exited, status=1/FAILURE) Sep 01 10:15:43 ip-172-31-32-179 gunicorn[30119]: self.stop() Sep 01 10:15:43 ip-172-31-32-179 gunicorn[30119]: File "/home/ubuntu/env/lib/python3.8/site-packages/gunicorn/arbiter.py", line 393, i> Sep 01 10:15:43 ip-172-31-32-179 gunicorn[30119]: time.sleep(0.1) Sep 01 10:15:43 ip-172-31-32-179 gunicorn[30119]: File "/home/ubuntu/env/lib/python3.8/site-packages/gunicorn/arbiter.py", line 245, i> Sep 01 10:15:43 ip-172-31-32-179 gunicorn[30119]: self.reap_workers() Sep 01 10:15:43 ip-172-31-32-179 gunicorn[30119]: File "/home/ubuntu/env/lib/python3.8/site-packages/gunicorn/arbiter.py", line 525, i> Sep 01 10:15:43 ip-172-31-32-179 gunicorn[30119]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) Sep 01 10:15:43 ip-172-31-32-179 gunicorn[30119]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Sep 01 10:15:43 ip-172-31-32-179 systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Sep 01 10:15:43 ip-172-31-32-179 systemd[1]: gunicorn.service: Failed with result 'exit-code'. lines 1-15/15 (END) I have tried looking for different fixes but not sure what i am doing wrong here or if i am … -
I'm testing my API through Postman and I'm using Django Rest Framework and I'm uploading a file and other data also
I want to upload file and other data through postman it is saving the file but it is an empty []. model.py class ServiceProjectAnswer(models.Model): project = models.ForeignKey(ServiceProject, on_delete=models.DO_NOTHING, related_name='project_answers') question = models.ForeignKey(ServiceQuestion, on_delete=models.DO_NOTHING, related_name='project_questions') answer = models.CharField(max_length=500, blank=True, null=True) class Meta: db_table = "pm_service_project_answer" verbose_name = 'service project answer' verbose_name_plural = 'service project answers' def project_files(instance, filename): #file will be uploaded to MEDIA_ROOT/epc/projects/<project_id>/filename return 'epc/projects/{0}/{1}'.format(instance.answer.project.id, filename) class AnswerAttachments(models.Model): # answer = models.ForeignKey(ServiceProjectAnswer, on_delete=models.DO_NOTHING, related_name='answer_attachments') answer = models.ForeignKey(ServiceProjectAnswer, on_delete=models.DO_NOTHING, related_name='attachement') attachement = models.FileField(upload_to=project_files, blank=True, null=True) class Meta: db_table = 'pm_answer_attachment' verbose_name = 'answer attachement' verbose_name_plural = 'answer attachements' serializer.py This is a attachment serializer class AnswerAttachmentsSerializer(serializers.ModelSerializer): class Meta: model = AnswerAttachments fields = '__all__' This is the answer serializer from where I am saving answer and attachment both class ServiceProjectAnswerSerializer(serializers.ModelSerializer): attachement = AnswerAttachmentsSerializer(many=True) def create(self, validated_data): attachement = validated_data.pop('attachement') answer = ServiceProjectAnswer.objects.create(**validated_data) attachment = AnswerAttachments.objects.create(answer=answer, attachement=attachement) return answer class Meta: model = ServiceProjectAnswer fields = ('project', 'question', 'answer', 'attachement') This is my view class ServiceProjectAnswerViewSet(viewsets.ModelViewSet): model = ServiceProjectAnswer serializer_class = ServiceProjectAnswerSerializer parser_classes = (MultiPartParser, FormParser,) This is my response in post man { "project": 1, "question": 3, "answer": "My name is vikrant patil", "attachement": [ { "id": 21, "attachement": "http://localhost:8000/media/%5B%5D", "answer": … -
django-ckeditor is not rendering in Heroku
I am using django-ckeditor == 6.1.0 for my django app and its working fine when I am running it locally. But after deploying it on heroku its not rendering and I am getting only the usual django form. Am I missing something? -
'list' object has no attribute 'all'
I am building a Book Blog App and I am trying to get cleaned_data in creation form and I am implementing a feature in which "User can add multiple books (like tags) in blogpost which are saved in another model" And If any of book name (Book Tag) mentioned in the form not in the Book List than It will show error "You cannot create a new book name" So I made an if else statement to check if typed book name is in existing book in Book Model BUT Than it worked perfectly BUT The Problem occurred When someone types 3 book names and one of them book name is in saved book name than , it will not see other book names which are not saved (It is saving the post), So it will not show error So I think I would access all the mentioned book names mentioned in form by .all() method ( So it will check if any of book name is not in the existing names) but this error is keep showing. 'list' object has no attribute 'all' What I am trying to do :- I am trying to check all the mentioned names … -
Why the django run command "python3 manage.py runserver" does not execute in docker-compose?
What Is The Problem? I have a Dockerfile, docker-compose.yml and a run.sh script that runs my django server with so many configurations that work just fine and everything is tested but... the server does not run at the end on python3 manage.py runserver 127.0.0.1:80 command inside run.sh bash script. I searched everywhere but didn't find any solution at all. If someone can guide me what the problem is, I would be so thankful because I literally lost two days of my life in the process of running a simple django server with docker-compose. Included Files This is my docker-compose.yml file: version: "3.9" services: backend: build: context: . dockerfile: backend.Dockerfile restart: always image: backend:latest container_name: backend networks: - net dns: backend volumes: - /project/backup:/project/backup --name backup volumes: backup: name: "backup" networks: net: name: net driver: bridge And this is my Dockerfile which you just need to read the last CMD line at the end cause the other else commands on top of it work just fine: # This is the only latest version of alpine that actually works with uwsgi FROM python:3.8-alpine3.10 # for mysql and postgres RUN set -ex \ && apk add --update --no-cache --virtual build-deps \ make \ … -
Different url path just for one article (Django)
I need to change url path just for one chosen article. This is how it looks for all of my articles: site.com/articles/some-article I would like to create some condition just for one chosen article. site.com/chosen-article is it possible? urls.py urlpatterns = [ url(r'^articles/', include('mysite.articles.urls')), ] -
Django Background task schedule using apscheduler?
I am using apscheduler for my django project background scheduling. I set the time for trigger as hours=2. But it is always triggering after 10 seconds. Now tell me what is that interval and why it is not triggering after 2 hours. Execution of job "my_scheduled_job (trigger: interval[0:00:10], next run at: 2021-09-01 15:21:40 +06)" skipped: maximum number of running instances reached (1) from apscheduler.schedulers.background import BackgroundScheduler from .jobs import my_scheduled_job def start(): scheduler = BackgroundScheduler() scheduler.add_job(my_scheduled_job, 'interval', hours=2) scheduler.start() -
Django: defining a slugify aggregator
I'd like to define a custom aggregator which would allow me to annotate in querysets a slug, this slug being generated from the object ids from a subquery ("1-12-52-34"). Any help would be appreciated. qs = my_model.objects.annotate(id_slug=Slugify(my_subquery)) -
how can get post value with key in dajngo
how can access post values with index as key in view.py in dajngo I need split values based on same key This is my post value <QueryDict: {'csrfmiddlewaretoken': ['b5cJ9z5zqWdMrUN8wyUvpQMjt7KeEy1bfWwjzia1KajUHWfI9OvXvxtOLNcB0HLW'], 'product_id': ['3'], 'include_product_id[x_808903]': ['1'], 'index_val': ['x_808903', 'x_152554'], 'product_name[]': ['ISOPURE AMINOS-(ALPINE PUNCH-10.05 OZ)', 'SYNTHA-6 EDGE-(CHOCOLATE MILKSHAKE-48 SERVING)'], 'product_qty[x_808903]': ['10'], 'product_price[x_808903]': ['1'], 'total_amount[x_808903]': ['10'], 'include_product_id[x_152554]': ['3'], 'product_qty[x_152554]': ['2'], 'product_price[x_152554]': ['2'], 'total_amount[x_152554]': ['4'], 'submit': ['Submit']}> I am trying this way to access but its not working for index in index_val: include_product_id =request.POST['include_product_id'+[index]] product_price =request.POST['product_price'+[index]] Anyone please help me -
How to add DjangoFilterBackend in APIView of Django rest framework?
I am trying to add all CRUD operations into a single endpoint using APIVIEW in DRF, as I have heard, thats what senior developers do (all apis into a single endpoint). But in get request, I have to use a Filterbackends, pagination and also some custom filter logic. I have succeeded in adding custom pagination and the custom filter logic inside the get function but have troubled to add the Filterset_class. Here is my view: class LeadsView(APIView): permission_classes = [IsAuthenticated] def get(self, request, pk=None, *args, **kwargs): id = pk if id is not None: abc = Lead.objects.get(id=id) serializer = LeadSerializer(abc) return Response(serializer.data,status=status.HTTP_200_OK) else: source = self.request.GET.get("source", None) # lead_status = self.request.GET.get("lead_status", None) if source is not None: source_values = source.split(",") if lead_status is not None: lead_status_values = lead_status.split(",") abc = Lead.objects.filter(source__in=source_values, lead_status__in=lead_status_values) else: abc = Lead.objects.filter(source__in=source_values) paginator = CustomPagination() result_page = paginator.paginate_queryset(abc, request) serializer = LeadSerializer(result_page,many=True) elif lead_status is not None: lead_status_values = lead_status.split(",") if source is not None: source_values = source.split(",") abc = Lead.objects.filter(lead_status__in=lead_status_values, source__in=source_values) else: abc = Lead.objects.filter(lead_status__in=lead_status_values) paginator = CustomPagination() result_page = paginator.paginate_queryset(abc, request) serializer = LeadSerializer(result_page,many=True) else: abc = Lead.objects.all() paginator = CustomPagination() result_page = paginator.paginate_queryset(abc, request) serializer = LeadSerializer(result_page,many=True) # return Response(serializer.data,status=status.HTTP_200_OK) return paginator.get_paginated_response(serializer.data) def …