Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Static files from AWS not served when they contain a Django {{variable}}
I have a Django App, deployed on Heroku with AWS S3. All static and dynamic files are being served, except when the static file name contains a Django variable. <div class="sibling" id="left"> <a href="{% url 'showtree' sibling_left_id %}"> <img src="{%static '/img/siblingsLeftFrame'%}{{no_siblings_left}}.png"> </a> </div> The generated URL should be (for example): ...amazonaws.com/img/siblingsLeftFrame02.png But looks like this: ...amazonaws.com/img/siblingsLeftFrame?X-Amz-Algortihm=AWS-4-etc.(credentials, date etc.).png Locally it works, but on Heroku/AWS I get a 403 Response. Is this a CORS problem? Here are the settings: INSTALLED_APPS = [ ... "corsheaders", ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', ... ] CORS_ALLOW_ALL_ORIGINS = True -
Module not found un uwsgi.ini when setting up Django and Docker
I'm getting a weird error when trying to run a Django server in Docker with uWSGI, for some reason the configuration file can't pick up the path to Django's wSGI file. I've run the app with just the regular "runserver" and things work fine, so I'ts not t an issue with the Django app, rather with the configuration file and how it accesses the directories in the Docker environment. I've also tried running: docker system prune -a --volumes To make sure that there isn't a problem with a redundant structure of volumes that got into the way. The error message: web_container | Traceback (most recent call last): web_container | File "/code/./docker/projectile/projectile/wsgi.py", line 16, in <module> web_container | application = get_wsgi_application() web_container | File "/usr/local/lib/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application web_container | django.setup(set_prefix=False) web_container | File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 19, in setup web_container | configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) web_container | File "/usr/local/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ web_container | self._setup(name) web_container | File "/usr/local/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup web_container | self._wrapped = Settings(settings_module) web_container | File "/usr/local/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ web_container | mod = importlib.import_module(self.SETTINGS_MODULE) web_container | File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module web_container | return _bootstrap._gcd_import(name[level:], package, level) web_container | ModuleNotFoundError: No module named … -
Django and DRF - checks for constraint before ID
In my Django project I use DRF. One of my models, Type, has a constraint; the name field should be unique. Another model, Project, relation to Type; a project always has a type. The serializer for Project has another relationship that I'd like to write in. For this purpose, ProjectSerializer implements WritableNestedModelSerializer from this package. Here's the problem: when making a new Project, one shouldn't also (be able to) create a new Type at the same time. However, it seems that Django does check if this would be allowed. This leads to an error, because when sending a Project object in a POST, it checks if the Type object given is allowed to be created before checking if it contains and ID field, indicating that it's using an already existing type. Because of this, I get an error that says the name field for the Type already exists, and I can't create the new project. How do I indicate that this isn't what I want? I could just remove the constraint on the name field in Type, but I do kind of want it there. Here is relevant code: class ProjectType(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50, unique=True) is_active = … -
Django webpack Loader / webpack5 / vue3 cannot render main.js in production
I am trying to deploy my simple application with Django 3 backend and Vue 3 frontend. I am using webpack-loader and webpack5 but i am not able to get main.js file produced in vue3 by webpack. in Django settings CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ("http://localhost:8080",) WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, 'BUNDLE_DIR_NAME': 'dist/', # must end with slash 'STATS_FILE': '/home/ytsejam/public_html/medtourism/medtourism/frontend/webpack-stats.json', 'POLL_INTERVAL': 0.1, 'TIMEOUT': None, 'IGNORE': [r'.+\.hot-update.js', r'.+\.map'], 'LOADER_CLASS': 'webpack_loader.loader.WebpackLoader', } } in webpack.config.json: module.exports = (env = {}) => { return { mode: 'production', devtool: 'source-map', entry: path.resolve(__dirname, './src/main.ts'), output: { path: path.resolve(__dirname, './dist/'), filename: "main.js", clean: true }, module: { rules: [ ... ] }, resolve: { ... }, plugins: [ new VueLoaderPlugin(), new BundleTracker({ filename: './webpack-stats.json', publicPath: 'http://localhost:8080/' }), new HtmlWebpackPlugin({ title: 'Production', }), ], devServer: { headers: { "Access-Control-Allow-Origin":"\*" }, hot: true, https: true, client: { overlay: true, }, } }; } In developer tools the request response is: Request URL: http://localhost:8080/main.js Referrer Policy: no-referrer-when-downgrade I have read all the documents, could not find a solution. can you help me ? Thanks -
can we get prefetch_related result in same queryset?
I don't want to query again from Model_B, can I get that result from same queryset? queryset = Model_A.objects.prefetch_related('Model_B') -
How to optimize creation of huge amount of objects in Django Models
I am trying to read a csv of 200k data and create Django models and save them using bulk_create but the model creations code (i.e. users_list.append(User(phone_number=phone_number) ) is taking too much time to create all the models, is there anyway to make it fast. -
File get closed once rest api return response
I am using threading to upload multiple files on S3 server but I am getting error I/o operation on closed file after my API returns the response, I don't want my API to wait for files to upload, I want to know why the file gets closed once it returns the response import threading class NewClass(APIView): def post(self, request): # doing_something threading.Thread(target=uploadDocs, args=(docList)).start() #docList eg. list of <InMemoryUploadedFile: file-sample_100kB.doc (application/msword)> return response({'status':True}) def uploadDocs(docList): for file in docList: print(file.closed) #prints false # suppose now api returns the response print(file.closed) #prints true S3_upload_doc(file) #fails to upload gives me error I/o operation on closed file -
List from django view past to template is not showing any elements
I have a problem in Django. I made the following view passing a list of errors and a length of the error list. The list of errors consists of strings. Output from printing it before passing it can be seen below. In my template I have the following code. But for some reason, the ordered list has no instances when rendering the page. I'm probably doing something wrong but cannot seem to figure out what. Any help would be really appreciated! -
How can I solve Django Heroku Deploy Issue?
I am trying to deploy my application on Heroku. Previously I tried with another application and it worked perfectly. But now it showing me an application error. I tried heroku logs --tail --app <my_app> and It shows my all log. This is my application Logs 2021-12-02T10:06:41.545537+00:00 app[web.1]: [2021-12-02 10:06:41 +0000] [9] [INFO] Worker exiting (pid: 9) 2021-12-02T10:06:41.724277+00:00 app[web.1]: [2021-12-02 10:06:41 +0000] [4] [WARNING] Worker with pid 9 was terminated due to signal 15 2021-12-02T10:06:41.738864+00:00 app[web.1]: [2021-12-02 10:06:41 +0000] [4] [INFO] Shutting down: Master 2021-12-02T10:06:41.738922+00:00 app[web.1]: [2021-12-02 10:06:41 +0000] [4] [INFO] Reason: Worker failed to boot. 2021-12-02T10:06:41.992312+00:00 heroku[web.1]: Process exited with status 3 2021-12-02T10:06:42.068312+00:00 heroku[web.1]: State changed from up to crashed 2021-12-02T10:06:45.375408+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=lproperty.herokuapp.com request_id=6e428a90-ba38-4d3f-8b0a-a469458e7dde fwd="13.213.118.202" dyno= connect= service= status=503 bytes= protocol=https 2021-12-02T10:06:45.754499+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=lproperty.herokuapp.com request_id=48a6a475-2745-45e1-844c-a6be90aef873 fwd="13.213.118.202" dyno= connect= service= status=503 bytes= protocol=https 2021-12-02T10:08:17.684518+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=lproperty.herokuapp.com request_id=f9b3efb8-2c1d-40d3-895a-5cc46994e8db fwd="13.213.118.202" dyno= connect= service= status=503 bytes= protocol=https 2021-12-02T10:08:18.110957+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=lproperty.herokuapp.com request_id=72825948-e67a-4e88-80a4-0672100e450f fwd="13.213.118.202" dyno= connect= service= status=503 bytes= protocol=https How can I solve this issue? -
How to sort data with depth-first processing pre order from django model in python?
I have a data in the database, if you convert to json the data would be like this: [{ 'id': 27, 'has_sub_topic': 1, 'name': '123123', 'xml_name': '123123', 'validated': 1, 'created_at': '2021-12-02 02:19:44.962043', 'updated_at': '2021-12-02 02:19:44.962043', 'last_editor_id': 2, 'parent_id': None, 'subject_module_level_id': 25, 'order': 1 }, { 'id': 34, 'has_sub_topic': 0, 'name': 'nosub', 'xml_name': 'nosub', 'validated': 1, 'created_at': '2021-12-02 02:19:44.962043', 'updated_at': '2021-12-02 02:19:44.962043', 'last_editor_id': 2, 'parent_id': None, 'subject_module_level_id': 25, 'order': 2 }, { 'id': 31, 'has_sub_topic': 1, 'name': 'asdasda', 'xml_name': 'asdasda', 'validated': 1, 'created_at': '2021-12-02 02:19:44.962043', 'updated_at': '2021-12-02 02:19:44.962043', 'last_editor_id': 2, 'parent_id': None, 'subject_module_level_id': 25, 'order': 3 }, { 'id': 28, 'has_sub_topic': 0, 'name': '11111', 'xml_name': '11111', 'validated': 1, 'created_at': '2021-12-02 02:19:44.962043', 'updated_at': '2021-12-02 02:19:44.962043', 'last_editor_id': 2, 'parent_id': 27, 'subject_module_level_id': 25, 'order': 1 }, { 'id': 29, 'has_sub_topic': 0, 'name': '2222', 'xml_name': '2222', 'validated': 1, 'created_at': '2021-12-02 02:19:44.962043', 'updated_at': '2021-12-02 02:19:44.962043', 'last_editor_id': 2, 'parent_id': 27, 'subject_module_level_id': 25, 'order': 2 }, { 'id': 32, 'has_sub_topic': 0, 'name': 'qweqwe', 'xml_name': 'qweqwe', 'validated': 1, 'created_at': '2021-12-02 02:19:44.962043', 'updated_at': '2021-12-02 02:19:44.962043', 'last_editor_id': 2, 'parent_id': 31, 'subject_module_level_id': 25, 'order': 1 }, { 'id': 33, 'has_sub_topic': 0, 'name': 'zxczxcz', 'xml_name': 'zxczxcz', 'validated': 1, 'created_at': '2021-12-02 02:19:44.962043', 'updated_at': '2021-12-02 02:19:44.962043', 'last_editor_id': 2, 'parent_id': 31, 'subject_module_level_id': 25, 'order': 2 }] … -
Social network failure apple signing
i have set up the apple signin in Django using SocialLoginView settings.py SOCIALACCOUNT_PROVIDERS = { "apple": { "APP": { # Your service identifier. "client_id": "com.test.web", # The Key ID (visible in the "View Key Details" page). "secret": "login with apple test", # Member ID/App ID Prefix -- you can find it below your name # at the top right corner of the page, or it’s your App ID # Prefix in your App ID. "key": "CCCDDDFAKE", "certificate_key": """-----BEGIN PRIVATE KEY----- dfdfdfddfdfjsdhfksdjfkljsdkfjsdlkfjksdlfjkdsjfkdjsfjdfkjdjfkjkdf MjqvQmfIotaSSRy/SkS9Kfagv/dkjfkjdfkjdfkjdkfjdkfjkdjfkjdfkjdfkjdf/s /Kd41Y03f1mDR8D5/dfdfdfdf+dfdfdfdfdf R3iwdyjH -----END PRIVATE KEY-----""" } } } views.py from allauth.socialaccount.providers.apple.views import AppleOAuth2Adapter,AppleOAuth2Client,AppleProvider from dj_rest_auth.registration.views import SocialLoginView as AppleLoginView class AppleLogin(AppleLoginView): adapter_class = AppleOAuth2Adapter callback_url = 'https://testssite.com/accounts/apple/login/callback' client_class = AppleOAuth2Client urls.py from django.urls import path, include from . import views urlpatterns = [ path('accounts/', include('allauth.urls')), path('login/', views.AppleLogin.as_view()), path("", views.index, name="index"), ] So far so good, if i go to mysite/accounts/apple/login i can provide my apple id. But then i get the message Social Network Login Failure Iam stuck with this, and dont know what is missing. -
How to change moderation in Django comments-xtd library
I have implemented comments xtd library in my blog however I am struggling with changing the moderation behavior. In order to see the page with comments, users must be logged in and I want to moderate all comments, also for logged-in users. For now, I see in the admin panel that is_public is by default True if the user posts a comment. How to change to False by default so the moderator has to accept the comment before publishing it? -
How to retrieve object with lookup field in Django Rest through React?
I am using the Django Rest framework as an API and React for front-end. I have everything configured to display React through Django. And everything works in development. However when using the production build I run in to an issue when trying to retrieve a single object from the database using 'slug' as the lookup field. For example I can make a call using the id field axiosInstance .get('/articles/1') which targets this view class ArticleViewSet(viewsets.ModelViewSet): ... and returns the desired article. However when I change the lookup field to 'slug' # views.py class ArticleViewSet(viewsets.ModelViewSet): lookup_field = 'slug' ... # serializers.py class ArticleSerializer(serializers.Serializer): class Meta: ... lookup_field = 'slug' and the axios call to console.log(slug) # Logs "article-1" as it should axiosInstance .get(`/articles/${slug}`) # This results in /articles/article-1 Then the index.html file is returned to me. The ArticleViewSet's retrieve method never even gets called. What's more strange is that I can still view the article using a slug by going directly to the api with, for example "localhost:8000/articles/article-1" in my browser. This returns the desired article. How can I call the retrieve method using a slug with the production build? Any help is much appreciated, thank you. -
why i am getting this kind of error Validation Error?
ERROR: raise exceptions.ValidationError( django.core.exceptions.ValidationError: ['“” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] models.py : from django.db import models from django.contrib.auth.models import User from django.db.models.deletion import CASCADE from django.utils.timezone import now class Post(models.Model): sno= models.AutoField(primary_key=True) title= models.CharField(max_length=255) author = models.CharField(max_length=13) slug = models.CharField(max_length=130) content= models.TextField() timeStamp = models.DateTimeField(blank=True, null=True ) def __str__(self): return self.title + ' by ' + self.author class BlogComment(models.Model): sno = models.AutoField(primary_key= True) comment = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True) timestamp = models.DateTimeField(null=True, blank=True) -
What is a better way to start django project?
I am using Django framework. I have tried the following four methods to start my project python manage.py. Disadvantage: If the first request get stuck, all the other requests will get stuck. gunicorn. Disadvantage: it has conflicts with asynchronous servers. (websockets) uvicorn. Disadvantage: it doesn't process some requests randomly. gunicorn+uvicorn(gunicorn myproject.asgi:application -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000). Disadvantage: the same with python manage.py -
How to display database data to your website?
This is a very simple question that got me stuck. I have 2 tables that are connected: Dealershiplistings, Dealerships. On my website I need to display the Model, Make and year of the car (Which are all stored in the DealershipListing, so i have no problem wiht this part) but I also need to print the address that is stored in the Dealerships table. Can anyone help me with this? this is what i have for my views.py def store(request): dealer_list = Dealer.objects.all() car_list = DealershipListing.objects.all() context = {'dealer_list': dealer_list, 'car_list': car_list} return render(request, 'store/store.html', context) i tried doing {{%for car in car_list%}} <h6>{{car.year}} {{car.make}} {{car.model}}</h6> {% endfor %} which works perfectly displaying those. But now how do i display the address of the dealership that is selling the car? models.py class Dealer(models.Model): dealersName = models.TextField(('DealersName')) zipcode = models.CharField(("zipcodex"), max_length = 15) zipcode_2 = models.CharField(("zipCode"), max_length = 15) state = models.CharField(("state"), max_length=5) address = models.TextField(("Address")) dealerId = models.IntegerField(("ids"), primary_key=True) def __str__(self): return self.dealersName class DealershipListing(models.Model): carID = models.IntegerField(("CarID"), primary_key=True) price = models.IntegerField(('price')) msrp = models.IntegerField(('msrp')) mileage = models.IntegerField(('mileage')) is_new = models.BooleanField(('isNew')) model = models.CharField(("Models"), max_length= 255) make = models.CharField(("Make"), max_length=255) year = models.CharField(("Year"),max_length=4) dealerID = models.ForeignKey(Dealer, models.CASCADE) def __str__(self): return … -
Dhnago Server Side Data table with DataTable.net
I am trying to implement serverside data table with Django.My Datas are going to the Clients side from server(as i have checked console.log(data)) but they are not displaying into table. If any of you guys could help me with this then i will be so much greateful. Thanks in advance ! Template: <div class="container"> <div class="row"> <div class="col-md-12"> <table id="example" class="display" style="width:100%"> <thead> <tr> <th>Uploader</th> <th>Main Category</th> <th>Sub Category</th> <th>Product Name</th> <th>Product Price</th> <th>Brand Name</th> <th>In Stock</th> <th>Product Number</th> <th>Warranty</th> <th>Uploaded</th> <th>Image</th> <!-- <th>Action</th> --> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> </div> </div> </div> Script: $(document).ready(function () { $('#example').DataTable({ responsive: true, "serverSide": true, "processing": true, "ajax": { url: '{% url "mainTableData" %}', success: function(data){ console.log(data) }, error: function (error){ console.error(error) } }, }); }); Views.py: def mainTableData(request): ajax_response = {} search_values = [] fields = ['v_user__username', 'v_main_category__cat_name', 'v_sub_category__sub_cat', 'v_product_name', 'v_product_price', 'v_brand_name', 'v_in_stock', 'v_product_number', 'v_product_warranty', 'v_created' ] for i in range(1, 10): value = request.GET.get('columns['+str(i)+'][search][value]') search_values.append(value) products = VendorProduct.objects.filter(reduce(AND, (Q(**{fields[i]+'__icontains': value} ) for i, value in enumerate(search_values)))).values_list('v_user__username', 'v_main_category__cat_name', 'v_sub_category__sub_cat', 'v_product_name', 'v_product_price', 'v_brand_name', 'v_in_stock', 'v_product_number', 'v_product_warranty', 'v_created').order_by('-id') # Add paginator paginator = Paginator(products, request.GET.get('page_length', 3)) showing_rows_in_current_draw = request.GET.get('length') products_list = … -
django: related_name of self related ForeignKey field not working | get opposite direction of self reference in template
Hej! :) I have a model to create single institutions (Institution) and can connect it to a parent institution, via parent_institution (self). So I have the institution A, which is parent to b, c, d (All themselves single institutions with an own detail view.) In the detail view of b I have the section 'parent institution' where I get A as a result, including a link to the detail view of A. <p><b>Parent institution: </b> {% if institution.parent_institution %} <a href="{% url 'stakeholders:institution_detail' institution.parent_institution.id %}"> {{institution.parent_institution}} </a> {% endif %} </p> Following this link I get to the detail view of A where I want a section with the child institutions. There should b, c, d be listed. I added a related name to the parent_institution class Institution(models.Model): name = models.CharField( verbose_name=_("Name of the institution"), max_length=200, ) parent_institution = models.ForeignKey( "self", verbose_name=_("Parent institution"), on_delete=models.SET_NULL, blank=True, null=True, help_text=_("if applicable"), related_name="child", ) normally I can follow the ForeignKey in the opposite direction via this related_name. <p><b>Child institution: </b> {{institution.child.name}} </p> but in this case this is not working and gives me 'None'. Therefor did I try: {% if institution.id == institution.all.parent_institution.id %} {{institution.name}} {% endif %} {% if institution.all.id == institution.parent_institution.id %} … -
Why doesn't this django form accept my input if it also generates the options itself?
It is a competition manager that matches the participants of a competition randomly, I call these pairs games. The game is a django model with an attribute called "ganador" to store the winner of the game. To choose the winner I use a modelform_factory called formaGanador and exclude all the attributes of the model except the "ganador" attribute. The attribute "ganador" has an option of "choices" so that the form only allows to choose one of the participants of that game and not participants of other games. Finally, when I select a participant from the list and press the submit button on the form, I receive the following response: Select a valid choice. Player A is not one of the available choices. model for games in model.py: class Juego(models.Model): torneo = models.ForeignKey(Torneo, on_delete=models.CASCADE, null=False) ronda = models.ForeignKey(Ronda, on_delete=models.CASCADE, null=False) jugadorA = models.ForeignKey(Jugador, on_delete=models.SET_NULL, null=True, related_name='jugadorA') jugadorB = models.ForeignKey(Jugador, on_delete=models.SET_NULL, null=True, related_name='jugadorB') puntuacionA = models.IntegerField(default=0) puntuacionB = models.IntegerField(default=0) ganador = models.ForeignKey(Jugador, on_delete=models.SET_NULL, null=True, default=None, choices=[('Jugador A', 'Jugador A'), ('Jugador B', 'Jugador B')]) creating the form in the views: GanadorForm = modelform_factory(Juego, exclude=['torneo', 'ronda', 'jugadorA', 'jugadorB', 'puntuacionA', 'puntuacionB']) passing and receiving the form "formaganador" from the template : def detalleTorneo(request, id): torneo … -
AWS lightsail django static files not loading using apache
I created a django project in AWS lightsail which makes use of bitnami. I have been able upload my project but when I tried accessing the from the public ip address I was given, it produced some error in my browser and the error log were Exception ignored in: <function Local.__del__ at 0x7f923d359550> Traceback (most recent call last): File "/opt/bitnami/python/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__ NameError: name 'TypeError' is not defined Exception ignored in: <function Local.__del__ at 0x7f923d359550> Traceback (most recent call last): File "/opt/bitnami/python/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__ NameError: name 'TypeError' is not defined [Thu Dec 02 08:25:01.082092 2021] [mpm_event:notice] [pid 18334:tid 140267253222272] AH00491: caught SIGTERM, shutting down [Thu Dec 02 08:25:01.259848 2021] [ssl:warn] [pid 18855:tid 140702045899648] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name [Thu Dec 02 08:25:01.269998 2021] [ssl:warn] [pid 18856:tid 140702045899648] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name [Thu Dec 02 08:25:01.270771 2021] [mpm_event:notice] [pid 18856:tid 140702045899648] AH00489: Apache/2.4.51 (Unix) OpenSSL/1.1.1d mod_wsgi/4.7.1 Python/3.8 configured -- resuming normal operations [Thu Dec 02 08:25:01.270797 2021] [core:notice] [pid 18856:tid 140702045899648] AH00094: Command line: '/opt/bitnami/apache/bin/httpd -f /opt/bitnami/apache/conf/httpd.conf' [Thu Dec 02 08:25:16.600738 2021] [authz_core:error] [pid 18858:tid 140701463279360] [client 185.220.101.170:29682] … -
TypeError at / Field 'id' expected a number but got <username>
returns username instead of user.id,i'm try to getting user.id in user_id field but getting username, the user-id field registerd as forignkey fiels of user,so it returns number only views.py def index(request): if request.user.is_authenticated: cus = User.objects.get(pk=request.user.id) print(cus) if request.method == 'POST': task = request.POST['task'] priority = request.POST['priority'] date = request.POST['date'] time = request.POST['time'] add_task = AddTodo(task=task, priority=priority, date=date, time=time, user_id=cus) add_task.save() if add_task is not None: print("task added suuccesfuly", task) else: print("task not added", task) return render(request, 'index.html') models.py class AddTodo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) task = models.CharField(max_length=100, blank=True) priority = models.IntegerField() date = models.DateField() time = models.TimeField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) exception: TypeError: Field 'id' expected a number but got <User: captainamerica123>. -
How to create dynamic queries with Django Q objects from parenthesis inside a string
I don't know if the title of the question is formed well enough. But essentially I would like to be able to do something like this from front end : (name="abc" OR name="xyz") AND (status="active" OR (status="available" AND age=30)) I want to the user to send this string. I will parse it in backend and form a query. I have looked at this answer and this but couldn't figure out how to solve the parenthesis here. I am thinking about using a stack (the way we solve infix expressions) to do this, but don't want to go that long route unless I am sure there isn't another/ready solution available. If someone can do this with that method, would be great too. -
how to create model object of a selected type of user in the registration form
how to create model object of a selected type of user in the registration form? what I want is if the selected type of user is a student then I want to automatically create it in the student model after being registered not just in the User model. how to achieve that? models.py class User(AbstractUser): is_admin = models.BooleanField('Is admin', default=False) is_teacher = models.BooleanField('Is teacher', default=False) is_student = models.BooleanField('Is student', default=False) class Student(models.Model): GENDER = ( ('1', 'Male'), ('2', 'Female') ) STATUS = ( ('1', 'Ongoing'), ('2', 'On Probition'), ('3', 'NA') ) name = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) id_number = models.IntegerField() gender = models.CharField( max_length=10, choices=GENDER, blank=True, null=True) date_of_birth = models.CharField(max_length=20, blank=True, null=True) course = models.ForeignKey( Course, on_delete=models.CASCADE, blank=True, null=True) year_level = models.IntegerField() status = models.CharField(max_length=10, choices=STATUS, default='3') def __str__(self): return str(self.name) class Teacher(models.Model): name = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) def __str__(self): return str(self.name) forms.py class SignUpForm(UserCreationForm): username = forms.CharField( widget=forms.TextInput( attrs={ "class": "form-control" } ) ) password1 = forms.CharField( widget=forms.PasswordInput( attrs={ "class": "form-control" } ) ) password2 = forms.CharField( widget=forms.PasswordInput( attrs={ "class": "form-control" } ) ) email = forms.CharField( widget=forms.TextInput( attrs={ "class": "form-control" } ) ) class Meta: model = User # model = Profile fields = ('username', 'email', 'password1', … -
Convert HTML to PDF with full CSS support
I want to convert a HTML file to PDF. Is there any package that supports CSS3? -
How to merge (audio-video) moviepy object download at client side using Django?
Is that possible to moviepy object download at the client-side without saving it in the local system? from moviepy.editor import * new_filename = "file.mp4" videoclip = VideoFileClip('https://r1---sn-bu2a-nu8l.googlevideo.com/videoplayback?expire=1638440709&ei=pUqoYZ2cI7rrjuMPkcmekAg&ip=103.250.149.188&id=o-ANFawiDzzYp-FoY6AqX0SXbijhKJ35opECWXtCnACjMA&itag=247&aitags=133%2C134%2C135%2C136%2C137%2C160%2C242%2C243%2C244%2C247%2C248%2C278&source=youtube&requiressl=yes&mh=Ex&mm=31%2C29&mn=sn-bu2a-nu8l%2Csn-cvh7knzy&ms=au%2Crdu&mv=m&mvi=1&pl=24&initcwndbps=1033750&vprv=1&mime=video%2Fwebm&ns=dlzD-Hg9SRxU5fPWrHNCpxoG&gir=yes&clen=4785704&dur=98.800&lmt=1629780934695756&mt=1638418840&fvip=4&keepalive=yes&fexp=24001373%2C24007246&c=WEB&txp=5316224&n=iQjeGVjS9lxbMWOMcaQ&sparams=expire%2Cei%2Cip%2Cid%2Caitags%2Csource%2Crequiressl%2Cvprv%2Cmime%2Cns%2Cgir%2Cclen%2Cdur%2Clmt&sig=AOq0QJ8wRAIgcB3Y4lQ_gHYarp6no018274Exolw0TWq2CLRs8yrSw8CIDOiiKaOcY5ErMyFoldCS7KHTzlQPPW0yEPYuVsCnCun&lsparams=mh%2Cmm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Cinitcwndbps&lsig=AG3C_xAwRgIhAJjwzsCqE5dF_IvaUo5JjQ8FsC1Wz9S84XGs_krXvSo5AiEA4va5rbULblSOajaV9-aJqP7vOsg5ZByr1QYJTQXegu0%3D') audioclip = AudioFileClip('https://r1---sn-bu2a-nu8l.googlevideo.com/videoplayback?expire=1638440709&ei=pUqoYZ2cI7rrjuMPkcmekAg&ip=103.250.149.188&id=o-ANFawiDzzYp-FoY6AqX0SXbijhKJ35opECWXtCnACjMA&itag=249&source=youtube&requiressl=yes&mh=Ex&mm=31%2C29&mn=sn-bu2a-nu8l%2Csn-cvh7knzy&ms=au%2Crdu&mv=m&mvi=1&pl=24&initcwndbps=1033750&vprv=1&mime=audio%2Fwebm&ns=dlzD-Hg9SRxU5fPWrHNCpxoG&gir=yes&clen=549813&dur=98.861&lmt=1629780936256332&mt=1638418840&fvip=4&keepalive=yes&fexp=24001373%2C24007246&c=WEB&txp=5311224&n=iQjeGVjS9lxbMWOMcaQ&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cvprv%2Cmime%2Cns%2Cgir%2Cclen%2Cdur%2Clmt&sig=AOq0QJ8wRQIhAPVt1A7C5tmoTqAtAIgx0vFlM7LHSiyD2QGmJBL0hdGBAiBfjiw5qrUrbw9KkTk_3z9gzDHHMsFUCOL9lhOMZbAbkg%3D%3D&lsparams=mh%2Cmm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Cinitcwndbps&lsig=AG3C_xAwRgIhAJjwzsCqE5dF_IvaUo5JjQ8FsC1Wz9S84XGs_krXvSo5AiEA4va5rbULblSOajaV9-aJqP7vOsg5ZByr1QYJTQXegu0%3D') new_audioclip = CompositeAudioClip([audioclip]) videoclip.audio = new_audioclip response = StreamingHttpResponse(streaming_content=videoclip) response['Content-Disposition'] = f'attachement; filename="{new_filename}"' return response It returns the error TypeError: 'VideoFileClip' object is not iterable Please help me.