Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does Django's ConditionalGetMiddleware play nicely with multiple servers behind a load balancer?
I read in a few places that if you're using etags you might run into issues if your app is horizontally scaled. Does Django's ConditionalGetMiddleware work out of the box if you run multiple app servers behind a load balancer? -
Removing all after specific character in Django
This is my string: Text1 - Text2 - Text2 This is the output wanted: Text1 I looked for a filter that could do this, but couldn't find it. Thanks. -
Prefilling a form field through url
I have a register form , in which when a already registered email gets entered , it shows a error message with a login link, when clicked on login link it redirects to login page, here I want to prefill the the email field with that user email. I am using django. Does anyone know how to do it? I would appreciate some help. Thank you. my login url in urls.py: path('login/', views.login, name="login") my login link in error message: <a href="login/">login</a> Please let me what to do add to the link in url to prefill it with the user email ID. -
How to write create/update statements for a multiple depth django_restframework serializer
I'm new to Django's rest_framework and have been working alongside the documentation to build out the application I'm working on. I've been stuck on how to handle serializing multiple nested levels and have run out of ideas to try. My code looks like below: models.py from django.db import models class EntityType(models.Model): entity_type_id = models.AutoField(primary_key=True) name = models.CharField(max_length=10) class Meta: managed = True class Entity(models.Model): entity_id = models.AutoField(primary_key=True) entity_type = models.ForeignKey(to=EntityType, on_delete=models.CASCADE) class Meta: managed = True class Person(models.Model): person_id = models.AutoField(primary_key=True) entity = models.ForeignKey(to=Entity, on_delete=models.CASCADE) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) date_of_birth = models.DateField() gender = models.CharField(max_length=10) class Meta: managed = True serializers.py from .models import Entity, EntityType, Person from rest_framework import serializers class EntityTypeSerializer(serializers.ModelSerializer): class Meta: model = EntityType fields = ['entity_type_id', 'name'] class EntitySerializer(serializers.ModelSerializer): entity_type = EntityTypeSerializer(many=False, read_only=False) class Meta: model = Entity fields = ['entity_id', 'entity_type'] def create(self, validated_data): entity_type_data = validated_data.pop('entity_type') entity_type, _ = EntityType.objects.get_or_create(**entity_type_data) validated_data['entity_type'] = entity_type entity = Entity.objects.create(**validated_data) return entity class PersonSerializer(serializers.ModelSerializer): entity = EntitySerializer(many=False, read_only=False) class Meta: model = Person fields = ['person_id', 'entity', 'first_name', 'last_name', 'date_of_birth', 'gender'] depth = 2 def create(self, validated_data): entity_data = validated_data.pop('entity') entity, created = Entity.objects.get_or_create(**entity_data) validated_data['entity'] = entity person = Person.objects.create(**validated_data) return person urls.py from django.contrib … -
celery : Received unregistered task of type 'celery_deploy.tasks._stocks'
When I run celery as below: celery -A bookmarks worker -l INFO it returned: [2020-11-10 23:14:21,649: ERROR/MainProcess] Received unregistered task of type 'celery_deploy.tasks._stocks'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? KeyError: 'celery_deploy.tasks._stocks' my celery.py in project bookmarks directory(where the Django project settings.py is): from __future__ import absolute_import, unicode_literals import os from celery import Celery, platforms from datetime import timedelta from . import settings BROKER_URL = 'redis://localhost:6379/0' BACKEND_URL = 'redis://localhost:6379/1' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookmarks.settings') app = Celery('bookmarks', backend=BACKEND_URL, broker=BROKER_URL) app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda : settings.INSTALLED_APPS) platforms.C_FORCE_ROOT = True app.conf.update( CELERY_ACKS_LATE = True, CELERY_ACCEPT_CONTENT = ['json'], CELERY_FORCE_EXECV = True, CELERY_CONCURRENCY = 4, CELERYD_MAX_TASKS_PER_CHILD = 10, CELERYBEAT_SCHEDULE = { 'get_stock_': { 'task': 'celery_deploy.tasks._stocks', 'schedule': timedelta(seconds=21), }, }, ) @app.task(bind = True) def debug_task(self): print('Request: {0!r}'.format(self.request)) My tasks.py in Django app celery_deploy: from __future__ import absolute_import from celery import shared_task from django.core.cache import cache from urllib.request import urlopen from bookmarks.celery import app import json import redis apibase = "https://financialmodelingprep.com/api/v3/" apikey = "[KEY]" exchange_open_day = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] json_parsed = {} CACHE_TIMEOUT = 60*60 @app.task def _stocks(): url = apibase + "quotes/nyse" + "?" + apikey response = urlopen(url) stocks_parsed … -
Django Nested Serializer Does Not Update But Inserts Data
I have a nested serializer, the create method works fine, but when I try updating an entry for one of the nested objects, it inserts that entry as a separate object rather than updating the existing nested object. What is going wrong? How could I solve this? serializers.py class LeadSerializer(serializers.ModelSerializer): language_id = LanguageSerializer(many=True) genre_id = GenreSerializer(many=True) business_id = BusinessSerializer(many=True) class Meta: model = Lead fields = "__all__" def update(self, instance, validated_data): language_data = validated_data.pop("language_id") genre_data = validated_data.pop("genre_id") business_data = validated_data.pop("business_id") if language_data: for language in language_data: if language.get("id", None) is not None: lang = Language.objects.get(id=language["id"]) if lang: lang.save(**language) else: serializers.ValidationError("No such detail") else: lang = Language.objects.create(**language) instance.language_id.add(lang) if genre_data: for genre in genre_data: if genre.get("id", None) is not None: gen = Genre.objects.get(id=genre["id"]) if gen: gen.save(**genre) else: serializers.ValidationError("No such genre") else: gen = Genre.objects.create(**genre) instance.genre_id.add(gen) if business_data: for business in business_data: if business.get("id", None) is not None: bus = Business.objects.get(id=business["id"]) if bus: bus.save(**business) else: serializers.ValidationError("No such business") else: bus = Business.objects.create(**business) instance.business_id.add(bus) instance.save() return instance views.py class DetailCreateAPIVIew(CreateAPIView): queryset = Detail.objects.all() serializer_class = DetailSerializer(partial=True) class DetailListAPIView(ListAPIView): queryset = Detail.objects.all() serializer_class = DetailSerializer class DetailRUDAPIView(RetrieveUpdateDestroyAPIView): queryset = Detail.objects.all() serializer_class = DetailSerializer(partial=True) -
Django next redirect to calling form works on localhost but not in production
I'm having an issue when I want to return to a calling form using a "next" parameter. I have a form with a list of transactions. Clicking on one of the transactions takes me to an update form. After making the update it should return back to the list of transactions. This works fine on my localhost when I run my app using "manage.py runserver". However when I deploy the code to the cloud (Pythonanywhere) clicking the submit button does not return to the calling form but keeps me on the update form. tran.html (list of transactions) - this link loads the update form with the transaction to be updated, <td><a href="{% url 'fin:tran_update' t.id request.get_full_path|urlencode%}">{{ t.omerchant }} url.py path('tran_update/<int:pk>', views.TranUpdateView.as_view(), name='tran_update'), path('tran_update/<int:pk>/<path:next>', views.TranUpdateView.as_view(), name='tran_update'), view.py class TranUpdateView(UpdateView): model = AccountTran form_class = AccountTranForm template_name = 'fin/tran_update.html' context_object_name = 'tran' def get_success_url(self, **kwargs): print('get_success_url - in TranUpdateview') if 'next' in self.kwargs: next_url = self.kwargs['next'] print('next_url:', next_url) return next_url return reverse_lazy('fin:tran') I can use filters when displaying my list view. My URL in localhost when displaying the list view looks like this: http://127.0.0.1:8000/tran/?odate__gt=2020-10-11 - when using filters or http://127.0.0.1:8000/tran/ - when not using filters The URL when displaying the update view … -
Django filter on a model with OneToOne relation
My application uses Django's built-in authentication system, but I create a Customer profile based on user first_name and last_name, and I add a phone_number field. So it looks like this: from django.db import models from django.dispatch import receiver from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=64, default='') last_name = models.CharField(max_length=64, default='') phone_number = models.CharField(max_length=13, default='') @receiver def create_customer_profile(sender, instance, created, **kwargs): if created: Customer.objects.create( user=instance, first_name=instance.first_name, last_name=instance.last_name, phone_number='', ) @receiver def save_customer_profile(sender, instance, **kwargs): instance.profile.save() def __str__(self): return self.user.username Then, somewhere in a view I want to filter Customer objects based on the user related to it. I tried this: @login_required def my_account(request): if request.user.is_authenticated: # ... customer = Customer.objects.filter(user=request.user) But I get this error: 'QuerySet' object has no attribute 'user' Django version: 3.1.3 -
How do I can redirect login, logout, register using rest_auth package?
I'm using Django rest_auth package in my project. by default when I using login, logout and register It showing me a key I want to redirect users in my home URL but I can't. I have LOGIN_REDIRECT_URL but still it shows me the key and LOGIN_REDIRECT_URL doesn't works. what should I do????? -
django how to update data without refreshing the page?
I hope my title is enough to understand what i want, i have this form in my html where the data updating in my database, <form method="POST" id="form" >{% csrf_token %} <input type="hidden" value="{{bought.id}}" name="itemID"> <div class="order-option"> <span id="quantity-field"> <input type="submit" value="-" id="down" formaction="/updatecart_index/" onclick="setQuantity('down');" > <input type="text" name="quantity" id="quantity" value="{{bought.quantity}}" onkeyup="multiplyBy()" style="width: 13%; text-align:left;" readonly> <input type="submit" value="+" id="up" formaction="/updatecart_index/" onclick="setQuantity('up');" > </span> </div> </form> this is my views.py def updatecart_index(request): item = request.POST.get("itemID") print(item) quantity = request.POST.get("quantity") product = CustomerPurchaseOrderDetail.objects.get(id=item) print("aa", CustomerPurchaseOrderDetail.objects.get(id=item)) product.quantity = quantity product.save() return HttpResponseRedirect('/') my urls.py path('updatecart_index/', customAdmin.views.updatecart_index, name='updatecart_index'), -
Deploying a Django site to GCP on App Engine, connecting App Engine to Cloud SQL
I've followed two tutorials to deploy my Django app to App Engine and to connect to the database: https://medium.com/@BennettGarner/deploying-a-django-application-to-google-app-engine-f9c91a30bd35 https://cloud.google.com/python/django/appengine I have the app "succesfully" running atm, but from print statenments I can see from the log information that as soon as the site reaches a point where it needs to query the database it times out (after 5min or so). So that suggests to me that there are some issues with the App Engine and Cloud SQL connection. I have succesfully the django site connected locally through the cloud sql proxy, and I try to deploy with the same configurations but doesn't seem to work. I suspect that the issue is one of the following: The Cloud SQL Configs should be different when running the app locally vs. in app engine (settings.py) In some examples I've seen the Main.py contain a lot of stuff around the database connection, but in neither of the tutorials do they do this, for example this is the GCP tutorial on the main.py file: https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/appengine/standard_python3/django/main.py I've checked that all App Engines inside the project have access to CLoud SQL by default, and the user also has access (i've used it for access). I'm not … -
Remove search option from django widget FilteredSelectMultiple
I am using FilteredSelectMultiple widget in my form but i want to remove the search option from the widget. forms.py study = forms.MultipleChoiceField(required=True, widget=FilteredSelectMultiple(_('Study'),False)) After rendering it's code comes out as a html paragraph with id="id_study_filter" and class="selector-filter". I tried to remove it using it's id but the following code didn't work. document.getElementById("id_study_filter").style.display = 'none'; I also tried to hide it after a timeout, still it's not working. $(document).ready(function() { $('#id_study_filter').delay(3000).hide();}); -
Posting to two related models through same api
I would like to post to related models using single api, I couldn't able to do it. I tried to override create as suggested here how to post multiple model data through one serializer in django rest api here's my models.py class Fullfillment(models.Model): candidate_name = models.CharField(max_length=60) manpower_requirement = models.ForeignKey(ManpowerRequirement, on_delete=models.CASCADE) passport_number = models.CharField(blank = True, max_length=60) joined_date = models.DateField(blank = True, null = True, default = '') remarks = models.TextField( blank = True) def __str__(self): return self.candidate_name class Meta: verbose_name_plural = "Fullfillment" class FullfillmentStatus(models.Model): fullfillment = models.ForeignKey(Fullfillment, on_delete=models.CASCADE) status = models.CharField(max_length=60) status_date = models.DateField() remarks = models.TextField( blank = True ) def __str__(self): return self.fullfillment.candidate_name class Meta: verbose_name_plural = "FullfillmentStatus" hers's seriallizers.py class FullfillmentSerializer(serializers.ModelSerializer): project = ManpowerRequirementSerializer(read_only=True,source='manpower_requirement') class Meta: model = Fullfillment fields = ('id','status','project','passport_number', 'candidate_name', 'joined_date',) class FullfillmentStatusSerializer(serializers.ModelSerializer): fullfillment_id = FullfillmentSerializer(source='fullfillment') class Meta: model = FullfillmentStatus fields = ('fullfillment_id','status','status_date','remarks',) def create(self, validated_data): data = validated_data.pop('fullfillment_id') fullfillment = Fullfillment.objects.create(**data) data_object = FullfillmentStatus.objects.create(fullfillment_id=fullfillment, **validated_data) return data_object here's my views.py class FullfillmentViewSet(viewsets.ModelViewSet): queryset = FullfillmentStatus.objects.all().order_by('id') serializer_class = FullfillmentStatusSerializer -
Why is the attach() not working in Django
I'm trying to attach a png file which is inside the "project_name/static/images/logo.png". My views.py code looks like this: def ForgotIDView(request): context = {} if request.method == 'POST': email = request.POST.get('email') try: user = User.objects.get(email=email) if user is not None: method_email = EmailMessage( 'Your ID is in the email', str(user.username), settings.EMAIL_HOST_USER, [email], ) method_email.attach_file('/images/logo.png') method_email.send(fail_silently=False) return render(request, 'accounts/id_sent.html', context) except: messages.info(request, "There is no username along with the email") context = {} return render(request, 'accounts/forgot_id.html', context) and the file directory looks like this: I'm sure that the settings.py on MEIDA_URL and stuff like that is alright, because everything else that has to do with the medias work. But only when I try to attach the files in this view, it's gives me back an error saying that: any way to solve this?? -
Cannot run python script in Django
In my Django project I have an app called 'catalog', here's the model in models.py: from django.db import models class Catalog(models.Model): brand = models.CharField(max_length=255) supplier = models.CharField(max_length=255) catalog_code = models.CharField(max_length=255, null=True, blank=True) collection = models.CharField(max_length=255) season = models.CharField(max_length=255) size_group_code = models.CharField(max_length=2) currency = models.CharField(max_length=3) target_area = models.CharField(max_length=255) I want to create one Catalog object but I don't want to do it using the admin panel or a form, so in the same app 'catalog' I've created tools.py which is just a script, it reads a csv file and create an istance of Catalog(). from catalog.models import Catalog def create_catalog(file): with open(file, 'r') as f: f = f.readlines() catalog = Catalog(# all my keyword args) catalog.save() I don't know if the script is fine but it's not important, my problem is when I try to run tools.py froom my IDE I get this error: raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I tried to run it from the shell with: exec(open('catalog/tools.py').read()) but nothing happens and no traceback. So how can I run a Python script inside of a Django project that creates objs … -
How to get text inside <a> tag in views.py django via form action?
I have a list in my function in views.py and displayed them in the html page as tags. When i click on any of the tag i need to get those text of tags in another function in views.py when the form is submitted. def index(request): vendor_data = requests.get('https://cve.circl.lu/api/browse').content vendors = json.loads(vendor_data) vendor_list = [] context = {} for i in range(len(vendors['vendor'])): vendor_list.append(vendors['vendor'][i]) paginator = Paginator(vendor_list, 50) page_number = request.GET.get('page') context['page_obj'] = paginator.get_page(page_number) return render(request,'index.html',context) index.html <form action="{% url 'appVuldb:output' %}" method="POST" id="venform"> {% csrf_token %} {%for vendor in page_obj%} <ul> <li> <a href="javascript:void(0);" class="link" name="vendor_name" onclick="document.forms['venform'].submit();">{{vendor}} </a> </li> </ul> {%endfor%} </form>` -
Error during template rendering: inconsistent use of tabs and spaces in indentation
[the running pic of django local site][ In the pic i have tried all the methods but that error is not going Can any one suggest how to solve it or some clear methods to integrate django with react. Thanks.] -
Will YouTube embedded videos work when I host the website on a public domain?
Currently, youtube embedding videos do not work on the IP address local server. Will it work if I deploy the site into production? -
Django in production not loading webfonts and javascript from Amazon S3 bucket [Cross-Origin Request Blocked]
I've installed django-cors-headers and added: CORS_ALLOWED_ORIGINS = [ "https://s3.us-east-2.amazonaws.com/", ] CORS_ORIGIN_ALLOW_ALL = False It doesn't seem to work. The problem is I can't keep bringing the site down and back up again because I only have so many Let'sEncrypt SSL certificates that I can get. I'll include the console errors please if someone can help I really need to finish this site. I've replaced my web address with 'my-site.static': GEThttps://s3.us-east-2.amazonaws.com/my-site.static/static/vendor/fade-zoom-scroll/dist/FadeJr.min.css [HTTP/1.1 403 Forbidden 430ms] GEThttps://s3.us-east-2.amazonaws.com/my-site.static/vendor/Animate.js-master/dist/animate.min.js [HTTP/1.1 403 Forbidden 251ms] GEThttps://s3.us-east-2.amazonaws.com/my-site.static/vendor/fade-zoom-scroll/dist/FadeJr.min.js [HTTP/1.1 403 Forbidden 242ms] Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://s3.us-east-2.amazonaws.com/my-site.static/vendor/fontawesome-free/webfonts/fa-solid-900.woff2. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://s3.us-east-2.amazonaws.com/my-site.static/vendor/simple-line-icons/fonts/Simple-Line-Icons.woff2?v=2.4.0. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). downloadable font: download failed (font-family: "Font Awesome 5 Free" style:normal weight:900 stretch:100 src index:1): bad URI or cross-site access not allowed source: https://s3.us-east-2.amazonaws.com/my-site.static/vendor/fontawesome-free/webfonts/fa-solid-900.woff2 GEThttps://s3.us-east-2.amazonaws.com/my-site.static/vendor/Animate.js-master/dist/animate.min.js [HTTP/1.1 403 Forbidden 47ms] downloadable font: download failed (font-family: "simple-line-icons" style:normal weight:400 stretch:100 src index:1): bad URI or cross-site access not allowed source: https://s3.us-east-2.amazonaws.com/my-site.static/vendor/simple-line-icons/fonts/Simple-Line-Icons.woff2?v=2.4.0 GEThttps://s3.us-east-2.amazonaws.com/my-site.static/vendor/fade-zoom-scroll/dist/FadeJr.min.js [HTTP/1.1 403 Forbidden 47ms] Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://s3.us-east-2.amazonaws.com/my-site.static/vendor/fontawesome-free/webfonts/fa-solid-900.woff. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). downloadable font: download failed (font-family: "Font … -
showing Django rest nested comments for products
I created nested comment for my project. I have my model and Serializer. I want to when I retrieve a product for showing product's details the product comments show as well. how do I can do this? this is my code: #models.py class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='comments') parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True,blank=True, related_name='replys') body = models.TextField() created = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user} - {self.body[:30]}' class Meta: ordering = ('-created',) #serializers.py class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ['id', 'user', 'product', 'parent', 'body', 'created'] #views.py class RetrieveProductView(generics.RetrieveAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = (permissions.AllowAny,) lookup_field = 'slug' -
How to connect web docker container (Django) to postgresql database locally (not in contaiiner)?
I am neewbie in Docker and experiment different configurations. My stack: Django/Nginx/Postgresql/Docker-compose I work locally with a Windows environnement and have to deploy apps on remote servers with Linux/Ubuntu. I try to set a configuration to be able to connect my Django app (inside a Docker container) to a Postgresql database hosted locally (http://127.0.0.1:55193 using pgAdmin 4). But when I built container, I can not access my Django app. I have no error messages (docker logs <my_container> seems to be OK). So I guess it is because my Django app do not connect to my postgresql database. Is extra_hosts parameters needed? What should be the IP? .env.prod DEBUG=0 SECRET_KEY=********************************** DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=db_prod SQL_USER=user_prod SQL_PASSWORD=user_prod SQL_HOST=db SQL_PORT=5432 DATABASE=postgres DJANGO_SETTINGS_MODULE=core.settings.prod docker-compose.prod.yml version: '3.7' services: web: build: context: ./app dockerfile: Dockerfile.prod restart: always command: gunicorn core.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles expose: - 8000 env_file: - ./.env.prod extra_hosts: - "db:127.0.0.1" nginx: build: ./nginx restart: always volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles ports: - 1338:80 depends_on: - web volumes: static_volume: media_volume: -
Why my serializer gets only one image instead of multiple (Rest Framework)
I am trying to upload multiple images with this serializer but it only accepts one image . View class ArticleView(CreateAPIView): queryset = Article.objects.all() serializer_class = ArticleViewSerializer permission_classes = (AllowAny,) parser_classes = (MultiPartParser, FormParser,) def get(self, request, format=None): queryset = Article.objects.all() serializer = ArticleViewSerializer() return Response(serializer.data) def post(self, request, *args, **kwargs): serializer = ArticleViewSerializer(data=request.data) if serializer.is_valid(): article = serializer.save() serializer = ArticleViewSerializer(article,many=True) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class ArticleImagesView(CreateAPIView): queryset = ArticleImages.objects.all() serializer_class = ArticleImagesViewSerializer permission_classes = (AllowAny,) parser_classes = (MultiPartParser, FormParser,) def get(self, request, format=None): queryset = ArticleImages.objects.all() serializer = ArticleImagesViewSerializer() return Response(serializer.data) def post(self, request, *args, **kwargs): serializer = ArticleImagesViewSerializer(data=request.data) if serializer.is_valid(): articleimages = serializer.save() serializer = ArticleImagesViewSerializer(articleimages,many=True) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializer class ArticleImagesViewSerializer(serializers.ModelSerializer): class Meta: model = ArticleImages fields = ('id','image') def create(self, validated_data): return ArticleImages.objects.create(**validated_data) class ArticleViewSerializer(serializers.ModelSerializer): imageset = ArticleImagesViewSerializer(required=False,many=True) class Meta: model = Article fields = ('imageset','id','author') def create(self, validated_data): images_data = self.context.get('view').request.FILES article = Article.objects.create(**validated_data) for image_data in images_data.values(): ArticleImages.objects.create(article=article, image=image_data) return article When i send a postman request to my django serializer,it only accepts one imageset ,like this: "imageset": [{ "id": "ec7b9665-92cd-4a8c-ba16-d62b4c24dfca", "image": "http://127.0.0.1:8000/images/images/download2_dmpBXZQ.png"}], I have also coded my def create() function such that it enters into loop,but i know … -
Django Celery: create periodic task at runtime with schedule depending on user input
I have a simple Django (v3.1) app where I receive data from a form, process it with a view and then pass it on to Celery (v4.4.7, RabbitMQ as broker). Depending on the data submitted in the form, it can be a one-time task or a periodic task. The periodic task should have a start date, end date and an intervall (e.g.: execute every 2 days at 4pm, starting now until 4 weeks). My view (shortened and renamed for illustration purposes, of course): # views.py if request.method == 'POST': form = BackupForm(request.POST) if form.is_valid(): data = ... if not form.cleaned_data['periodic']: celery_task = single_task.delay(data) else: schedule = { 'first_backup': form.cleaned_data['first_backup'], 'last_backup': form.cleaned_data['last_backup'], 'intervall_every': form.cleaned_data['intervall_every'], 'intervall_unit': form.cleaned_data['intervall_unit'], 'intervall_time': form.cleaned_data['intervall_time'], } celery_task = periodic_task.delay(data, schedule) return HttpResponseRedirect(reverse('app:index')) The single task looks like this: # tasks.py @shared_task def single_task(data: dict) -> None: asyncio.run(bulk_screen(data=data)) This works well for a single task. However, I don't know how to adapt this to create dynamic periodic tasks. My schedule data varies, depending on the users' form input. I have to create the periodic task at runtime. According to the official documentation on periodic tasks, crontab schedules is what I need: from celery.schedules import crontab app.conf.beat_schedule = { # … -
anytomany field and a foreignkey to the same model class in a django model
How can I set a manytomany field and a foreignkey to the same model class in a django model. My data structure is similar to a linking list. class cls_object(models.Model): child = models.ManyToManyField('cls_object') parent = models.ForeignKey('cls_object', on_delete=models.CASCADE, blank=True, null=True) django always tells me to change one of the two: ERRORS: cls_object: (fields.E304) Reverse accessor for 'cls_object.child' clashes with reverse accessor for 'cls_object.parent '. HINT: Add or change a related_name argument to the definition for 'cls_object.child' or 'cls_object.parent'. cls_object: (fields.E304) Reverse accessor for 'cls_object.parent' clashes with reverse accessor for 'cls_object.child'. HINT: Add or change a related_name argument to the definition for 'cls_object.parent' or 'cls_object.child'. i would like to have the opportunity to find out its parents from the respective object and have to know which objects emanate from it. A loop would not be possible (syntax, of course, yes). should one possibly do this differently? The error is sure that he does not know how to resolve it clearly in the database, but something like that should work anyway, right? am I completely wrong? -
Query multiple tables with manytomany relationship and also check against a timestamp that is in the through table
Here's a simplified version of my model class: class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) class UserProfile(models.Model): user = models.OneToOneField(User, related_name = 'profile') first_name = models.CharField(max_length=120, blank=True, null=True) last_name = models.CharField(max_length=120, blank=True, null=True) following = models.ManyToManyField(User, related_name = 'followed_by', blank=True, through='FollowingRelation') class FollowingRelation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) I'd like to query all rows from BlogPost that have been created by the session user, plus all other posts created by the users that the sessionUser is following, but has a timestamp greater than or equal to the timestamp when the session user started following. The raw sql query is something like this: select * from blog_blogpost A where A.user_id = sessionuserid or A.timestamp >= ( select timestamp from userprofile_followingrelation where user_id = A.user_id and userprofile_id = (select id from userprofile_userprofile where user_id = sessionuserid) ) I am unable to build this query in django.