Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Adding Random String In Static File Names
I have a Django (Wagtail CMS) website deployed using Apache WSGI. For some reason, the static files linked in the page source code is wrong. For example, the page's styling doesn't work because the page's HTML comes up as: <link rel="stylesheet" type="text/css" href="/static/css/styles.d0720c096b01.css"> The link /static/css/styles.d0720c096b01.css leads to a 404, but if I browse to /static/css/styles.css I can see my stylesheets. The random string d0720c096b01 is being added to all the static files. How do I fix this? -
DRF OpenAPI documentation omitting nested endpoints
In urls.py I specify a number of URLs. But only those with only one slash-separated "word" beyond api/ are actually included in the schema. E.g. an openapi schema generated from the code below will only document the /api/token/ endpoint. The (deprecated) corejson schema does include them. Is this because my endpoints are not OpenAPI compliant? urls.py urlpatterns = [ path("api/token/", auth_user_views.AuthUserView.as_view(), name="auth_user"), path( "api/token/refresh/", auth_user_views.AuthUserRefreshView.as_view(), name="token_refresh", ), url( r"^api/token/verify/$", jwt_views.TokenVerifyView.as_view(), name="token_verify" ), ] -
Django_filter: How to specify the fields from a Foreign Key using Multiple choice filter?
I have a database (django model) containing DNA sequences with certain informations (not relevant here) which are associated with a Foreign Key (species name)to species informations. I want to research the sequences via the species name using django_filter MultipleChoiceFilter. the problem is: the choices which appear to the users are the species id not the species name. I tried to define a custom class to only display species name however it does not change anything. Maybe I should specify something in the init() function ? Thank you for your help. Here are my models: Class Especes(models.Model): nom_espece = models.CharField(max_length=100,unique=True) famille = models.CharField(max_length=100) ordre = models.CharField(max_length=100) classe = models.CharField(max_length=100) embranchement = models.CharField(max_length=100) regne = models.CharField(max_length=100) pays = models.CharField(max_length=100) class Meta: verbose_name = 'especes' def _str_(self): return self.nom_espece class Sequences(models.Model): numero_sequence = models.IntegerField() sequences = models.CharField(max_length=1000000) gene = models.CharField(max_length=100) nombre_pdb = models.IntegerField()#check how to limit integer field ?? amorces = models.CharField(max_length=1000) espece=models.ForeignKey(Especes,on_delete=models.CASCADE,related_name='liste_sequence',default=None) auteurs = models.CharField(max_length=100) annee_publication = models.IntegerField() groupe_recherche = models.CharField(max_length=100) institut = models.CharField(max_length=100) class Meta: verbose_name = 'numero_sequence' def _str_(self): return self.gene` Here is my filters.py file: `class MyMultipleChoiceFilter(django_filters.ModelChoiceFilter): def label_from_instance(self, obj): return obj.nom_espece class SequencesFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) espece = MyMultipleChoiceFilter(queryset=Especes.objects.all(),label='Species') class Meta: model = Sequences fields … -
javascript file loading problem in a web browser, relating to mime types, context Django debug_toolbar concerning Django/debug_toolbar versions >=3.X
I have noticed, at some point last year, that the debug_toolbar is not present anymore. Now I have found the problem, but do not actually completely understand what is happening and why. The initial information is that I tried a lot of different version combinations for Django/delug_toolbar and there were no problems as the version number of both started by 2. However, the toolbar is not showing itself if a version number starts by 3. The toolbar 2.2 should work with Django version 3 or larger also. Now I have located the problem to be that toolbar.js is not loaded. There is a message in the developer tool's console: :8001/static/debug_toolbar/js/toolbar.js:1 Failed to load module script: The server responded with a non-JavaScript MIME type of "text/plain". Strict MIME type checking is enforced for module scripts per HTML spec. So I found the location of the toolbar.js under the static files folder of the debug_toolbar. The file is loaded in a template base.html (in folder env\Lib\site-packages\debug_toolbar\templates\debug_toolbar) There is a line: <script type="module" src="{% static 'debug_toolbar/js/toolbar.js' %}" async></script> I changed it to be: <script type="application/javascript" src="{% static 'debug_toolbar/js/toolbar.js' %}" async></script> And the change I made is quite obvious. But I do not understand … -
Django/HTML: Pre-populating "number" input fields with decimal values from a model
I'm writing code for editing infos about a product an user has already saved in our database. So I want to pre-populate the fields of the form with the 'old' infos. Everything works fine except for the prices that I can't get to be displayed. I understand that the problem is related to the decimals since the "weight" field (whole numbers) works fine. Here's the context in my view function (working fine, I can print the prices values on the console): context["old_title"] = selected_product.title context["old_weight"] = selected_product.weight context["old_dayprice"] = selected_product.price_day_tvac context["old_weekendprice"] = selected_product.price_weekend_tvac context["old_weekprice"] = selected_product.price_week_tvac context["old_monthprice"] = selected_product.price_month_tvac context["old_description"] = selected_product.text Here's the HTML input: <div class="col-md-3 multi-horizontal" data-for="dayprice"> <div class="form-group" data-children-count="1"> <label class="form-control-label display-7 font-weight-bold" for="website" >€ / day </label > <input type="number" class="form-control" name="dayprice" data-form-field="Dayprice" id="dayprice" placeholder="5" step="any" min="0" value= "{{ old_dayprice }}" /> <p class="font-italic font-weight-light"></p> </div> and here's the model's concerned fields: price_day_tvac = models.DecimalField(verbose_name="DAY - Medium season", default=0, max_digits=9, decimal_places=2) price_week_tvac = models.DecimalField(verbose_name="WEEK - Medium season", default=0, max_digits=9, decimal_places=2) price_weekend_tvac = models.DecimalField(verbose_name="WEEKEND - Medium season", default=0, max_digits=9, decimal_places=2 price_month_tvac = models.DecimalField(verbose_name="MONTH - Medium season", default=0, max_digits=9, decimal_places=2) I tried changing the 'steps'(do different values, 'any', removing it), placing a hard-coded value (with decimal or … -
Django-tenants error redirecting to correct tenant/schema
First, I'm not sure if it's a problem of the package itself or something that I'm doing wrong (I guess it's the second option). I followed all the instructions of documentation (here https://django-tenants.readthedocs.io/en/latest/use.html) and even tho I can't figure out what I'm doing wrong. I have a app 'costumers' which is held my tenant model. This app is on 'SHARED_APPS' right under 'django_tenants'. My app 'university' is on 'TENANT_APPS'. This app contains all the logic and it has my models.py. I managed to create tenants correctly, BUT, the problem occurs when I try to use any of my Api endpoints. Example: I created a tenant called university1 and this tenant has it's own schema on my PostgreSQL database. When I do a post request using an api (using this tenant 'university1'), django is trying to use a table which doesn't exist on my schema. I really don't know what I'm doing wrong. In my models.py (in my app 'university'), do I have to add anything there? For example class Meta: managed = False and db_table=name_of_table_on_database? This is a sample of it: from django.db import models from comum.models import * from datetime import datetime from django.utils.translation import gettext_lazy as _ from … -
Controlling access to HTTP API with Django as issuer
I have Django GraphQL deployed to AWS Lambda + API Gateway using the serverless framework. For authentication I have used the django-graphql-jwt package. It is working perfectly fine using the provided queries. I would like to move to the new API Gateway HTTP API as I only proxy traffic. I was wondering if there is any advantage of validating the provided token at the API Gateway level? If so, is there any way I can achieve that by defining django with this package as the issuer? -
Using Different Redis Database for Different Queues in Celery
I have a Django application that uses Celery with Redis broker for asynchronous task execution. Currently, the app has 3 queues (& 3 workers) that connect to a single Redis instance for communication. Here, the first two workers are prefork-based workers and the third one is a gevent-based worker. The Celery setting variables regarding the broker and backend look like this: CELERY_BROKER_URL="redis://localhost:6379/0" CELERY_RESULT_BACKEND="redis://localhost:6379/1" Since Celery uses rpush-blpop to implement the FIFO queue, I was wondering if it'd be correct or even possible to use different Redis databases for different queues like — q1 uses database .../1 and q2 uses database .../2 for messaging? This way each worker will only listen to the dedicated database for that and pick up the task from the queue with less competition. Does this even make any sense? If so, how do you implement something like this in Celery? -
Page not found (Django)
I'm making website using Python Framework of 'Django'. I have some problems with Django about entering. The page for http://127.0.0.1:8000/blog/archive/2021/1%EC%9B%94/ should be uploaded when the January link is clicked, otherwise Page not found (404) will appear. I'd like to know what's wrong and how to fix it. project/urls.py contains: """mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from bookmark.views import BookmarkListView, BookmarkDetailView urlpatterns = [ path('admin/', admin.site.urls), path('bookmark/', include('bookmark.urls')), path('blog/', include('blog.urls')), ] blog/urls.py contains: from django.urls import path, re_path from blog import views app_name='blog' urlpatterns = [ # Example: /blog/ path('', views.PostListView.as_view(), name='index'), # Example: /blog/post/ (same as /blog/) path('post/', views.PostListView.as_view(), name='post_list'), # Example: /blog/post/django-example/ re_path(r'^post/(?P<slug>[-\w]+)/$', views.PostDetailView.as_view(), name='post_detail'), # Example: /blog/archive/ path('archive/', views.PostArchiveView.as_view(), name='post_archive'), # Example: /blog/archive/2019/ path('archive/<int:year>/', views.PostYearArchiveView.as_view(), name='post_year_archive'), # Example: … -
Sentry Performance Monitoring for Django per Request
I have set up performance monitoring for Django using sentry_sdk package, by default it sends one transaction(unit of monitoring) to my server per each celery task, is there an easy way to do it for each request? In the docs, it said that this is the default behavior for flask apps. -
Image is not Editing when i select it
I am going through a Django Tutorial. I am building a feature of Image Crop in my Blog App. BUT my selected image is not Editing. Here is my Code :- views.py def edit_photo(request): if request.method == 'POST': photo_form = EditProfilePhoto(request.POST, request.FILES, instance=request.user.profile) if photo_form.is_valid(): custom_form = photo_form.save(False) custom_form.save() return redirect('/') else: photo_form = EditProfilePhoto(instance=request.user.profile) args = {} args['photo_form'] = photo_form return render(request, 'edit_photo.html' , args) models.py class Profile(models.Model): name = models.CharField(max_length=22) user = models.ForeignKey(User,on_delete=models.CASCADE) image = models.ImageField(upload_to='images') forms.py class EditProfilePhoto(forms.ModelForm): class Meta: model = Profile fields = ['image',] widgets = {'image' : forms.FileInput} base.html {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- favicon --> <link rel="shortcut icon" type="image/jpg" href="{% static 'favicon.ico' %}"/> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384- TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <!-- jquery --> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <!-- cropper --> <script src="https://cdnjs.cloudflare.com/ajax/libs/cropper/4.1.0/cropper.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropper/4.1.0/cropper.min.css"> <!-- custom css & js--> <link rel="stylesheet" href={% static 'style.css' %}> <script src={% static 'main.js' %} defer></script> <title>image cropper</title> </head> <body> <div class="container mt-3"> </div> </body> </html> <p> main.js ( File in static folder in Project Directory ) const alertBox = document.getElementById('alert-box') const imageBox = document.getElementById('image-box') const editProfilePhoto = document.getElementById('editProfilePhoto-form') … -
Heroku error: filename.whl is not a supported wheel on this platform
I know this question has been posted many a time, but I am facing this error during Heroku Deployment for my Django Project. I have placed GDAL-3.1.4-cp38-cp38-win_amd64.whl in the root directory of the project. The .whl file installs successfully locally, but the mentioned error still persists during deployment. The GDAL_LIBRARY_PATH is set as: GDAL_LIBRARY_PATH = 'env/Lib/site-packages/osgeo/gdal301.dll' GEOS_LIBRARY_PATH = 'env/Lib/site-packages/osgeo/geos_c.dll' When I try: git push heroku master I get the following error: Enumerating objects: 14, done. Counting objects: 100% (14/14), done. Delta compression using up to 4 threads Compressing objects: 100% (10/10), done. Writing objects: 100% (10/10), 24.68 MiB | 1.57 MiB/s, done. Total 10 (delta 6), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Python has released a security update! Please consider upgrading to python-3.8.7 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Requirements file has been changed, clearing cached dependencies remote: -----> Installing python-3.8.2 remote: -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 remote: ERROR: GDAL-3.1.4-cp38-cp38-win_amd64.whl is not a supported wheel on this platform. #This is the error remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: … -
Django Form does not load MultipleChoiceField data from POST request
I ve a weird issue with a MultipleChoiceField that does not return the items that are in the POST QueryDict here is the Form class TranslationLanguagesForm(forms.Form): languages = forms.MultipleChoiceField( widget=forms.SelectMultiple(attrs={"novalidate": "",}), choices=languages, required=False, ) the View is something like (shortened): class AjaxSpotlerCreateView(View): def post(self,request): # ... # some code before # translation_form = TranslationLanguagesForm( self.request.POST, prefix="translation" ) if translation_form.is_valid(): translation_languages = translation_form.cleaned_data.get( "languages" ) # # some code after # the issue is that the form is never "filled" by the data of request.POST and translation_languages receives always an empty list. ...but self.request.POST.getlist("translation-languages[]") returns the correct values It only happened on MultipleChoiceField whereas ChoiceField returns the correct value here are the POST data (you see more data than needed by the form with the issue because there are 4 forms and 1 formset in the view) : <QueryDict: {'csrfmiddlewaretoken': ['bQQzHTR4JDFZFnmO1ExlPZhqURHswXTmXA9RGC2c05pBM63ns2gnVwUnbnwGzor1'], 'transcription-language': ['en-us'], 'translation-languages[]': ['fr', 'es'], 'spotlers-TOTAL_FORMS': ['1'], 'spotlers-INITIAL_FORMS': ['1'], 'spotlers-MIN_NUM_FORMS': ['0'], 'spotlers-MAX_NUM_FORMS': ['1000'], 'spotlers-0-url': ['https://test-dev-s.storage.googleapis.com/uploads/FR/5e24512/2021/1/9fccac26/9fc37a26-2545-434f-8bd2-0afc3df839aa_full.mp4?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=storage%40funky-tower-264412.iam.gserviceaccount.com%2F20210108%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20210108T125533Z&X-Goog-Expires=3600&X-Goog-SignedHeaders=host&x-goog-signature=8e737cbc384fab5e11002cbc5e6308'], 'spotlers-0-id': ['9fc37a26-1893-434f-8bd2-0afc3df839ef'], 'spotlers-0-name': ['ultraclimb'], 'spotlers-0-duration': ['00:02:43'], 'spotlers-0-is_postedited': ['true'], 'keywords-keywords': [''], 'glossary-glossary': ['']}> -
Why my exclude filter remove different objects from the "same" django query applied to a foreign key?
The following queries and classes are simplified. The final objective is to look for the best selling products, providers, categories and other types of infos that would be useful in reports. Let's start by (trying) to find the sum of all products that have been sold, i.e, where the sales note is not None: >>> Product.objects.exclude( ... orderitem__order__salesnote__isnull=True ... ).aggregate(quantity_sum=Sum("orderitem__quantity"))["quantity_sum"] 9507578 Now, let's look for the providers: >>> Provider.objects.exclude( ... product__orderitem__order__salesnote__isnull=True ... ).aggregate(quantity_sum=Sum("product__orderitem__quantity"))["quantity_sum"] 8849003 If I remove the exclude filter, both queries returns the same amount: 9835691 Right now the db only have one order without a sales note: >>> for order in Order.objects.filter(salesnote__isnull=True): ... for item in order.orderitem_set.all(): ... print(item.product, item.quantity) ... Drum kit 3 What is causing this discrepancy? What am I doing wrong? models.py class AbstractSimplifiedModel(models.Model): name = models.CharField(max_length=150) def __str__(self): return str(self.name) class Meta: abstract = True class Provider(AbstractSimplifiedModel): pass class Category(AbstractSimplifiedModel): pass class Product(AbstractSimplifiedModel): price = models.DecimalField(max_digits=7, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) provider = models.ForeignKey(Provider, on_delete=models.CASCADE) class Store(AbstractSimplifiedModel): products = models.ManyToManyField(Product) class Customer(AbstractSimplifiedModel): pass class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) store = models.ForeignKey(Store, on_delete=models.SET_NULL, null=True) requested_at = models.DateTimeField() class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.PositiveSmallIntegerField(default=0) … -
Django FileField unable to save file
I'm currently trying to upload a file to my Django backend using the model InteractorFile, which has a FileField. This is the view I have written to do so: class FileView(APIView): parser_class = (FileUploadParser,) def post(self, request, format=None): # Get bytes from received file receivedFile = request.FILES['fileField'] my_bytes = receivedFile.file.read() f = open('./example.jpg', 'wb+') f.write(my_bytes) f.close() f = open('./example.jpg', 'rb') myFile = File(f) interactorFile = InteractorFile.objects.create(name='pepe', owner=request.user, fileField=myFile) return Response(status=status.HTTP_201_CREATED, data=FileSerializer(interactorFile).data) This is working correctly and saving the received content in a file called 'example.jpg'. However, I want to avoid creating a file and writing to it, because this is very slow. This is why I wanted to use the Django ContentFile class, given that it supposedly does the same as the File class, but can be supplied directly with bytes from the HTTP request. def post(self, request, format=None): # Get bytes from received file receivedFile = request.FILES['fileField'] my_bytes = receivedFile.file.read() myFile = ContentFile(my_bytes, name="example.jpg") interactorFile = InteractorFile.objects.create(name='pepe', owner=request.user) interactorFile.fileField.save(name="example.jpg", content=myFile) return Response(status=status.HTTP_201_CREATED, data=FileSerializer(interactorFile).data) This is saving the data in a file called 'None'. This should mean that I'm not passing the name to the FileField correctly. This has been driving me crazy and I would appreciate any help. It … -
psycopg2.errors.UndefinedTable: relation "functie" does not exist (table DOES exist)
I'm practicing on creating an API with Django and a Postgres DB. I'm trying to do a raw query (as this is a requirement) but I keep getting an error saying the table doesn't exist. I've set up an APIView for this, which for 1 table actually does work, but the same thing doesn't work for the other. Here's my code: class RetrieveEmployee(APIView): def get(self, request): data = user.objects.raw("SELECT 1 as id FROM user", []) print(data.query) serializer = serializers.EmployeeSerializer(data, many=True) return Response({"employee": serializer.data}) ^ This one does work. class RetrieveRole(APIView): def get(self, request): data = functie.objects.raw("SELECT 1 as id FROM functie", []) print(data.query) serializer = serializers.RoleSerializer(data, many=True) return Response({"role": serializer.data}) ^ This one doesn't. However, both tables 'user' and 'functie' do exist in my Postgres DB. Why does psycopg2 keep saying the relation doesn't exist? I've checked everywhere on spelling mistakes. Image: tables overview in Postgres -
Not able to get list of ManytoMany field using filter
views create = Create.objects.filter(campaign_id=campaign_id).values() print (create) saved = create.produces.filter(active=True).values() print(saved) models class Create(models.Model): user = models.ForeignKey(User,on_delete= models.CASCADE,blank=True) campaign = models.ForeignKey(Campaign,on_delete=models.CASCADE,blank=True) produces = models.ManyToManyField(Saved,blank=True) class Saved(models.Model): user = models.ForeignKey(User,on_delete= models.CASCADE,blank=True) unique_key = models.CharField(max_length=2000,default='') text = models.CharField(max_length=2000,default='') active = models.BooleanField(default=False,blank=True) How to get all saved with active=True It is giving error of saved = create.produces.filter(active=True).values() AttributeError: 'QuerySet' object has no attribute 'produces' in the output of print(create) their is no produce field -
Django : Media Images not displayed in templates
I am trying to create a blog and to display image for each post. i am trying to display user-uploaded images on a webpage. When I upload the image files using the Django admin interface (I made a model for Post images with an ImageField), the image is stored in /media/images correctly. But I can't display the image on my webpage. However, when I inspect my template with GoogleChrome, the path of my files are ok but there is a 500 error (about-us-2.jpg:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error). Media Settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'core/static'), ) Project urls.py: from django.conf.urls import include, url from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin' , admin.site.urls), path("", include("authentication.urls")), path("", include("app.urls")), ]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) App urls.py: rom django.urls import path, re_path from django.conf.urls import include, url from app import views from . import views urlpatterns = [ path('', views.index, name='home'), url(r'^blog$', views.blog_view, name ='blog'), url(r'^blog/(?P<id>[0-9]+)$', views.post_view, name ='blog_post'), re_path(r'^.*\.*', views.pages, name='pages'), ] Views.py … -
Django Rest Api, Nested Serializers, OneToOne and ManyToMany relantions
I started to creating simple pizza ordering rest api for learning purpose. Creating simple model works perfertly fine, but when i trying to use model with relantions like oneToOne or ManyToMany post method stop working. My goal is to create new Order with always new OrderCredentials(OneToOne) and use existing dishes(ManyToMany) with one request my models: class Dish(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, unique=True) ingredients = models.JSONField(blank=True, null=True) price = models.FloatField() description = models.TextField(blank=True, null=True) def get_absolute_url(self): return reverse('dish_detail', args=[self.id]) class OrderCredentials(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) surname = models.CharField(max_length=255) street = models.CharField(max_length=255) houseNumber = models.CharField(max_length=255) flatNumber = models.CharField(max_length=255) phoneNumber = models.CharField(max_length=255) email = models.CharField(max_length=255) def get_absolute_url(self): return reverse('order_credentials_detail', args=[self.id]) class Order(models.Model): id = models.AutoField(primary_key=True) realized = models.IntegerField() dishes = models.ManyToManyField(Dish) credentials = models.OneToOneField(OrderCredentials, on_delete=models.CASCADE, blank=True, null=True) def get_absolute_url(self): return reverse('order_detail', args=[self.id]) OrderSerializer: class OrderSerializer(serializers.ModelSerializer): credentials = OrderCredentialsSerializer() # dishes = DishSerializer(many=True) class Meta: model = Order fields = ('id', 'realized', 'dishes', 'credentials') def create(self, validated_data): credentials_data = validated_data.pop('credentials') dishes_data = validated_data.pop('dishes') order = Order.objects.create(**validated_data) for dish_data in dishes_data: dish = Dish.objects.get_or_create(order=order, **dish_data) order.dishes.add(dish) credentials = OrderCredentials.objects.create(order=order, **credentials_data) order.credentials = credentials print(order) return order I tried to get dishes by id like this: Dish.objects.get(id = dish_data.id) but dish_data doesn't … -
Sending asynchronous email with celery in django project
have a good day. I watched how to install celery to my django project. From start to this step there is no problem actually. My purpose is when i submit a form from my web site, that request takes too much time with sending email and submitting. I installed celery for asynchronous tasks to send email seperately. My email sending function works fine without a delay. But i want to add a delay to it. Celery logs says the task is succeeded in bla-bla seconds but i got nothing in my email. this is my celery.py file import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_project.settings') os.environ.setdefault('FORKED_BY_MULTIPROCESSING', '1') app = Celery('django_project') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') this is my views.py def kaiserdicke(request): successful_submit = check_newsletter_submission(request) if request.method == "POST": send_email_task.delay( 'Information about Kaiser&Dicke', 'Hello there!', 'info @ xn - -denkmalgeschtztelofts - kic.de', [request.POST['email']] ) … -
how to drag and drop Django ManyToManyField using sortable.js?
how can i use sortable.min.js with django ManyToManyField form save. my code drag & drop table1 to table2 is working fine but when i press submit button the data is not saved in database. Because the (articles field) is not working fine. i don't understand how can i define javaScript function to save drag and drop data using sortable.min.js. my form is not post data because articles Field is not getting the drag & drop data. please can anybody tell me how can i use sortable.min.js with django form? models.py class SetRundown(models.Model): pool_title = models.CharField(max_length=200) articles = models.ManyToManyField(Article) index.html <form action="." method="POST"> <input class="form-control name="pool_title" id="id_pool_title"> <table class="table"> <thead> <tr> <th>ID</th> <th>Story</th> </tr> </thead> <tbody id="drop" name="articles"> {% for object in form.articles.field.queryset %} <tr> <td>{{ object.id }}</td> <td><a href="">{{ object.title|slice:":30" }}</a></td> </tr> {% endfor %} </tbody> </table> <table class="table"> <thead> <tr> <th>ID</th> <th>Story</th> </tr> </thead> <tbody id="drag" name="articles"> </tbody> </table> <button type="submit" class="btn btn-success">Submit</button> </form> <script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script> script.js new Sortable(drag, { group: '#id_articles', // set both lists to same group }); new Sortable(id_articles, { group: '#id_articles', // set both lists to same group animation: 150, }); -
how can i post the data "added_by"(in model.py) in APIVIEW which has a foreignkey relationship
In my models.py i have a field called "added_by" and it has a foreignkey relationship. Now i want to post the data in the ApiView through post method and i dont have idea how can i post it. can anyone help me with this.And the added by have a foreignkey relationship with User models.py '''from django.db import models # Create your models here. class RatingRates(models.Model): Rating = models.IntegerField() class UserMovie(models.Model): Movie = models.CharField(max_length=64) Title = models.CharField(max_length=128) #rates = models.OneToOneField(RatingRates, on_delete=models.CASCADE, null=True) def __str__(self): return self.Movie class JoinModel(models.Model): Movie=models.CharField(max_length=64) Title=models.CharField(max_length=128) Rating=models.IntegerField() ''' from django.db import models from django.contrib.auth.models import User from django.core.validators import MinValueValidator, MaxValueValidator class Movie(models.Model): title = models.CharField(max_length=128) director = models.CharField(max_length=128) added_by = models.ForeignKey(User, related_name="movie", on_delete=models.CASCADE, null=True) added_at = models.DateTimeField(auto_now_add=True) # rating=models.IntegerField() class Meta: db_table = "Movie" class Rating(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE) rating = models.IntegerField(validators=[MinValueValidator(0),MaxValueValidator(5)]) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_rating') class Meta: db_table = "Rating" serializer.py class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = ['id', 'title', 'director'] class RatingSerializer(serializers.ModelSerializer): class Meta: model = Rating fields = ['id', 'movie','rating'] views.py class ListUsers(APIView): permission_classes = [IsAuthenticated] def get(self, request, format=None): movie=Movie.objects.all() serializer=MovieSerializer(movie,many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): movie_data = request.data new_movie = Movie.objects.create(title=movie_data["title"], director=movie_data[ "director"]) new_movie.save() serializer … -
Python generate a message with number between each word
I have coded something that allows me to generate a text. My message is my input and it returns me a new message with numbers instead of spaces. Here is an example : The problem is that some words like "goal" are cut at the end of the line (it's a website so the size is never the same). Is there a way to adjust the number of numbers between each word so that it displays correctly? Here is the code : def generate_grid(message): final_message = [] message_split = message.split(" ") words = [] for word in message_split: words.append(list(word)) # if I want to use letter insstead of numbers upper_case_alphabet = string.ascii_uppercase lower_case_alphabet = string.ascii_lowercase for word in words: final_message.append('<strong>') for i in range(len(word)): final_message.append(word[i].upper()) final_message.append('</strong>') random_number = random.randint(1, 3) for _ in range(random_number): random_char = random.randint(0, 9) final_message.append(str(random_char)) return mark_safe(" ".join(final_message)) -
Cannot import Javascript file in other Javascript file
For a project, I'm using Django for my backend, HTML/CSS/JS for frontend. For one HTML page, I use two JS files: dom_creator.js and console_page.js. I would like to use the functions of dom_creator in console_page, but whatever I try, I cannot find the right statement to import (and many of the ES6 import statements even make my console_page.js to stop working). I also have a module imported to my HTML (console_module.js). In that file, I have no issue importing dom_creator.js with import {function1, function2} from "./dom_creator.js" How would I be able to import functions from dom_creator in console_page.js (which is not a module)? I've tried all suggestions on Stack Overflow, but none of them seem to work. -
Earnings from websites?
My question is that I had created a dynamic website using HTML5 CSS3 Javascript Bootstrap Django sqlite3 Now my question is, I want to host the website and earn money but I don't know how to do this , what kind of technologies use for hosting these website and what is Best platform for hosting website. If i miss any kind of thing on these web development roadmap please guide me what can i do. One more thing how to host website on Google and how google paid for these.