Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker remote shell via websocket
I have a Django application and a Docker Setup running. I'm trying to achieve that a user of the Django application can remotely connect to a container via websocket and get a shell inside his browser, so he needs no additional setup etc.. My initial thought something like: The user send a request for container X to Django. Django checks if the user is authenticated etc. Django calls docker Docker opens a socket Django returns socket to Frontend (User) To test this process, I tried something like: import docker client = docker.from_env() container = client.containers.get("Id of conainer X") result = container.exec_run(cmd="/bin/bash", stdout=True, stdin=True, stderr=True, tty=True, socket=True) Here begins my struggle. The PyCharm Debuggers tells me, that result[1] (I assume is the socket for stdin?) is of type:socket.SocketIO How can i open a shell in my Frontend with that socket? I've looked at Portainer and a tool called docker-box, but they both use a strange Golang method to hijack the connection? Here is the code of the docker-box tool: func ExecContainer(ws *websocket.Conn) { container := ws.Request().URL.Path[len("/exec/"):] if container == "" { ws.Write([]byte("Container does not exist")) return } type stuff struct { Id string } var s stuff params := bytes.NewBufferString("{\"AttachStdin\":true,\"AttachStdout\":true,\"AttachStderr\":true,\"Tty\":true,\"Cmd\":[\"/bin/bash\"]}") resp, … -
Styling django IntegerField form field width
I'm trying to style the quantity column. As you can see from the screenshot below the input field is wider than expected by default. How do I customize the forms.IntegerField() ? UI screenshot forms.py class CartAddProductForm(forms.Form): quantity = forms.IntegerField() override = forms.BooleanField(required=False,initial=False,widget=forms.HiddenInput) html <td> <div class="input-append"> <form action="{% url "cart:cart_add" product.id %}" method="post"> {{ item.update_quantity_form.quantity }} {{ item.update_quantity_form.override }} <input class="btn btn-mini" type="submit" value="Update"> {% csrf_token %} </form> </div> </td> -
python AttributeError 'dict' object has no attribute
I get following error: AttributeError at /filterrule/createresultset/ 'dict' object has no attribute 'filter_query_json' Here's the code: from django.db import connections def fetch_filter_rule_sql_from_ui_db(filter_rule_id): with connections['frontend'].cursor() as cursor: query = "SELECT id, filter_query_json FROM dmf_filter_rules WHERE id=%s LIMIT 1" cursor.execute(query, [filter_rule_id]) filter_rule_sql_json = dictfetchall(cursor)[0].filter_query_json # filter_rule_sql_json = dictfetchall(cursor)[0][filter_query_json] return filter_rule_sql_json def dictfetchall(cursor): "Return all rows from a cursor as a dict" columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for row in cursor.fetchall() ] The output to dictfetchall(cursor)[0] is: { "id": 1, "filter_query_json": "{\"request_id\":\"341\",\"match_status\":\"1\",\"verdict\":\"Non Match\",\"matched\":\"s_vs_r_image_class_match\"}" } Object looks fine to me and I confirmed the filter_query_json attribute too. What is missing? -
Django Haystack SearchQuerySet returns none using solr
I'm making use of Django haystack for my blog with solr as my search engine. I have also setup my solr(version 6.6.6) properly and all query are showing on the solr website. But when I make use of the SearchQuerySet it returnss none upon query. I have included code below. views.py from django.shortcuts import render, redirect from django.urls import reverse_lazy from django.views import generic from blog.views import Post from django.views.generic.base import TemplateView from haystack.query import SearchQuerySet import logging logger = logging.getLogger(__name__) class Search(TemplateView): template_name = 'blog/post_search.html' def get(self, request, **kwargs): query = request.GET.get('query', '') results = SearchQuerySet().models(Post).filter(content='query').load_all() total = results.count() return render(request, self.template_name, {'results':results, 'total':total}) search_indexes.py from haystack import indexes from blog.models import Post class PostIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) publish = indexes.DateTimeField(model_attr='publish_date') def get_model(self): return Post def index_queryset(self, using=None): return self.get_model().objects.published() settings.py """ Django settings for radd project. Generated by 'django-admin startproject' using Django 3.0.5. 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__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ SITE_ID = 1 ALLOWED_HOSTS … -
I would like to manipulate the data from the views to / render (html) in Django
I have this view using generic in django and I need to manipulate it. But it seems that whenever I tried using setattr it doesn't manipulate/replace the data in the queryset. view.py class ArticleListView(ListView): #using the Generic ListView in django template_name = 'article/article_list_view.html' queryset = Article.objects.all()[:5] def get(self, request, *args, **kwargs): setattr(self.queryset[0], 'title', 'something') #Trying to change the title in the first element print(getattr(self.queryset[0], 'title')) #it outputs the old value return super().get(request, *args, **kwargs) article_list_view.html {% extends 'base.html' %} {% block content %} {% for instance in object_list %} <h5>{{instance.title}}</h5> {% autoescape off %} <p>{{instance.content| capfirst}}</p> {% endautoescape %} {% endfor %} {% endblock content %} Do you have any idea to solve this issue? -
Django channels without javascript?
I am trying to create a chat app in Django using channels but the official tutorial in Django documentation uses javascript and jQuery. I am not quite familiar with them so can anyone give me a source from which I can learn how to use channels without javascript? Thank you! -
Reference ForiegnKey of one-to-many relatioship
i need some help for my project. I want to update and add an additional address to the Address model. i was able to update the address or edit the address but implementing the add additional address my cod seems not to be working. Here is my HTML form. update_address.html {% extends "livestock/livestock_base.html" %} {% load crispy_forms_tags %} {% block livestock%} <div class="card-body"> <div class="row"> <div class="col-md-6 offset-3 "> <form class="" action=" " method="POST"> {% csrf_token %} <div class="row"> <div class="form-group col-md-8 "> {{form.street_name | as_crispy_field}} </div> <div class="form-group col-md-4"> {{form.street_no | as_crispy_field}} </div> </div> <div class="row"> <div class="form-group col-md-6 "> {{form.city | as_crispy_field}} </div> <div class="form-group col-md-6"> {{form.state | as_crispy_field}} </div> </div> <div class="form-group col"> {{form.country | as_crispy_field}} </div> <div class="row"> <div class="form-group col-md-6"> <input type="submit" class="btn btn-primary btn-block btn-sm" name="update" value="Update" /> </div> <div class="form-group col-md-6"> <input type="submit" class="btn btn-primary btn-block btn-sm" name="newaddress" value="Additional Address"/> </div> </div> </form> </div> </div> {% endblock livestock%} The user will edit and update the address otherwise they can add additional address. Here is my views.py def update_adress(request, id): address = Address.objects.get(pk = id) form = forms.AddressCreateForm(instance=address) if request.method == 'POST' and 'update' in request.POST: farm = Address.objects.get(pk=id) form = forms.AddressCreateForm(request.POST, instance=farm) *elif … -
Pre_save in model class: missing 1 required positional argument: 'self'
I want to save an attribute numeric_software_version in my Device model in pre_save. @receiver(pre_save) def save_numeric_update_version(self, sender, *args, **kwargs): if self.software_version: if not self.numeric_software_version: self.numeric_software_version = self.numeric_version( self.software_version ) super(Device, self).save(*args, **kwargs) Now when I test it (run migrations), I get following error: File "/usr/local/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp> for receiver in self._live_receivers(sender) TypeError: save_numeric_update_version() missing 1 required positional argument: 'self' I tried several other approaches but can't find a solution. -
How to validate django username in real-time using vuejs?
I have seen that django raise "username already exists" error after I click the sign up button which is very annoying considering I have to fill the form again. -
Is it a good idea to use cache and how to use it for 4000-10000 data rows in Django for a single page?
Django 2.2 I need to fetch 4000-10000 data rows from a particular datatable (let's call this commonsites) amongst others to display a webpage. I can narrow down to just 3 fields of these 4000-10000 rows (id, name, business_id) My traffic is low. But i was wondering whether it's a good idea to use caching to fetch these 4000-10000 rows The data for these rows are unlikely to change. But in case they do change or get deleted, how do I update/remove individual rows in the cache, rather than the entire cache? Or is this even a good idea? My installs are : redis==3.3.11 # https://github.com/antirez/redis django-redis==4.11.0 # https://github.com/niwinz/django-redis -
Get uploaded file size in Flask
I am new in flask and making a small application. I uploaded some images to image/upload folder. I can able to see all the images from client side but I also want to get the uploaded image size . How can I do that ? here is my routes.py import os import hashlib import time from PIL import Image from file_counter_app import app, photos from file_counter_app.form import UploadForm from flask import render_template, request,url_for,redirect,flash @app.route('/') @app.route('/home') def home(): return render_template('home.html') @app.route('/about') def about(): return render_template('about.html') @app.route('/contact') def contact(): return render_template('contact.html') @app.route('/upload_picture', methods=['GET', 'POST']) def upload_picture(): form = UploadForm() if form.validate_on_submit(): for filename in request.files.getlist('photo'): str_name = 'admin'+str(int(time.time())) name = hashlib.md5(str_name.encode('utf-8')).hexdigest()[:15] photos.save(filename, name=name + '.') success = True return redirect(url_for('upload_picture')) return render_template('upload.html',form=form,) @app.route('/details') def show_details(): files_list = os.listdir(app.config['UPLOADED_PHOTOS_DEST']) return render_template('details.html', files_list=(files_list)) details.html {% extends 'layout.html' %} {% block content %} <h1>File Manager</h1> <hr> {% for photo in files_list %} {{ photo }} {% endfor %} {% endblock %} form.py from file_counter_app import photos from flask_wtf import FlaskForm from flask_wtf.file import FileField,FileRequired,FileAllowed from wtforms import SubmitField #class form for image upload class UploadForm(FlaskForm): photo = FileField(validators=[FileAllowed(photos,'Image Only!'),FileRequired('Choose a file')]) submit = SubmitField('Upload') -
sqlite3.OperationalError: unable to open database file when running dDango test coverage inside a docker container
Hello I have seen many questions with this title but I couldn't fix my issue with any of the answers. I'm setting up a Django project within a docker container but I also want to run the test coverage inside the docker container because my app is using PostgreSQL database which is also configured in Docker. Basically when I run the command docker-compose run web sh -c "coverage run manage.py test && coverage report"` ``locally it works fine but the same command does not work onTravis ci``` Here is the error I get when the same command runs on Travis Traceback (most recent call last): File "/usr/local/bin/coverage", line 8, in <module> sys.exit(main()) File "/usr/local/lib/python3.8/site-packages/coverage/cmdline.py", line 827, in main status = CoverageScript().command_line(argv) File "/usr/local/lib/python3.8/site-packages/coverage/cmdline.py", line 555, in command_line return self.do_run(options, args) File "/usr/local/lib/python3.8/site-packages/coverage/cmdline.py", line 710, in do_run self.coverage.save() File "/usr/local/lib/python3.8/site-packages/coverage/control.py", line 649, in save data = self.get_data() File "/usr/local/lib/python3.8/site-packages/coverage/control.py", line 703, in get_data if self._collector and self._collector.flush_data(): File "/usr/local/lib/python3.8/site-packages/coverage/collector.py", line 425, in flush_data self.covdata.add_lines(self.mapped_file_dict(self.data)) File "/usr/local/lib/python3.8/site-packages/coverage/sqldata.py", line 437, in add_lines self._choose_lines_or_arcs(lines=True) File "/usr/local/lib/python3.8/site-packages/coverage/sqldata.py", line 494, in _choose_lines_or_arcs with self._connect() as con: File "/usr/local/lib/python3.8/site-packages/coverage/sqldata.py", line 299, in _connect self._create_db() File "/usr/local/lib/python3.8/site-packages/coverage/sqldata.py", line 248, in _create_db with db: File "/usr/local/lib/python3.8/site-packages/coverage/sqldata.py", line 1026, in … -
How to display images uploaded from django admin to heroku?
I deployed my django project on heroku. The site is all working well except for the fact that some images are not displayed on the site. These images are all images which I uploaded to my site in local server via the django admin. These images were uploaded to my site on local server by providing the url in image field in django admin page. All the images which are hard coded in the html code and are static/images folder in my project are displayed. Any changes I should make to my settings.py file to dipslay these pictures? How to resolve this? My settings.py file """ Django settings for ecommerce project. Generated by 'django-admin startproject' using Django 2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/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/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'gm1zyhprh9=9+4@vu*^8g30(pg*xq6e@0z1)h81hc2evd7n*^v' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['market-shaurya.herokuapp.com', '127.0.0.1'] # Application definition INSTALLED_APPS … -
Django and jQuery, how to manage class container?
I have the following jQuery code: var delButtonHTML = '<a class="' + options.deleteCssClass + '" href="javascript:void(0)">' + options.deleteText +'</a>'; if (options.deleteContainerClass) { // If we have a specific container for the remove button, // place it as the last child of that container: row.find('[class*="' + options.deleteContainerClass + '"]').append(delButtonHTML); } else if..... $.fn.formset.defaults = { addContainerClass: null, // Container CSS class for the add link}; So I dont understand how set this container in my html template to get place my remove button properly. Someone could I help me? -
How to send data from local postgresql db to heroku postgres db
I have developed a Django web app with PostgreSQL. I was able to deploy my app to heroku server and also installed heroku PostgreSQL addon to it. No i am trying to send Blogs, Posts which in entered through Django Admin panel How will I Set up these information's in it -
How can I get simple Lightbox to show that scaling effect when hovering over an image
I have little experience with javascript and I am now building a little site with Django. Then I stumbled upon a site that mentioned SimpleLightbox. So, here is what I got: {% block content %} {% load static %} {% static "../" as baseURL %} <!-- findet er beide noch nicht --> <link rel="stylesheet" href="{% static 'photo/css/simple-lightbox.min.css' %}"> <script type="text/javascript" src="{% static 'photo/js/simple-lightbox.jquery.min.js' %}"></script> <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"> <h2 class="page-header-tuesday">Bilder Galerie</h2> <div class="row"> <div class="col-sm-6 col-sm-offset-0 col-md-7 col-md-offset-0 text-mainframe"> <br> <div class="gallery"> {% load photo_tags %} {% if images %} {% for image in images %} {% with image|split:'.' as strs %} {% with strs|length as str_arr_len %} {% with str_arr_len|add:'-1' as ext_idx %} {% if strs|get_by_index:ext_idx == 'jpg' %} <a href="{{ MEDIA_URL}}ObjPDW2/bilder/{{ image }}"> <img src="{{ MEDIA_URL }}ObjPDW2/bilder/{{ image }}" alt="{{ image }}"> </a> {% endif %} {% endwith %} {% endwith %} {% endwith %} {% if forloop.counter|divisibleby:4 %} <div class="clear"></div> {% endif %} {% endfor %} {% else %} <p>No image available.</p> {% endif %} </div> <script type="text/javascript"> $(document).ready(function() { $('.gallery a').simpleLightbox(); }); </script> </div> <div class="col-md-4 col-sm-4 col-md-offset-1"> <br> </div> </div> </div> {% endblock %} I can see the test image that I have … -
How to use my existing csv file to django python? [closed]
How to use my existing csv file to django python? i tried placing the csv file in the outer folder with views.py and I thought its just like that but when I tried to get the data in csv file it gives me error. so can you give a tutorial or step by step on how to use my csv file and use the data and output it in html. -
Django. How to find out a user liked a post or didn't?
I have 2 models. Product and Favorite (its kind of like) Favorite has relationship to product and user. I need to check in templates do a user have relationship with a product for inserting like or unlike button. class Favorite(models.Model): """User favorite products""" user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='favorites') product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='favorites') class Product(models.Model): """Store product""" ... In template I have: {% for product in products %} ... I'd think i can do it like that {% if product in user.favorites.all %} But i dont know how to get all favorite products instead of favorites How i can solve it in templates? -
Django, bulk_create or bulk_update with manytomanyfield?
With the following models, class Song(models.Model): name = models.CharField(max_length=10) class Album(models.Model): songs = models.ManyToManyField(Song, through=AlbumSong) class AlbumSong(models.Model): song = models.ForeginKey(song) album = models.ForeginKey(album) I want to do bulk_create albums with songs (following code doesn't work because songs field can't be set as it is) albums = [ Album( songs=[1,2] ), Album( songs=[3,5] ) ] Album.objects.bulk_create(albums) I also want to bulk_update with songs set to list of values albums = Album.objects.some_filter() for album in albums: album.songs = [1,2] Album.objects.bulk_update(albums) I can do bulk_create on AlbumSong through table, but it's harder with bulk_update where you might have to remove some songs from albums. (unless you delete rows from AlbumSong and inserts [1, 2]) -
Pythonanywhere: how to run slq script for db sqlite?
I have deployed a Django project on Pythonanywhere. I have a db.Sqlite3 database and I need to initiailze this database with a sql script. I could not find how to do this in pythonanywhere and did not find any help on forums. Is it possible (I think it is...) ? -
Why does Django log out a user after login() after redirect
I am using Django and Wagtail but I think this is more specifically a Django problem. When someone needs to reset their password because they have forgotten it I email them out an activation link. The problem is that even though the activation link passes and I login them in with django.contrib.auth.login as soon as I redirect them to another page they are logged out again. I have tried setting SESSION_COOKIE_SECURE = False but this has made no difference for me. I am using Django 2.2 and Wagtail 2.8. This is happening on both my development server (python manage.py runserver) and the production uwsgi server. I've been pulling my hair out over this one so if any bright person can point me in the right direction would be appreciated. @route(r'^activate/([\w-]+)/([\w-]+)/$') def activate(self, request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = get_user_model().objects.get(id=uid) except(TypeError, ValueError, OverflowError, get_user_model().DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): login(request, user) url = self.url + self.reverse_subpage('password_change', args=(user.pk,)) return redirect(url) # weirdly logs out the user immediately else: return HttpResponse('Activation link is invalid!') -
python call child method from parent method
Here's the idea: I have a "base" class called AdBase and I want a "generic" method like "get_infos()". From there I can have many child classes: AdRealEstate(AdBase), AdCar(AdBase), AdTrading(AdBase), etc. From there I have a model: Clip that has a link to AdBase, like this! class AdBase(BaseModel): title = models.CharField(max_length=200, default=None, null=True, blank=False) def get_infos(self, max_len=55): return [self.title] class AdRealEstate(AdBase): price = MoneyField(max_digits=19, decimal_places=0, default=0, null=True, blank=False, default_currency='EUR') def get_infos(self, max_len=55): result = super().tab_infos() result.extend([_("Price: {}").format(str(self.price) or ''),]) return result class Clip(BaseModel): ads = models.ManyToManyField(AdBase, related_name='clips', through='ClipAd') I just want to do something like: for ad in Clip.object.get(pk=1).ads.all(): print(ad.get_infos()) The problem is that ad in the loop can be AdRealEstate, AdCar, AdTrading, etc. so I would like to call the get_infos() of the children, and it only calls get_infos() of AdBase. What is the generic way to make ad.get_infos() based on the class? -
SearchQuerySet Returns None with haystack solr
SearchView keeps returning none with filter tag. Is there anyway I can get content? -
Let user switch between weeks to show different data in template - Django
I'm building a planning tool/dashboard where a user can plan standardized activities to reach their weekly planning target. Because it's a weekly planning, I'm showing the current week by default atm. I want the user to be able to switch weeks to see their future and previous plannings, but I'm not sure now how to switch from the current week to future or previous ones in the table... Completely new to coding and Django, so would be awesome if someone could help me out! models.py class PlanningActivity(models.Model): name = models.CharField(max_length=255) is_billable = models.BooleanField() is_auto_realised = models.BooleanField() strd_duration = models.PositiveIntegerField() def __str__(self): return self.name class Planning(models.Model): added_by = models.ForeignKey( User, related_name='planning_activity', on_delete=models.DO_NOTHING ) activity = models.ForeignKey( PlanningActivity, on_delete=models.DO_NOTHING ) date = models.DateField() note = models.CharField(max_length=255, blank=True) def __str__(self): return str(self.id) class UserContract(models.Model): assigned_user = models.ForeignKey( User, on_delete=models.DO_NOTHING ) organisation = models.CharField(max_length=255) function = models.CharField(max_length=255) team = models.CharField(max_length=255) hrs_per_week = models.PositiveIntegerField() planning_target = models.PositiveIntegerField() beginning_date = models.DateField() ending_date = models.DateField() @property def Target(self): return (self.hrs_per_week * (self.planning_target/100)) def __str__(self): return str(self.assigned_user) views.py def home(request): planning_form = PlanningForm(request.POST) current_week = date.today().isocalendar()[1] if request.user.is_authenticated: planning = Planning.objects.filter(added_by=request.user, date__week=current_week).select_related('activity').order_by('-date') total_planned_current_week = Planning.objects.filter(added_by=request.user, date__week=current_week).select_related('activity').aggregate(Sum('activity__strd_duration'))['activity__strd_duration__sum'] total_planned = Planning.objects.filter(added_by=request.user).select_related('activity').aggregate(Sum('activity__strd_duration'))['activity__strd_duration__sum'] contracts = UserContract.objects.filter(assigned_user=request.user) if total_planned == None: return redirect('/first_planning') … -
Django and jQuery.formset, how to manipulate delete button position
I'm trying to set my formset in django, using the famous jQuery plugin jQuery.formset.js All works perfectly, but I have some problem to set the right position of the delete button. Now it is set in the last column of my table, like in the following figure: But my aim is to replace the delete button in the same line of the the add button (+). I have found in the code the following instructions, but I don't now how could set it for my aim: var delButtonHTML = '<a class="' + options.deleteCssClass + '" href="javascript:void(0)">' + options.deleteText +'</a>'; if (options.deleteContainerClass) { // If we have a specific container for the remove button, // place it as the last child of that container: row.find('[class*="' + options.deleteContainerClass + '"]').append(delButtonHTML); } else if (row.is('TR')) { // If the forms are laid out in table rows, insert // the remove button into the last table cell: row.children(':last').append(deleteButtonHTML); } else if (row.is('UL') || row.is('OL')) { // If they're laid out as an ordered/unordered list, // insert an <li> after the last list item: row.append('<li>' + deleteButtonHTML + '</li>'); } else { // Otherwise, just insert the remove button as the // last child element …