Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make multilang posts? - django | ideas
I have a blog on English. I need to make multilang posts. Do I need to add russian fields in post create or can it be a simpler way? How to implement it? Your ideas. I'll hope you understand the question. -
Need help forming queryset with multiple aggregates
I have the following model defined: class TestCaseResult(models.Model): run_result = models.ForeignKey( RunResult, on_delete=models.CASCADE, ) name = models.CharField(max_length=128) duration = models.DurationField(default=datetime.timedelta) result = models.CharField( max_length=1, choices=(('f', 'failure'), ('s', 'skipped'), ('p', 'passed'), ('e', 'error')), ) I'm trying to get, in a single query, the count of each kind of result for a given run_result, along with the sum of the durations for the test cases with that result. This gives me the count of each type of result, but I can't figure out how to get the sum of the durations included. qs = TestCaseResult.objects.filter(run_result=run_result).values('result').annotate(result_count=Count('result')) I basically want this as the resulting SQL: SELECT "api2_testcaseresult"."result", SUM("api2_testcaseresult"."duration") AS "duration", COUNT("api2_testcaseresult"."result") AS "result_count" FROM "api2_testcaseresult" WHERE "api2_testcaseresult"."run_result_id" = 3 GROUP BY "api2_testcaseresult"."result"; Note how 'duration' is not part of the 'group by' clause. -
I have an a problem with HTML video player
Well I tried to made my own videoplayer(add my buttons scrollbar and etc) when I start site it show only pics This is my main html file, and my css: <!DOCTYPE html> <head> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css"> <!-- jQuery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> {% load staticfiles %} <link rel = "stylesheet" type = "text / CSS" href = "video-player.css"> </head> <body> <img src="{% static 'accounts/image/gogi.jpg' %}" class="img-responsive center-block"> <div id="video-player"> <video poster="image/127.jpg" width="1280" height="720" controls> <source src="{% static 'accounts/vid/1224.mp4' %}" type="video/mp4"> </video> <div id="progress-tree"> <div id="progress"></div> </div> <div id="button-tree"> <img id="play-button" src="{% static 'accounts/image/2712.png' %}" width="100" height="100"> <div id="time-factor"> 0:00 / 0:00 </div> <img id="backward-button" src="{% static 'accounts/image/backward.png' %}" width="100" height="100"> <div id="soundbar-tree"> <div id="soundbar" width="100" height="100"></div> </div> <img id="forward-button" src="{% static 'accounts/image/forward.png' %}" width="100" height="100"> </div> </div> and this is css file #video-player{ background-color: aquamarine; display: inline-block; } img{ background-color: Aqua; } #video-tree{ width: 640px; height: 640px; } video{ height: 100%; width: 100% } #progress-tree{ background-color: CadetBlue; } #progress{ height: 5px; width; 50%; background-color: Black; } #button-tree{ height: 50px; } #button-tree > * { display: inline-block; height: 50px; … -
How to click a button on my Django Interface and start a python script
I am working on my first webapp using Django (Python 3), and I have a python script that already plots data using matplotlib with no problem. However I want to place a button in a webapp to simply trigger my plotting script to run. I have looked for tutorials online, but they are mostly unclear and only show css options and javascript options. If it's possible, is there a way to do this? My code is fairly simple right now and I am using a dummy script just for testing. I have a scripts folder in my webapp directory with the test script in it, but I can't find a way to run it. urls.py: from django.urls import path from django.conf.urls import include,url from . import views app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ####My first attempt was the line below##### url(r'^polls/scripts/_stocks_automation.py', views.IndexView, name='chart') ] index.py: {% if latest_question_list %} <!--my test button --> <button id="runScript_btn" type="button" style="height:100px;width:100px" action="chart"></button> <h1>"Le Duh"</h1> <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif … -
Django can't save new instance to model
I cannot save the data taken from the form to database. The form is displayed properly and it seems that I can submit. Whenever I was redirected to "project_list.html", I cannot see the new project. I also checked the admin site to whether new instance is saved to model but it seems that something is wrong with my code. Here is my files: model.py class Project(models.Model): project_id = models.CharField(max_length=30) project_name = models.CharField(max_length=100) view.py def project_add(request): if request.method == 'POST': form = ProjectAddForm(request.POST) if form.is_valid(): form.save() return redirect('project_list',) else: form = ProjectAddForm() return render(request, 'portal/project/add.html', {'form': form}) forms.py from django import forms from .models import Project class ProjectAddForm(forms.ModelForm): class Meta: model = Project fields = ['project_id', 'project_name',] add.html {% extends 'portal/base.html' %} {% block title %}Add Project{% endblock title %} {% block content %} <div class="col-sm-10 offset-sm-1 text-center"> <form action="{% url 'portal:projects_list' %}" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> </div> {% endblock content %} -
Printing in Django Template a Pandas dataframe with dynamic indexes and columns
I have a script that creates dataframe with dynamic indexes values and name of the columns, as well as the number of columns. The only fixed value is the name of the index column that is "Transaction". Below an example. I am passing this dataframe from a Django view to a Django Template, but I don't know how to access, in the template, the values of it. def myFunction(request): df = myDfFunction() #returns the dataframe return render(request, 'reports/my_page.html', {'df': df}) In the template I am trying to access it in many ways, without success. <html> <head> <title>Page Title</title> </head> <body> {% for row in df %} <p> {{ row[0][0] }} </p> {% endfor %} </body> -
How to render view from differents apps in the same template?
I have two apps (blog ans category). on the post list template i'd like to get the category blog name and description. I have tried to put import category model in blog view but noting show up. So i have made 2 views rendering the same template but it does not work. //blog models from django.db import models from django.utils import timezone from autoslug import AutoSlugField from category.models import Category class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE, default='') title = models.CharField(max_length=200) ... class Meta: verbose_name = "Post" verbose_name_plural = "Posts" ordering = ['created_date'] def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title // Category models class Category(models.Model): name = models.CharField(max_length=200) slug = AutoSlugField(populate_from='name', default='') parent = models.ForeignKey('self',blank=True, null=True ,related_name='children', on_delete=models.CASCADE) description = models.TextField(max_length=200) class Meta: unique_together = ('slug', 'parent',) #enforcing that there can not be two verbose_name_plural = "categories" #categories under a parent with same #slug def __str__(self): # __str__ method elaborated later in full_path = [self.name] # post. use __unicode__ in place of # __str__ if you are using python 2 k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) //Blog view def post_list(request): posts = Post.objects.all() context … -
Is there a way to capture video from a usb camera with multiple processes in Python using cv2?
I'm making a django project which will run on a Raspberry Pi 3. The Pi has an attached USB camera. One of the web pages in my project will show a video feed from the camera. The way I access the camera is by using code borrowed from here, which looks like this: from django.http import StreamingHttpResponse, HttpResponseServerError from django.views.decorators import gzip import cv2 class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) def __del__(self): self.video.release() def get_frame(self): ret,image = self.video.read() ret,jpeg = cv2.imencode('.jpg',image) return jpeg.tobytes() def gen(camera): while True: frame = camera.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @gzip.gzip_page def view_cam(request): try: return StreamingHttpResponse(gen(VideoCamera()),content_type="multipart/x-mixed-replace;boundary=frame") except HttpResponseServerError as e: print("aborted") It works great, except for the fact that only a single instance of django can view the video stream at a time. If another process already ran cv2.VideoCapture(0) and you run it again, that method call will block until the other process releases the lock with .release(). As far as I can tell, this essentially means that you can only have one browser watching the video feed at any given time. Is this some sort of inherent limitation of watching a USB camera feed? Do I need some sort of single … -
How can I open Django app page within the domain name, not like domain/app_page_url?
Python == 3.6.5 Django == 1.8 Recently purchased domain name, http://www.favourite.uz. And placed my Django project to my hosting in cPanel. When I browse domain http://www.favourite.uz, it throws to default page of cPanel. But when try http://www.favourite.uz/news it opens my django app. I wanted to browse this http://www.favourite.uz/news page within the domain name, without /news. I placed used server's namespaces in Domain registrator's page. Tried to create another simple project from this tutorial,https://www.youtube.com/watch?v=ffqMZ5IcmSY. But it still opens default page of cPanel. Main favourite/urls.py # from django.urls import path from django.conf.urls import include, url from django.conf import settings from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.static import serve urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^news/', include('news.urls')), url(r'^i18n/', include('django.conf.urls.i18n')), ] if settings.DEBUG is False: urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, { 'document_root' : settings.MEDIA_ROOT,}), ] (news)app url, news/urls.py from . import views urlpatterns =[ url(r'^$', views.NewsView.as_view(), name='posts'), url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^index', views.search, name="search"), url(r'^chaining/', include('smart_selects.urls')), url(r'^league/(?P<pk>[0-9]+)/$', views.league_detail, name='league_detail'), ] settings, favourite/settings.py Django settings for futbik_version_7 project. Generated by 'django-admin startproject' using Django 2.0.5. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os from django.utils.translation import ugettext_lazy as _ # Build … -
IndentationError: unindent does not match any outer indentation level in django developing
When i compile the following code snippet it throws an error... formfield_overrides= { models.TextField: {'widget': TinyMCE()}, } IndentationError: unindent does not match any outer indentation level -
400 Bad Requests under Nginx + Gunicorn for Django graphene
I built a website with ssl cert serverd by Django, Gunicorn and Nginx. After that, I add graphene to Django and config the api call. Unfortunately, I can only query by this link using GET instead of POST. Here is the Nginx config: server { listen 80; server_name _; return 301 https://$host$request_uri; } server { listen 443 ssl; server_name mydomain.com www.mydomain.com 123.123.123.123; ssl_certificate /etc/letsencrypt/live/mydomain/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/mydomain/privkey.pem; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; ssl_trusted_certificate /etc/letsencrypt/live/mydomain/chain.pem; location ~ ^/favicon\.ico$ { root /var/www/mydomain/static; } location /static/ { root /var/www/mydomain/; } location /media/ { root /var/www/mydomain/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } And here is the gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=user Group=www-data WorkingDirectory=/home/user/mydomain ExecStart=/usr/local/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ mydomain.wsgi:application [Install] WantedBy=multi-user.target nginx/1.14.0 django/2.1.5 graphene-django/2.2.0 gunicorn/19.9.0 Please give me a help. -
Django 2 implement Other user's Profile View
I'm working on a project using Python(3.7) and Django(2.1) in which I need to implement a view for users to view other user's profile, I have implemented the view, it shows the profile but displaying the profile information. Here what I have tried: From models.py: class ProfileModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='profile') avatar = models.CharField(max_length=500, null=True, blank=True) about = models.CharField(max_length=1000, null=True) slogan = models.CharField(max_length=500, null=True) profile_pic = models.ImageField(default='/assets/images/avatar.png', upload_to='profile_pics', null=True) def __str__(self): return self.user.username From views.py: class UserProfile(LoginRequiredMixin, CreateView): def get(self, request, *args, **kwargs): username = self.kwargs['username'] user_profile = ProfileModel.objects.filter(user=User.objects.get(username=username)) gigs = Gig.objects.filter(user__username=username, status=True) print(user_profile.values()) return render(request, 'jobexpertapp/profile.html', {'user_profile': user_profile, 'gigs': gigs, 'name': username}) From templates/profile.html: {% if name == user.username %} #, In this case, I will add a, `edit` button and display other info # the info in this case id displaying correctly {% else %} # Here I need to display other user's info e.g <h1> {{ user_profile.slogan }}</h1> -
Is it possible to render 2 queryset in ListView?
I am new to django and recently read a tutural that describes the usage of class based view. But when I try to render 2 different queryset (all data and filterd data) to the same template, I can't find the solution for display 2 different queryset. Can anyone suggest the best solution about this? I know writing the function based view is much easy for this, but I hope it can be done by Class based view, thank you #in view.py from django.views.generic import ListView from books.models import Book class BookListView(generic.ListView): model = Book context_object_name = 'my_book_list' queryset = Book.objects.all() template_name = 'books/my_arbitrary_template_name_list.html' # queryset = Book.objects.filter(title='war')? #in templage.py #Main content <div class="main_content"> <h1>All War</h1> <ul> {% for book in book_list %} <li> {{book.title}} </li> {% for endfor %} </ul> </div> #Sidebar <div class="sidebar"> <h1>All War</h1> <ul> {% for book in book_list %} <li> {{book.title}} </li> {% for endfor %} </ul> </div> -
Django: ValueError during migration (how to fix???)
I have 2 classes. Student and parent. The parent class links to the student class via a models.ForeignKey(Student, on_delete=models.CASCADE) When running makemigrations django asked whether I wanted to input because there was no default. So I input "defult". Turns out it wanted a string and now whenever I run migrate C:\Users\Egor\Desktop\mysite>python manage.py makemigrations Migrations for 'main': main\migrations\0028_auto_20190129_2010.py - Alter field student_joined on student C:\Users\Egor\Desktop\mysite>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, main, sessions Running migrations: Applying main.0007_auto_20190129_1732...Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\Egor\AppData\Local\Programs\Python\Python37\lib\site- packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Egor\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Egor\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Egor\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\Egor\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Egor\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\migrate.py", line 203, in handle fake_initial=fake_initial, File "C:\Users\Egor\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Egor\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\Egor\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\Egor\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\Egor\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards field, File "C:\Users\Egor\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\sqlite3\schema.py", line 309, in add_field … -
Django: render image from static folder in admin
I need to render a thumbnail image for all my files uploaded in Admin. I'm using the logo of Adobe Illustrator to show that the files are indeed AI files. However, it is not beeing rendered. In the HTML I get: <img src="static/img/admin/adobe_illustrator_file_logo.png" width="200px" height="180px"> That renders like this: Why? class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) product = models.CharField(max_length= 200) quantity = models.CharField(max_length= 200) size = models.CharField(max_length=200) price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name= 'PEN Price') file = models.FileField(upload_to='files', blank=True, null=True) comment = models.CharField(max_length=200, blank=True, null=True, default='') uploaded_at = models.DateTimeField(auto_now_add=True) class Meta: db_table = "OrderItem" def file_thumbnail(self): if self.file: return mark_safe(u'<img src="%s" width="200px" height="180px" />' % ('static/img/admin/adobe_illustrator_file_logo.png')) else: pass -
Django + pipenv + Apache + mod_wsgi deployment on ubuntu not loading modules
I'm trying to deploy django project on Ubuntu server using apache and mod_wsgi. I'm using python3 and pipenv to manage venv. Environment variable PIPENV_VENV_IN_PROJECT=True so that venv created by pipenv is located inside the project folder. This is the project structure: /srv/project | |-.venv # venv creted by pipenv | |-bin | |-... | |-Pipfile |-Pipfile.lock | |-django_app | |-manage.py |-... | |-django_app | |-settings.py |-... |-wsgi.py Apache VirtualHost configuration (/etc/apache2/sites-available/000-default.conf): <VirtualHost *:80> <Directory /srv/project/django_app/django_app> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess django_app python-home=/srv/project/.venv python-path=/srv/project/django_app WSGIProcessGroup django_app WSGIScriptAlias / /srv/project/django_app/django_app/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> Apache works fine and responds correctly, until I add the WSGI part of the configuration. Then it stops responding (all requests are pending). And same error message keeps repeating in apache error log (/var/log/apache2/error.log) - even when no requests are sent to server: Current thread 0x00007f300f446bc0 (most recent call first): [Tue Jan 29 15:43:58.899091 2019] [core:notice] [pid 16407:tid 139844391300032] AH00051: child pid 22818 exit signal Aborted (6), possible coredump in /etc/apache2 Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' It seems that the process is not able to load modules, probably due to improper venv configuration … -
Django Rest Framewrork viewsets delete nested resources from relationship
I'm building an API with Applications and Servers. An application can have many servers and a server can have many applications. These are my models. class Server(Model): name = TextField(unique=True) description = TextField(blank=True) ip_address = TextField() class Meta: ordering = ["name"] def __str__(self): return self.name class Application(Model): name = TextField(unique=True) description = TextField() is_critical = BooleanField() servers = ManyToManyField(Server, related_name="applications") class Meta: ordering = ["name"] def __str__(self): return self.name These are my serializers. class ServerSerializer(ModelSerializer): class Meta: model = Server fields = "__all__" class ApplicationSerializer(ModelSerializer): servers = ServerSerializer(many=True, read_only=True) class Meta: model = Application fields = "__all__" I'm using DRF's Viewsets. class ServerViewSet(ModelViewSet): queryset = Server.objects.all() serializer_class = ServerSerializer class ApplicationViewSet(ModelViewSet): queryset = Application.objects.all() serializer_class = ApplicationSerializer @action(detail=True, methods=["HEAD", "GET", "POST", "DELETE"]) def servers(self, request, pk=None): """Relate a server to the application""" application = self.get_object() if request.method in ("HEAD", "GET"): s_servers = ServerSerializer(application.servers, many=True) return Response(s_servers.data) else: server_id = request.data.get("id") if not server_id: return Response( "Server details must be provided", status=HTTP_400_BAD_REQUEST) server = get_object_or_404(Server, id=server_id) if request.method == "POST": application.servers.add(server) return Response( "Server added to the application", HTTP_201_CREATED) elif request.method == "DELETE": application.servers.remove(server) return Response( "Server removed from the application", HTTP_204_NO_CONTENT) I would like servers to be unique and applications … -
MultiValueDictKeyError when deleting related inline records in another tab
I'll try to be as concise as possible. Background I have a model Person which has a ForeignKey to model Document. Each Person can only have one Document but, as you may already know, each Document can be linked to many Persons. In the Document's Admin form I have the Persons associated to the Document displayed inline. I can edit, add or delete the Persons right there. Problem Following these steps I get the error: I open the Admin edit form for a Document. Let's call it Document A. This Document has two Persons associated, let's call them John Doe and Jane Doe. You can see them there (inline) in the form and the fields are editable, but I don't touch them. I open another tab and go straight to the Persons list and delete Jane Doe. I get back to the first tab (the Document's edit form) and click on "Save and continue editing". The form is sent and I get a generic error at the top (something like) "Please, fix the following errors". But the form shows no errors (next to the fields) to correct and, obviously, the record for Jane Doe isn't displayed. I click again on … -
How to reorder dynamic string keys for dictionary to save it to JSON
How to sort the dynamic updated dictionary data every time new keys are updated in the dictionary? It gives me a random order for the keys whenever i try to print the dictionary after updating. Using Sorted function doesn't seem to work in sorting the data dynamically. I keep getting random order whenever new keys are added to dictionary and i need to sort them and update them in JSON formatted data. mydict ={"item_0": "apples"} print(mydict) mydict.update(item_1="banana") print(mydict) mydict.update(item_2="oranges") print(mydict) mydict.update(item_3="peaches") print(mydict) mydict.update(item_4="tangerines") print(mydict) Actual Results {'item_0': 'apples'} {'item_0': 'apples', 'item_1': 'banana'} {'item_2': 'oranges', 'item_0': 'apples', 'item_1': 'banana'} {'item_2': 'oranges', 'item_3': 'peaches', 'item_0': 'apples', 'item_1': 'banana'} {'item_4': 'tangerines', 'item_2': 'oranges', 'item_3': 'peaches', 'item_0': 'apples', 'item_1': 'banana'} Expected Results {'item_0': 'apples'} {'item_0': 'apples', 'item_1': 'banana'} {'item_0': 'apples', 'item_1': 'banana', 'item_2': 'oranges'} {'item_0': 'apples', 'item_1': 'banana', 'item_2': 'oranges', 'item_3': 'peaches'} {'item_0': 'apples', 'item_1': 'banana', 'item_2': 'oranges', 'item_3': 'peaches', 'item_4': 'tangerines'} -
Dynamic success_url in Generic View
I want to make success_url dynamic like instead of giving path success_url =/company/ i want to give path name. Example somewhat like this success_url =superadmin_company_update path('update/<int:pk>/', views.CompanyUpdateView.as_view(), name='superadmin_company_update'), class CompanyUpdateView(LoginRequiredMixin, generic.UpdateView): model = Company success_url = '/company/' template_name = 'company/company_form.html' fields = ['company_name', 'company_description', 'company_email', 'company_website', 'company_address', 'company_phone', 'company_status', 'company_monthly_payment', 'company_logo'] -
How to change date view format? (DJANGO PROJECT)
I am using a postgresql DB and I want to see my dates as dd-mm-YYYY but my project is outputting e.g. Jan. 29, 2019: html: <tr> <td><div style="width:180px">{{ event.week }}</a></div></td> <td><div style="width:200px">{{ event.name }}</div></td> </tr> forms.py: class EventForm2(forms.ModelForm): sunday = forms.CharField(required=False, widget=forms.HiddenInput()) saturday = forms.CharField(required=False, widget=forms.HiddenInput()) week = forms.DateField(input_formats=settings.DATE_INPUT_FORMATS, widget=forms.DateInput(format='%d-%m-%Y')) -
Unit testing Django form with custom file-upload validation logic (not integration testing; no requests/posts/etc.)
I'm looking to unit test some form validation logic in Django, but don't know how to manually input an uploaded file. My form field looks like this: sounds_to_upload = forms.FileField(widget=forms.ClearableFileInput(attrs={"multiple": True})) I've tried: file_info = {"sounds_to_upload": [SimpleUploadedFile("test_sound.wav", test_sound.read())]} file_info = {"sounds_to_upload": SimpleUploadedFile("test_sound.wav", test_sound.read())} file_info = {"sounds_to_upload": SimpleUploadedFile("test_sound.wav", test_sound)} file_info = {"sounds_to_upload": SimpleUploadedFile("test_sound.wav", test_sound.read())} file_info["sounds_to_upload"].size = os.path.getsize(test_sound.name) And many other variations. These will be put into a form like this: form = SoundForm(data=self.sound_info, files=file_info) And, in my form, I've overwritten the clean() method to contain: for sound_file in self.cleaned_data["sounds_to_upload"]: if sound_file.size > 1024*1024: raise forms.ValidationError("File is too large (> 1 mB)") I've also tried for sound_file in self.cleaned_data.get("sounds_to_upload") and cleaned_data = super(SoundForm, self).clean() for sound_file in cleaned_data["sounds_to_upload"]: ... (I've tried all permutations of the various changes outlined above to no avail.) Regardless of what I do, I get the error AttributeError: 'bytes' object has no attribute 'size', so the SimpleUploadedFile itself isn't being accessed, just what's being read from the file. I'm assuming this means I'm using SimpleUploadedFile incorrectly, or populating the files field of the form incorrectly somehow. Please keep in mind that I'm attempting to write a unit test, not an integration test—so I'm avoiding manually sending requests, posting … -
Changes in base.html
I was making some changes in my template/base.html and uploaded in my FTP server and changes I've made are not showing up. What I can do ? Reload the server are not a option. =/ ps. I have ssh access to the server in a normal account. Thanks !! -
Django Channels connection with Web socket
I have implemented the Django Channels as given in the tutorial. The chat works fine and i am able to send and receive messages in a group. But when i try to send a message from a web socket to channels chat it does not display the message. Instead an error is populated. However, i am able to recieve messages from Channels chat to my web socket html page. websocket.html <!DOCTYPE html> <meta charset="utf-8" /> <title>WebSocket Test</title> <script language="javascript" type="text/javascript"> var wsUri = "ws://localhost:8000/ws/power/room/"; var output; function init() { output = document.getElementById("output"); testWebSocket(); testWebSocket(); } function testWebSocket() { websocket = new WebSocket(wsUri); websocket.onopen = function(evt) { onOpen(evt) }; websocket.onclose = function(evt) { onClose(evt) }; websocket.onmessage = function(evt) { onMessage(evt) }; websocket.onerror = function(evt) { onError(evt) }; } function onOpen(evt) { writeToScreen("CONNECTED"); doSend("WebSocket rocks"); } function onClose(evt) { writeToScreen("DISCONNECTED"); } function onMessage(evt) { writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>'); websocket.close(); } function onError(evt) { writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data); } function doSend(message) { writeToScreen("SENT: " + message); websocket.send(message); } function writeToScreen(message) { var pre = document.createElement("p"); pre.style.wordWrap = "break-word"; pre.innerHTML = message; output.appendChild(pre); } window.addEventListener("load", init, false); </script> <h2>WebSocket Test</h2> <div id="output"></div> consumers.py class EchoConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = … -
How to change the value of a button that is in the same class of other buttons?
I have a group of buttons that are assigned to a class and I want to change the value of a specific button from that class. {% for titles in title %} <table> <tr> <td> <input type = "button" class = "openGraph" value = "{{titles.title}}" id="{% url 'openGraph' title=titles.id %}"> </td> <td> <input type = "button" class = "deleteGraph" value = "Delete" id="{% url 'deleteGraph' title=titles.id %}"> </td> </tr> </table> {% endfor %} For those unfamiliar with django the {{}} represents the context passed from the server and are just values from the database. This is the javascript code I attempted: $('.currentGraph').each(function(i, obj){ if($("#idOfGraph").val() == $(this).val()){ console.log($("#idOfGraph").val()) console.log($(this).val()) $('.openGraph').each(function(i,obj){ if($(this).val() == currentTitle){ $(this).val(title); } }) } })