Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display Django Foreign key on webpage
I have three models. class Supplier(models.Model): name = models.CharField(max_length=200, null=True) class Order(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) class Product(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, null=True, blank=True) on_order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True, blank=True) I can display a table of all the products of a given order. However, I cannot seem to render the name of that supplier on the html page like <h4> Supplier: {{order.supplier}}</h4> this is the view: def PurchaseOrder(request, pk_order): orders = Order.objects.get(id=pk_order) products = Product.objects.filter( on_order_id=pk_order).prefetch_related('on_order') total_products = products.count() supplier = Product.objects.filter(on_order_id=pk_order).prefetch_related('on_order') context = { 'supplier': supplier, 'products': products, 'orders': orders, 'total_products': total_products, } return render(request, 'crmapp/purchase_order.html', context) I've tried so hard... and didn't get very far. Please help... -
Mongodb aggregations with django
i am trying to develop a mongodb aggregation with django and python. I have an atlas server with a database named 'sucre' with a collection named 'bdua' In settings.py i have: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'morfeeweb', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': 'mongodb+srv://xxxxxx:xxxxxx@xxxxx.xxxxx.xxxxxx.mongodb.net/morfeeweb?retryWrites=true&w=majority', 'port': 27017, 'username': 'xxxxxx', 'password': 'xxxxxxxx', 'authSource': 'admin', 'authMechanism': 'SCRAM-SHA-1' }, 'LOGGING': { 'version': 1, 'loggers': { 'djongo': { 'level': 'DEBUG', 'propagate': False, } }, }, }, 'sucre': { 'ENGINE': 'djongo', 'NAME': 'sucre', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': 'mongodb+srv://xxxx:xxxxxx@xxxxx.xxxxx.xxxx.mongodb.net/sucre?retryWrites=true&w=majority', 'port': 27017, 'username': 'xxxxx', 'password': 'xxxxxxxx', 'authSource': 'admin', 'authMechanism': 'SCRAM-SHA-1' }, 'LOGGING': { 'version': 1, 'loggers': { 'djongo': { 'level': 'DEBUG', 'propagate': False, } }, }, } } views.py from django.contrib.auth.decorators import login_required from django.shortcuts import render from django.http import HttpResponse, JsonResponse from random import randint from django.db import connection @login_required(login_url='/admin/login') def consolidado(request): aggretation_sample = connection['sucre'].db.bdua.aggregate([ { '$match': {'estado': 'AC', 'regimen': 'subsidiado'} }, { '$group': { '_id': '$cod_EPS', 'Afiliados': {'$sum': 1}} }, { '$sort': {'Afiliados': -1} } ]) return HttpResponse(aggretation_sample) It returns 'TypeError at /aseguramiento/ 'DefaultConnectionProxy' object is not subscriptable' Help please -
Jinja for loop is not working after adding qs to iterator. Django
In my project I am using django-filter and when I am adding .qs to {% for product in products %} {% for product in products.qs %}. In the template result filters are displaying, but products are not. Here are my files. html <form method="get"> {{ filterA.form.as_p }} {{ filterB.form.as_p }} <input type="submit" value="Press" class="filter-go"> </form> {% for product in products.qs %} <div class="product" onclick="location.href='{% url 'items' product.id %}'"> <img src="{{product.image.url}}" alt="Img is not found ("> <p class="product-title">{{ product.title }}</p> <b><p class="product-price">{{ product.price }} &#8381;</p></b> </div> {% endfor %} views.py def index(request): con = { 'services': Service.objects.all(), 'products': Product.objects.all(), 'galery': GaleryImage.objects.all(), 'product_types': Category.objects.all(), 'filterA': FilterA(request.GET, queryset=Product.objects.all()), 'filterB': FilterB(request.GET, queryset=Product.objects.all()), } return render(request, 'index.html', con) def product(request, pk=None): try: a = Product.objects.get(id=pk) except: return render(request, 'error404.html') context = { 'id': pk, 'product': a, } return render(request, 'product.html', context) filters.py class FilterA(django_filters.FilterSet): class Meta: model = Product fields = ['category'] class FilterB(django_filters.FilterSet): CHOICES = ( ('ascending', 'По дате (А-Я)'), ('descending', 'По дате (Я-А)'), ) CHOICES2 = ( ('price_low', 'По цене по возрастанию'), ('price_high', 'По цене по убыванию'), ) orderDate = django_filters.ChoiceFilter(choices=CHOICES, method='filter_by_date', label='') orderPrice = django_filters.ChoiceFilter(choices=CHOICES2, method='filter_by_price', label='') class Meta: model = Product fields = { 'price': ['lt', 'gt'], } def filter_by_date(self, queryset, … -
supervisor does not start process (django server with waitress) as user
I have added the username=myname in the supervisor config files. Then I executed: sudo supervisorctl reread all sudo supervisorctl reload all sudo supervisorctl restart all And then I killed all the running processes to make sure they are restarted with the new config. However, one of my processes, a django server, keeps starting as root. Why is it not starting under the respective username? ps aux | grep server.py > root 4286 19.2 0.5 1336924 180920 ? Sl 17:22 0:02 python server.py server.py: from waitress import serve from omics_server.wsgi import application if __name__ == '__main__': serve(application, port='8123', url_scheme='https', threads=12, max_request_body_size=20*1073741824) -
Can I upload my Python Django web app on Cpanel without buying and installing Cloud Linux
Hey guys i have made my django project successfully and I was ready to upload my django project to cpanel Linux shared Hosting which I bought but when I searched on Google on how to upload Django project to cpanel I found that there is a option in cpanel called Setup Python App which gives us features to upload Python Apps and this option is only shown on cpanels which have CloudLinux but I don't have CloudLinux and it is paid. My cpanel is only showing me Application Manager kind of thing under Software Option which I think could be an alternative to upload my app. Am I right, can I really do that with Application manager thing or is there any free way to upload my Django App on my bought cpanel. I bought Linux shared hosting in cpanel and bought a domain too. Please Help. -
What does request.GET.get('page') mean?
What does request.GET.get('page') mean? Also can someone explain what is happening here: def post_list(request): object_list = Post.published.all() paginator = Paginator(object_list, 3)# 3 posts in each page page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page posts = paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results posts = paginator.page(paginator.num_pages) return render(request, 'blog/post/list.html', {'page': page, 'posts': posts}) -
Can I upload Django project on Cpanel without CloudLinux installed
Hey guys i have made my django project successfully and I was ready to upload my django project to cpanel Linux shared Hosting which I bought but when I searched on Google on how to upload Django project to cpanel I found that there is a option in cpanel called Setup Python App which gives us features to upload Python Apps and this option is only shown on cpanels which have CloudLinux but I don't have CloudLinux and it is paid. My cpanel is only showing me Application Manager kind of thing under Software Option which I think could be an alternative to upload my app. Am I right, can I really do that with Application manager thing or is there any free way to upload my Django App on my bought cpanel. I bought Linux shared hosting in cpanel and bought a domain too. Please Help. -
Django db_index=True and Meta Indexes in Django 3.1 and PostgreSQL: what is the difference and what is best practice
There is a pretty old question about it here and I don't think it quite answers the difference and what should be used: Database indexes in Django 1.11: difference between db_true, indexes and index_together At any rate, there is: db_index. For example: test_int = models.IntegerField(db_index=True) Meta models.Index class Meta: indexes = [ models.Index(fields=['last_name', 'first_name']), models.Index(fields=['first_name'], name='first_name_idx'), ] I guess I'm not seeing entirely what the benefit is of one over the other and what the convention is for use. There is nothing explicitly saying the documentation. I guess it is easier to read using models.Index Suggestions? -
Is it worth to learn Flask? How powerful is that?
I learned Python and i would like to use it and make money with that. I worked with django about a few days but i didn't like that. Should i learn Flask? Can I make good websites with Flask? Is it worth to learn? -
Django get filename without url
I get a file with this commannd: src = request.POST.get('src', '') But the output is: https://url.com/path/filename.jpg How can I just get path/filename.jpg? regards Christopher -
Why custom RESTful Django Authentication triggers AttributeError :- Exception Value: 'PasswordInput' object has no attribute 'startswith'
I was working on a Signup Page, where REST API Authentication is used. superuser created as username:foo and password:bar but when i run the server, and tries to login in Django admin. password = forms.CharField(widget=forms.PasswordInput()) ** This is the Error throw ** Error Page -
Django: Pass LDAP Credentials to 3rd Party SDK
I'm new to Django and developing an app for internal use. I have configured it with the django_auth_ldap module for authenticating to LDAP. Once the user has authenticated there are automation tasks for them to execute that use 3rd party SDKs (also LDAP auth required). Below is a simple function in my views.py config that will create a session using the SDK, but is there a way to pass the authentication of the user to the function? views.py def create_session(hostname, username, password): """Create an API Session using an SDK.""" session = SDK(hostname, username=username, password=password) return session @login_required def list_info(request): if request.method == 'POST': form = Form(request.POST) if form.is_valid(): session = create_session(form.cleaned_data['host'], ?username?, ?password?) host_info = session.get() note = 'Information from {}: '.format(form.cleaned_data['host']) dataset = pd.json_normalize(host_info) session.invalidate_cookie() else: note = 'API call has failed. Try again.' return render(request, 'list_info.html', {'form':form, 'note':note, 'dataset':dataset.to_html(index=False, justify='left', classes='table table-stripe')}) else: form = Form() return render(request, 'list_info.html', {'form':form}) I originally created CLI apps using the click module but have been trying to convert them to Django. Is there an easier approach to this? -
Page not found error in django where it is not supposed to rise
I am building a video player app in django. But, when going to the register route, I get this error: Page not found (404) Request Method: GET Request URL: http://localhost:8000/users/login/%7B%25%20url%20'register'%20%7D I don't even have a url called users/login/register. And I have checked my urls.py. Here it is: urlpatterns = [ path('register/',views.register,name='register'), ] And here is the link that leads to this route: <a href="{% url 'register' }">Register</a> I have built many apps with django but have never encountered an error like this. Why am I getting this error? -
How can I return a redirect and file in Django
I'm working on a form that when submitted has the option to export a PDF. This is great but I would also like to be able to return a new URL for the user to be redirected to as well as downloading the file. Something that combines render() or redirect() with FileResponse() -
Using For loop and If condition in Django to display Images in Bootstrap Carousel
I haven been looking everywhere for a case similar to this, but haven't found anything that could solve my problem. I want to display an image from a model in my html inside a for loop, which has an if condition. This is my models.py: from django.db import models # Create your models here. class CarouselItem(models.Model): carousel_picture = models.ImageField(upload_to='carousel_images/', null=True, blank=True) views.py: from django.shortcuts import render from .models import CarouselItem # Create your views here. def index(request): carousel_items = CarouselItem.objects.all() context = { 'carousel_items': carousel_items } return render(request, "home/index.html", context=context) and my html: {% if carousel_items %} <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> {% for item in carousel_items %} {% if forloop.first %} <div class="carousel-item active"> <img src="{% item.carousel_picture.url %}" class="d-block w-100" alt="..."> </div> {% else %} <div class="carousel-item"> <img src="{% item.carousel_picture.url %}" class="d-block w-100" alt="..."> </div> {% endif %} {% endfor %} <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> {% else %} <h3>We are sorry, there are currently no Images to display</h3> {% endif %} When I want to access the page associated with the html I get this error message: Invalid … -
how to setup static file in django 3.1
I am having issue with setting up static_root ,i m using django 3.1, And trying to deploy my project on heroku server. so when i try to create new superuser by heroku run python manage.py createsuperuser then it returns following traceback. Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/app/dotescrow/settings.py", line 15, in <module> django_heroku.settings(locals()) File "/app/.heroku/python/lib/python3.6/site-packages/django_heroku/core.py", line 89, in settings config['STATIC_ROOT'] = os.path.join(config['BASE_DIR'], 'staticfiles') KeyError: 'BASE_DIR' in settings.py im doing configuration in a following manner. STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_ROOT = "/var/www/example.com/static/" STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", # '/var/www/static/', ] if more code … -
Reverse for 'detail' with no arguments not found. 1 pattern(s) tried: ['product/(?P<slug>[-a-zA-Z0-9_]+)$']
hi everyone i got this error when i post a comment although the comment is posting but it give me this error and do not go to any redirect URL my views.py file is: class CommentCreateView(CreateView): model = Comment form_class = CommentForm template_name = 'add-comment.html' # fields = '__all__' def form_valid(self, form): form.instance.product = Product.objects.get(slug=self.kwargs['slug']) return super().form_valid(form) success_url = reverse_lazy('products:detail') my urls.py is: urlpatterns = [ path('' , ProductListView.as_view(), name= "list"), path('new/' , ProductCreateView.as_view() , name="product-create"), path('<slug:slug>/update/' , ProductUpdateView.as_view() , name="product-update"), path('<slug:slug>/delete/' , ProductDeleteView.as_view() , name="product-delete"), path('<slug:slug>/comment' , CommentCreateView.as_view() , name="add-comment"), path('<slug:slug>' , ProductDetailSlugView.as_view() , name="detail"), ] my models.py file is: class Comment(models.Model): product=models.ForeignKey(Product , related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=255) body=models.TextField() date_added = models.DateTimeField(auto_now_add=True) # def get_absolute_url(self): # return reverse("products:detail", kwargs={"slug" : self.slug}) def __str__(self): return '%s - %s'%(self.product.title, self.name) and my add-comment.html is: {% extends "base.html"%} {% load crispy_forms_tags%} {% block content %} <h2 class="text-center">comment here...</h2> <div class="col-md-6 offset-md-3"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> {{form|crispy}} </fieldset> <button class="btn btn-secondary" >Add comment</button> </form> and when i click on add comment it is adding comment but do not redirect to that page. the error is:enter image description here -
How to send a specific Mailgun email template from django application?
I am implementing mailgun with a django application and thinking about the logic. Firstly, I thought about creating templates in mailgun and when the cronjob takes place - it gets the recipient list and downloads the related template and off it sends. However, two issues arose along the way. First of all, when downloading the template with a function provided by mailgun, def get_template(template_name): return requests.get( "https://api.mailgun.net/v3/mydomain/templates/{0}".format(template_name), auth=("api", "mykey")) instead of the actual html (which is needed for the send_mail function it returns <Response [200]>. Nevertheless, if a template will contain eg images or other attachments, it would create unnecessary traffic due to the downloading. So now I am thinking about somehow specifying the template and other required attrs and sending it to mailgun which would send the email. However I cannot find a function or any solution (I'm looking for example here) that would allow me to specify the template eg ... data={'recipients': 'some list', 'template': 'template001', ... I would much appreciate any thoughts on this or any suggestion or hint. -
How can I call collectstatic routine inside a django app?
My Django app works with css/html themes and I can upload new themes from the user interface, that is, a regular user can upload a new theme without asking for a IT guy. I usually call a os.run('python manage.py collectstatic') but I would like to know if it is possible to do it in a more elegant or pythonic way. -
Handle List of objects passed to django template in jQuery for Ajax call
I have my views.py function as below: def method(request): objects = Model1.objects.all() return render(request, 'manager/link.html', {'objects': object}) In my template, link.html I have the below code: <script> $('#nav').on('click', function (event) { $('#stock_holdings').text('Loading...'); var stocks = ({{ stocks|get_list|safe }}); $.ajax({ type: "GET", url: '{% url 'broker:load_data' %}', data: { 'stocks': stocks, }, dataType: 'json', success: function (data) { $('#stock_holdings').text(data['stocks_details']); } }); }) ; </script> where get_list is a custom tag to convert the queryset into a list of objects: @register.filter def get_list(queryset): return list(queryset) However I get the below error when the code is run and I see its due to this in the browser debug window: Error: Uncaught SyntaxError: Unexpected token '<' Line causing the error: var stocks = ([<broker: stock1>, <broker: stock2>]); It looks like the '<' in the list of objects is causing the error. Could someone please help on how to handle this? -
Why doesn't Django load my javascript file correctly?
I am new to Django and I'm trying to implement drag and drop file uploading using dropzone.js. I was follow this tutorial to start of with. Dropzone is working fine and the file is being uploaded and stored correctly, my issues comes with the customization of the dropzone instance. I created a second javascript file to create my custom dropzone like the tutorial showed and included it into the django template. But for some reason this does not change anything, with or without customization javascript file, the dropzone looks exactly the same. The javascript file: Dropzone.autoDiscovery = false; const dropzone = new Dropzone("#drop", { dictDefaultMessage = "Upload your PDF here", clickable: false, url: "/upload", maxFiles: 1, acceptedFiles: ".pdf", }); The django template file I'm trying to include the script into: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>PDF2Notes</title> </head> <body> <form method="POST" action="/upload" class="dropzone dz" id="drop"> {% csrf_token %} <div class="fallback"> <input name="file" type="file"> </div> </form> <!--default stylesheet--> <link rel="stylesheet" type="text/css" href="{% static 'converter/style.css' %}"> <script type="text/javascript" src="{% static 'converter/main.js' %}"></script> <!--dropzone js & css--> <link rel="stylesheet" tpye="text/css" href="{% static 'converter/dropzone/dist/dropzone.css' %}"> <script type="text/javascript" src="{% static 'converter/dropzone/dist/dropzone.js' %}"></script> </body> </html> My static file directory is setup correctly, … -
Django deployment with Docker on EB failed and 502 badgateway
Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY ./config/requirements.txt . RUN pip install -r requirements.txt COPY . . docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0:8000 ports: - '8000:8000' depends_on: - db - redis db: image: postgres environment: - POSTGRES_USER=postgres_test - POSTGRES_PASSWORD=postgres_test_pw redis: image: redis ports: - '6379:6379' and in vscode terminal eb init -> choose docker , Docker running on 64bit Amazon Linux 2 eb create -> application balancer type and when "eb open" i got 502 badgateway what should i do -
Django & PostgreSQL is making Server response very slow
When we are doing changes in the code of CSS or python Django, sometimes the changes are reflecting after 15-20 min. but when we restart the web server the changes reflect. so is there any setting in Django to store or release Cache Memory or Virtual Memory that is making the code changes response slower? -
Django channels + celery: Handler is called on exception, fails to be called for a second time
I have an api endpoint that triggers a celery task, when it's done, it writes a result into a AsyncWebSocketConsumer group (Only one user will be on it). This goes well on all successful tasks, but if a task fails due to an exception, it will send a failure event the first time and it will be sent via the websocket (As expected), but it will fail to do it a second time. class ConversionConsumer(AsyncWebsocketConsumer): async def connect(self): self.user = self.scope["user"] self.awaiting_for_conversion = None if self.user.is_anonymous: await self.close() return await self.accept() async def disconnect(self, close_code): if self.awaiting_for_conversion: await self.channel_layer.group_discard( self.awaiting_for_conversion, self.channel_name ) async def receive(self, text_data): try: action = json.loads(text_data) # the user has to send a message asking for the conversion he wants to receive information on if action['type'] == 'await_for_conversion': self.awaiting_for_conversion = action['payload']['uid'] await self.channel_layer.group_add( self.awaiting_for_conversion, self.channel_name ) except: pass async def conversion_succeded(self, event): uid = event['uid'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'status': 'SUCCESS', 'type': 'conversion_has_finish', 'uid': uid })) async def conversion_failed(self, event): # This will be called the first time an exception is raised and caused the task to fail, but not if another task is called and fails the same way uid = event['uid'] … -
Working on Django forms, I will like to use input field as variable for a regular expression function? not working as I have it
passing input of form search = form.cleaned_data["search"] return get_search(request,search, list1) *using input form as variable def get_search(request,search, list): # convert list to string for re entries = str1.join(list) # using pattern to match items in my string?? re pattern = re.compile(r'{}.*.format(search)', re.IGNORECASE) matches = pattern.finditer(entries) # ** passing variables to a new template but it is not working!! return render(request, "encyclopedia/search.html", { "matches": matches })