Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I preview a pdf file before saving it in Django?
How do I preview a pdf file before saving it in Django? I am trying to preview a pdf file before the user uploads it using the "pip install preview-generator" Link: https://pypi.org/project/preview-generator/ However the pdf file isn't loading up properly. I am not really sure what is pdf_or_odt_to_preview_path as the documentation wasn't clear. As such, I tried to use JS and jquery to send information from the front end to views.py, and subsequently use the tag to hold the pdf file. First Attempt which didnt work as the file didnt show: views.py @login_required def preview(request): if request.method == 'POST': body = json.loads(request.body) embedPDF = body['PDF'] print(PDF) cache_path = '/tmp/preview_cache' pdf_or_odt_to_preview_path = f'{PDF}' manager = PreviewManager(cache_path, create_folder= True) path_to_preview_image = manager.get_jpeg_preview(pdf_or_odt_to_preview_path) return JsonResponse({'status':200}) javascript: $('#testing-nia').on('change', function () { const file = this.files[0] reader = new FileReader(); reader.readAsDataURL(file); $(reader).on('load', function() { PDF = this.result var request = new Request( "{% url 'preview' %}", {headers: {'X-CSRFToken': '{{csrf_token}}'}} ) fetch(request, { method: 'POST', mode: 'same-origin', body: JSON.stringify({'PDF' : PDF, }) }) .then(response => response.json()) .then(data => console.log('finished if false')) }) }) 2nd Attempt which rendered a header i dont want: javascript: else if (file.name.endsWith('pdf')) { reader = new FileReader(); reader.readAsDataURL(file); $(reader).on('load', function () { … -
"School with ID “601664bd3c7d8d38768c43b9” doesn’t exist. Perhaps it was deleted?" Error when migrated using mongorestore
I want to migrate the data from a Mongodb database running with a Nodejs+mongoose platform into a Django+djongo platform. I created the data backup using mongodump and got me a .bson file which I used for migration. data shown in source database is as follows. { "_id" : ObjectId("5c03c9f4a836690d6c540835"), "title" : "School A", "location" : "Location A", "postTime" : "1543752160981", "createdAt" : ISODate("2021-10-23T16:47:43Z"), "verified" : true, "__v" : 0, "image" : "http://21.441.45.80:3002/images/1543752161789-file.jpg", "thumbnail" : "http://21.441.45.80:3002/images/thumnail-1543752161789-file.jpg" } I created the destination database with similar fields avoiding "__v". I imported the source data into destination database using following command. mongorestore --db school_db --collection school_schoolmodel ../path/to/school.bson I got message that 1169 document(s) restored successfully. 0 document(s) failed to restore. Then I opened the django admin panel, and clicked one of the item. Then I got following error? School with ID “601664bd3c7d8d38768c43b9” doesn’t exist. Perhaps it was deleted? What is the issue here? I'm putting code here. Please comment if any additional details required. I'm not allowed to change the configuration of source database. models.py class NewsModel(models.Model): _id = models.CharField(max_length=20, primary_key=True, serialize=False, verbose_name='Company Code') title = models.CharField(max_length=60, blank=True) location = models.TextField(blank=True) postTime = models.IntegerField(blank=True) createdAt = models.DateTimeField(blank=True) verified = models.BooleanField(default=False, blank=True) image = models.ImageField(upload_to=image_upload_to, … -
how to render data from 1 view in 2 different htmls in the same page
My django web application has the following structure main.html <body> <div id="mn" class="mainw"> <div id="message" class="message"> <b>{{context.title}}</b> </div> <div class="sidenav"> <ul> <li class="li"><a href="acctlkpview" target="iframe1">Billing Account Lookup</a></li> <li class="li"><a href="acctlkpnoresell" target="iframe1">Billing Account Lookup No-Resell</a></li> </ul> </div> <div class="frame"> <iframe width="100%" height="100%" name="iframe1" > </iframe> </div> </body> i have another side navigation bar side nav which populates a iframe iframe1 inside the main.html Now the iframe is populated by views which returns data for the iframe when the unordered links in sidenav are clicked. For each view i load a different html page inside the frame, I return a value called title in the context, from the view context={"title":message,'role':role,'email':email} return render(request,'billingacct/view2.html',{"context":context}) Now I want this title to be set as the title attribute in the main.html {{context.title}}. But the view will only render attributes for view2.html which is displayed inside the iframe in the main.html. Can anyone please tell me how to achieve this? Thanks -
Django Forms not showing
I am trying to use Django provided forms instead of manually creating them with HTML. When I do this, however, they do not appear. The questions/answers I have found on this site have so far been unable to solve my issue. (unless I am reading them wrong.) forms.py from django import forms class KeywordForm(forms.Form): input_keywords = forms.CharField(label="Keywords", max_length='100') class LocationForm(forms.Form): input_location = forms.CharField(label="Location", max_length="250") views.py from django.shortcuts import render from .forms import KeywordForm, LocationForm def search_view(request): keyword_form = KeywordForm() location_form = LocationForm() return render(request, 'search_results.html', {'keyword_form': keyword_form, 'location_form': location_form}) urls.py from django.urls import path from . import views urlpatterns = [ ... path('search/', views.search_view, name='search'), ] base.html {% block search %} <div class="card"> <div class="card-body"> <form class="row align-items-center"> <form action="search" method="GET"> <div class="col-sm-2"> {{ keyword_form }} </div> <div class="col-sm-2"> {{ location_form }} </div> <!-- <label for="inputKeywords" class="form-label">Keywords</label>--> <!-- <input class="form-control" id="inputKeywords" type="text" name="inputKeywords" placeholder="Enter Keywords...">--> <!-- </div>--> <!-- <div class="col-sm-2">--> <!-- <label for="inputLocation" class="form-label">Location</label>--> <!-- <input type="Text" class="form-control" id="inputLocation" name="inputLocation" placeholder="Enter location...">--> <!-- </div>--> <div class="col"> <input class="btn btn-primary" type="submit" value="Search"> </div> </form> </form> </div> </div> {% endblock %} -
ImportError: No module named backends when uising python-social-auth when upgrading to Django 1.9
I am upgrading my project from Django 1.8 to Django 1.9 and when I run my server using python manage.py runserver i am getting error in my views like Traceback (most recent call last): File "/home/projectfolder/project/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/projectfolder/project/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "/home/projectfolder/project/local/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/home/projectfolder/project/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/home/projectfolder/project/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 10, in check_url_config return check_resolver(resolver) File "/home/projectfolder/project/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 19, in check_resolver for pattern in resolver.url_patterns: File "/home/projectfolder/project/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/projectfolder/project/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 417, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/projectfolder/project/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/projectfolder/project/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/projectfolder/projectrespos/dev-1.8/mcam/server/mcam/mcam/urls.py", line 10, in <module> from crm.views import * File "/home/projectfolder/projectrespos/dev-1.8/mcam/server/mcam/crm/views.py", line 63, in <module> from core.views import (CustomAuthMixin, CustomAdminMixin, JSONResponseMixin, File "/home/projectfolder/projectrespos/dev-1.8/mcam/server/mcam/core/views.py", line 477, in <module> from social.apps.backends import get_backends ImportError: No module named backends core/views.py from social.apps.backends import get_backends def get_auth_backends(): backends = get_backends() return [(name, title, backends.get(name)) for name, title in settings.SOCIAL_AUTH_ACTIVE_BACKENDS.items() if name in backends] In my settings.py folder INSTALLED_APPS = [ . . … -
Efective way to develop django project
i'm an intern and currently developing a simple dashboard to display visualization of school database, using Django. There are two scenarios of how am i gonna develop this, First, I connect django models to mysql database where the data stored. I fetch the models into table and graphics then display it in the html page, but the page consuming some time to load the data. Honestly, i don't really know how to processing the models in the views.py like i'm processing data usually in python using pandas. This scenario interact with only one database. Second, i connect mysql database directly in views.py and process it using pandas. When one executive want to know a graphic/chart from spesific row and column, they can request in the page. If it takes some time to load, it's okay, but the result have to be stored in django models. So, when the other executive want to know the same result, we just have to fetch the result from django database. This scenario interact with two database. I need some advice from you regarding what scenario that's better to used and some other tips to develop web dashboard using Django, considering this is my first … -
How to direct Http protocol to Https protocol in Django using mod_wsgi and SSL?
I'm using mod_wsgi to run my Django API but it's running on HTTP protocol. I want it to run in HTTPS protocol but I don't know how to install/configure SSL in the Dockerfile. I have searched for implementing SSL for my Django API but I couldn't find any example that uses dockerized Django application using mod_wsgi. Dockerfile: FROM python:3 RUN echo 'en_US.UTF-8 UTF-8' >> /etc/locale.gen && locale-gen ENV LANG=en_US.UTF-8 LC_ALL=en_US.UTF- COPY ./requirements.txt /requirements.txt RUN pip install --no-cache-dir -r /requirements.txt WORKDIR /opt/app-root COPY . /opt/app-root EXPOSE 80 CMD ["mod_wsgi-express", "start-server", "--port", "80", "--threads","20","--processes","5","--user","www-data", "--group", "www-data", "--log-to-terminal", "/opt/app-root/mysite/wsgi.py"] This site describes the implementation of OpenSSL in mod_wsgi but I don't know how to use this in Dockerfile. Please help me with this -
Django PasswordResetConfirmView
When using Django3.0 internal PasswordResetConfirmView and tampering with the token generated it raises a form "is_bound" error. It doesn't redirect to some failure url. Internal Server Error: /account/password/reset/MQ/akbdyj-e5f18868fas35e748160dd6ef006803a5/ Traceback (most recent call last): File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\response.py", line 108, in render self.content = self.rendered_content File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\response.py", line 86, in rendered_content return template.render(context, self._request) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\base.py", line 170, in render return self._render(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\loader_tags.py", line 62, in render result = block.nodelist.render(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\crispy_forms\templatetags\crispy_forms_tags.py", line 203, in render c = self.get_render(context).flatten() File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\crispy_forms\templatetags\crispy_forms_tags.py", line 112, in get_render node_context.update({"is_bound": actual_form.is_bound}) AttributeError: 'NoneType' object has no attribute 'is_bound' I have tried passing the failure template … -
How to seralize cart?
I got this error when I added product in the basket type object 'Cart' has no attribute '_meta'. Views Django class Cart(object): def __init__(self, request): """ Initialize the cart. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: #Save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart self.coupon_id = self.session.get('coupon_id') Form from django import forms from django.core.validators import MinValueValidator, MaxValueValidator class CartProductForm(forms.Form): quantity = forms.IntegerField(initial=1) update_qt = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) HTML Form Code <form action="{% url "..." %}" method="post" data-id="{{ ... }}" class="form-order" id="form"> {{ cart_product_form }} {% csrf_token %} <a data-id="{{ ... }}" class="buy-product"><button>BUY</button></a> </form> HTML Span <ul class="navbar-nav ml-auto d-block d-md-none"> <li class="nav-item"> <a class="btn btn-link" href="#"><i class="bx bxs-cart icon-single"></i> <span class="badge badge-danger" id="cartval">{{ cart | length }}</span></a> </li> </ul> -
What is the best way to write Django for user interaction using button which updates values in the model
I am trying to write Django code for below: A user presses a button in the frontend. Multiple button options to decrement value by 10, 20, 30 etc. When the user presses the button, value for a Django model attribute in the backend will decrement accordingly. For example in the code below I set the intial value to 107. When the user presses the "Subtract 10" button in the html template, I want 10 subtracted from 107, so that the value then becomes 97. User is not entering any data. I unsuccessfully tried to use Django modelForm and "POST" and that did not work. Any suggestions appreciated. Below is the code I had that did not work. models.py class Balance(models.Model): userBalance = models.DecimalField(max_digits=10, decimal_places=2, null=True) forms.py class BalanceForm(forms.ModelForm): class Meta: model = Balance fields = ['userBalance'] views.py def balance(request): form = BalanceForm(initial={"userBalance":107}) if form.is_valid(): if request.method == "POST" and "form10" in request.POST: formValue = form.cleaned_data.get('userBalance') form2 = formValue - 10 return render(request, "econlabs/balance.html", {'form2': form2}) return render(request, "econlabs/balance.html", {'form': form}) -
Django no context data
I try to show data on template. But context data ois empty on html page. views.py from .models import DataS def index(request): list_z = DataS.objects.all().count() context = {'list_z:': list_z} return render(request, 'index.html', context=context) index.html <!DOCTYPE html> <html> <head>Page</head> <body> <ul> <li>{{ list_z }}</li> </ul> </body> </html> -
Can't reference Django database with dj_database_url
I have a Django application using decouple and dj_database_url (it is not on Heroku). If I put my connection information in settings.ini (DB_NAME, DB_USER, DB_PASSWORD, DB_HOST, and DB_PORT) and set up my database connection in settings.py like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': config('DB_HOST'), 'PORT': 'DB_PORT', } } It works fine. However, if I put this in my settings.ini: DATABASE_URL=postgres://johndoe:mypassword@123.456.789.000:5000/blog_db and reference it like this in my settings.py: DATABASES = {"default": dj_database_url.config(default=config("DATABASE_URL"))} It doesn't work. I just get a 500 when I try to run my server. I presume there is something wrong with my syntax. Can anyone point out what I'm doing wrong? Thanks! -
Django: making an evenly distributed mixed item feed
Let's say I want to generate a feed consisting of ItemA and ItemB, each item has a "published_date" field and newer items should appear at the top of the feed. However I want to further ensure that the feed always has 2 of ItemA, followed by 1 of ItemA, followed by 2 of ItemA,....regardless of the absolute publish date (i.e. even if the 10 most recent published items were all A, I'd still see B as the third item if there is an instance of it). How can I achieve something like this in Django? I was originally doing this something like # models.py class FeedItem(models.Model): id = HashidAutoField(primary_key=True, min_length=8, alphabet="0123456789abcdefghijklmnopqrstuvwxyz") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True, db_index=True) # When is this scheduled to be published publish_date = models.DateTimeField(db_index=True) # Type of Feed Item ITEM_TYPES = Choices((1, 'A', 'ItemA'), (2, 'B', 'ItemB')) # item_type item_type = models.PositiveSmallIntegerField(db_index=True, choices=ITEM_TYPES) def save(self, force_insert=False, force_update=False, using=None, update_fields=None, **kwargs): """ Ensure that when we save each subclass then we get the correct item_type :param force_insert: :param force_update: :param using: :param update_fields: :param kwargs: :return: """ if (self.__class__.__name__ == 'FeedItemA' and self.item_type != self.ITEM_TYPES._identifier_map['A']): self.item_type = self.ITEM_TYPES._identifier_map['A'] elif (self.__class__.__name__ == 'FeedItemB' and self.item_type != self.ITEM_TYPES._identifier_map['B']): … -
Celery. How to kill a task when it exceeds a certain execution time?
I would like to kill a task when it exceeds a certain execution time. I have been trying with the expires argument and with the time_limit and soft_time_limit configuration variables, but neither works as the task continues to run after this time exceeds. I'm using celery==5.0.5, redis==3.5.3 and Django==3.1.7 This is the code I have been using: # In settings.py CELERY_BROKER_URL = "redis://redis:6379" CELERY_RESULT_BACKEND = "redis://redis:6379" CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'America/Mexico_City' CELERY_ENABLE_UTC = True CELERYD_TASK_TIME_LIMIT = 300 CELERY_TASK_TRACK_STARTED = True # In tasks.py @shared_task(name='some_process') def some_process(_id, flag): # Do some long process pass # Running the task expires = 300 tasks.some_process.apply_async((_id, flag), expires=expires) I also read other questions, but they have the reverse problem: link, link link -
Update quantity of cart after add product to cart AJAX / Django without refreshing page?
The product is successfully added in the cart but the cart value is not up to date. I will have to refresh the page so that the div is up to date. I tried the load() and html() methods but anything will happened. How to refresh cart container when I add the product to the cart ? I need a help please. Views Django def add_cart(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update_qt'] ) return JsonResponse({'status': 'success'}) Form from django import forms from django.core.validators import MinValueValidator, MaxValueValidator class CartProductForm(forms.Form): quantity = forms.IntegerField(initial=1) update_qt = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) HTML Form Code <form action="{% url "..." %}" method="post" data-id="{{ ... }}" class="form-order" id="form"> {{ cart_product_form }} {% csrf_token %} <a data-id="{{ ... }}" class="buy-product"><button>BUY</button></a> </form> HTML Span <ul class="navbar-nav ml-auto d-block d-md-none"> <li class="nav-item"> <a class="btn btn-link" href="#"><i class="bx bxs-cart icon-single"></i> <span class="badge badge-danger" id="cartval">{{ cart | length }}</span></a> </li> </ul> JS Code $(".form-order").on('submit', function(e){ e.preventDefault(); var product_id = $(this).attr('data-id') var quantity = $(this).find("#id_quantite").val() console.log(product_id) console.log(quantity) data = { 'product_id': product_id, 'quantity': quantity } var point='/cart/add/'+product_id+'/' $.ajax({ headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, url: point, type: 'POST', dataType: 'json', data: data, success: … -
Is it possible to use an iframe in django without putting it in static and generating a url?
In an app made with django, I want to call the editor.html file as an iframe in the search.html file in the following folder. my app template serach.html editor.html Most answers are to register editor.html in url or go to static file. I have checked that both methods are currently running, but I want to save them in the same folder and call them without registering the url. The code that calls the current iframe is <iframe id="sketch" src="./editor.html" </iframe> I wrote it, but the iframe doesn't work. Is there any other way besides the two above? -
Django project does not work after being transferred from Windows to Mac
I'm using Django 3.1.7 on a MacBook Pro after transferring the Django project off of a Windows 10 machine. However, upon re-setting up the database and superuser and running the command pipenv sync to install all necessary modules, the server does run; but it doesn't serve any of my URLs or the CSS styles for the Admin page. I can reach the admin page at '/admin' but no other page that I've set up will display. All it gives me is my custom 404 page whenever I try to serve a page. Is there any way to fix this? Is something wrong? Where are the Admin CSS files? -
How to include an avatar/profile image in Django send_email with a "noreply" address?
In email clients such as Gmail and Apple Mail, with each incoming email there's an avatar/profile image of the email's sender. I have a Django app that sends emails from a "noreply@mycompany.com" email address using send_mail. The (sanitized) code looks something like the following: from django.template.loader import get_template from django.core.mail import send_mail from myapp.models import User ... users = User.objects.all() subject = 'Email for {name}'.format(name=user.name) plaintext = get_template('emails/email_template.txt') html = get_template('emails/email_template.html') data = {'name': user.name} text_content = plaintext.render(data) html_content = html.render(data) for user in users: send_mail(subject, text_content, 'noreply@mycompany.com', [user.email], html_message=html_content) print('Email sent: ' + user.email) I want to have my company's logo be displayed in email clients as the avatar/profile image. What is the best way to accomplish this? For example, is this something I can specify in my emails' Django template? -
Django, lose the variables of a template when I call the extended template
I have a django project and an random app, a homepage.html in localhost:8000/, a base.html with a path url: /base/some_id, an extended template1.html with url:/base/some_id/template1. base.html <body> <h2>{{message}}</h2> <a href="{% url 'template1' some_id %}">BUTTON</a> {% block content%} {% endblock %} </body> template1.html {% extends 'base.html' %} {% block content %} <p>some text here</p> {% endblock %} urls.py urlpatterns = [ path('', views.home, name = 'homepage'), path('base/<int:some_id>/',views.base, name = 'base'), path('base/<some_id>/template1/', views.template1, name = 'template1'),] views.py def base(request,some_id): context={ "message":"Hello", "some_id":some_id, } return render(request,"base.html",context) def template1(request,some_id): return render(request,"base.html",{"newmessage":"some text"}) My page base.html is correctly displayed, but when I click to the tag to go to template1 I take a message "Reverse for 'template1' with arguments '('',)' not found...." I've tried many things but nothing worked, I think my issue is that the variable "some_id" doesn't have any value in template anymore. Any help would be appreciated! Thank you in advance guys! -
DJANGO: Upload image file to cart
I am completing a project which involved building a shopping cart. The shopping cart requires the user to attach an image to the OrderItem The cart is updated from the store via javascript. I have been able to separate out the code into a separate view and have it successfully upload the image, but to an separate instance of the OrderItem which is not connected to the existing orderitem. When attached on the cart the user is able to upload in the browser, but the file is not transmitted to the DJANGO backend or uploaded to the file location. The page reloads but no traceback is present. I am new to coding and have only limited experience. Please help! Settings.py """ Django settings for ecommerce project. Generated by 'django-admin startproject' using Django 3.0.2. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = # SECURITY WARNING: don't run with debug turned … -
How to access a point in postgis database from Django?
I am trying to get points (latitude longitude coordinates) from my database using django / postgis, but I run into this error that I can't figure: django.db.utils.ProgrammingError: cannot cast type point to bytea LINE 1: ...lon_id", "lat_lon"."house_id", "lat_lon"."lat_lon"::bytea FR... My database looks like this: And I set up my model (models.py) like this: class LatLon(models.Model): lat_lon_id = models.AutoField(primary_key=True) house = models.ForeignKey(Houses, models.DO_NOTHING) lat_lon = models.PointField() class Meta: managed = False db_table = 'lat_lon' @property def lat_lng(self): return(list(getattr(self.lat_lon, 'coords', []))[::-1]) and make a listview (views.py): class LatlonList(ListView): queryset = LatLon.objects.filter(lat_lon__isnull=False) Finally my urlpatterns look like this: urlpatterns = [ path("", views.home, name="home"), path("hello/<name>", views.hello_there, name="hello_there"), path("about/", views.about, name="about"), path("contact/", views.contact, name="contact"), path("log/", views.log_message, name="log"), path("test_page/", views.LatlonList.as_view(template_name = 'test_page.html'), name="test_page"), path('map/', views.EntryList.as_view()), I guess from the error that Django tries to cast my points to bytea data type, but I clearly specify in the model that they are points (Pointfield). I am new to django, so any responses/hints are appreciated! -
Django Loading Page while Server does some backend retrieval
I am trying to bulid a website via Django. Basically what I'm after is that the website will first open a simple loading screen. On that time there is some processing done in the backend to retrieve the data. Once data retrieval is finalised the loading page is redirected to another page. Any idea on how this can be done please. I'm pretty convinced that I need to use Ajax but would really love to get the syntax of how it can be done Thanks -
CBV form_valid() and form_invalid() methods not called, form not saved to database
I tried following this tutorial: Link Whenever I try creating/updating/deleting a Record (my model, in this case) it redirects me to the page I've told it to redirect me to, and displays that a POST has been called in the command prompt, yet the Record is not created. I've tried overwriting both the form_valid() and form_invalid() functions, and added some print statements. Neither print statements print, so I don't believe either of these methods are called. Why are neither of these methods called, and why isn't my model being created and stored? Here's the model creation form, record_form.html: {% extends "catalog/base.html" %} {% block content %} <h1 class="text py-3 pt-4">Create/Update a Record!</h1> <style> .text { font-size: 40px; font-weight: bold; color: #060007; } </style> <div class="shadow p-3 mb-3 bg-light rounded"> <form class="form" method="POST" action="/catalog/"> {% csrf_token %} <p><label for="my_catalog">Catalog name:</label> {{ form.my_catalog }}</p> <p><label for="name">Name:</label> {{ form.name }}</p> <p><label for="description">Description:</label></p> <p>{{ form.description }}</p> <p><label for="date_start">Date start:</label> {{ form.date_start }}</p> <p><label for="date_end">Date end:</label> {{ form.date_end }}</p> <p><label for="manufacturer">Manufacturer:</label> {{ form.manufacturer }}</p> <p><label for="condition_rating">Condition rating (between 0 and 5):</label> {{ form.condition_rating }}</p> <p><label for="condition_description">Condition description:</label></p> <p>{{ form.condition_description }}</p> <div><input type="submit" value="Save"></div> </form> <style> .form { color: #060007; } </style> </div> {% endblock content … -
Docker - Django - PermissionError after switching to Host volumes on Ubuntu Server
The Docker image / container worked fine on Ubuntu, however I wanted to have access to the static folder. Therefore I added "Host volumes" to the docker-compose.yml (volumes was empty before): version: '3.3' services: api: build: context: . restart: always ports: - "8000:8000" volumes: - ./app_static:/app/static $ docker-compose up After building the image and running the python manage.py collectstatic command, I get the following error: PermissionError: [Errno 13] Permission denied: 'static/media' The folder structure inside the docker image looks like this: appuser@1e2bc02404a2:/app$ ls -la total 24 drwxr-xr-x 1 appuser appuser 4096 Mar 29 21:50 . drwxr-xr-x 1 root root 4096 Mar 29 21:51 .. drwxr-xr-x 1 appuser appuser 4096 Mar 29 21:00 api -rw-r--r-- 1 appuser appuser 765 Mar 29 21:00 manage.py drwxr-xr-x 1 appuser appuser 4096 Mar 29 21:00 mausefallentest drwxr-xr-x 2 root root 4096 Mar 29 21:51 static The problem is, that after adding Host volumes to the docker-compose file, the user for the static folder changed to root. But the Docker image is runnung under the "appuser" user. Thus i get the permission denied error. But how can i solve this problem ? I only have this problem on my Ubuntu server. On Windows its working fine. -
Unable to Save images to database
am unable to save images containing url on database this will give me an error if file and not file._committed: AttributeError: 'list' object has no attribute '_committed' this error is as a result of my attempts to save this scrapped image with beautiful soup below are images list that refused to be saved on my models , this images are been scrapped with beautiful soup something like this brought the images images = [i['data-src'] for i in soup.find_all('img', {'class','attachment-jnews-750x375 size-jnews-750x375 lazyload wp-post-image'})] https://people.net/wp-content/uploads/2021/03/ad1-746x375.jpg https://people.net/wp-content/uploads/2020/08/caroon-1-600x375.jpg why this code brought the above error Post.objects.create( title=title, content_1=paragraphs, image=images, sources=lnk, ) this is my model.py example code class Post(models.Model): title = models.CharField(max_length=250, blank = True, help_text='Maximum 160 Title characters.') image = models.FileField(upload_to='images', blank=True, null=True, help_text='You must upload original image before continuing.') but i get this error if file and not file._committed: AttributeError: 'list' object has no attribute '_committed' but if am saving normal jpeg file it is always a success. how do i save this scrapped images to models