Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Vim & NeoVim Cannot Detect Django HTML FileType
I'm using Vim 8.1 and NeoVim 0.4.3. When I'm editing Django template html files neither could correctly detect the file type and hence no color or syntax highlighting at all. I'm pretty sure filetype on because this is the output: filetype dection:ON plugin:ON indent:ON I followed this issue and forcing the filetype to htmldjango (at the bottom of the .vimrc file I post down below) did work, but I don't think it's ideal. Could anybody please help me with this? My .vimrc: " macOS version set rtp+=/usr/local/opt/fzf call plug#begin('~/.vim/plugged') Plug 'junegunn/vim-easy-align' " tmux Plug 'christoomey/vim-tmux-navigator' Plug 'tmux-plugins/vim-tmux' Plug 'benmills/vimux' " Coc Plug 'neoclide/coc.nvim', {'branch': 'release'} Plug 'tpope/vim-fugitive' " fzf Plug '/usr/local/opt/fzf' Plug 'junegunn/fzf.vim' " Ack search tool Plug 'mileszs/ack.vim' " Indentation Plug 'Yggdroot/indentLine' " Python autoformat Plug 'psf/black' " Django HTML Plug 'tweekmonster/django-plus.vim' " comment Plug 'scrooloose/nerdcommenter' Plug 'tpope/vim-sensible' Plug 'tpope/vim-sleuth' " gitgutter Plug 'airblade/vim-gitgutter' " emmet Plug 'mattn/emmet-vim' " Ale Plug 'w0rp/ale' " lightline Plug 'itchyny/lightline.vim' " Eslint Plug 'vim-syntastic/syntastic' " EcmaScript and JSX Plug 'pangloss/vim-javascript' Plug 'maxmellon/vim-jsx-pretty' " TypeScript Plug 'leafgarland/typescript-vim' Plug 'Quramy/tsuquyomi' Plug 'Shougo/vimproc.vim' " Elm Plug 'elmcast/elm-vim' " Go format Plug 'fatih/vim-go' " NERDTree Plug 'scrooloose/nerdtree' ", {'on': 'NERDTreeToggle'} Plug 'Xuyuanp/nerdtree-git-plugin' " Colorscheme Plug 'morhetz/gruvbox' Plug … -
Django delete() not working inside form_valid
I have been trying to delete a record from inside Django UpdateView def form_valid(self, form): journal_id = form.instance.id IncomeJournal.objects.filter(pk=journal_id).delete() I tried to use both objects.filter and objects.get both didn't work. When I try to print print(IncomeJournal.objects.get(pk=journal_id)) I am getting the queryset. -
Django makemigrations tries to make a migration file for dbtemplate when there's no change
Django version: 1.11 Python: 3.6 I've modified a save() method on one model that is unrelated (I believe) to dbtemplates, the code looks like this: class SomeObj(): ....... def save(self, *args, **kwargs): if self.some_condition(): self.some_attri = True self.save() super(SomeObj, self).save(*args, **kwargs) But now when I do makemigrations, django returns a permission error saying I have no permission to create /path/to/python3.6/site-packages/dbtemplates/migrations/0002_auto_20200113_1641.py When doing a dry-run, it's returning - Change managers on template What could cause this? I'm not modifying anything dbtemplates related -
How to create 100 instances of model automatically after the creation of new model?
I work on cinema booking app. I've already created table in frontend, contains 100 seats (10 rows x 10 seats). Each seat is "td". I thought about making each td an object of the model so I can easily assign users later on. Basing on main model's max_seats i want to create the objects. After adding a new movie to db the objects should get created automatically. Any idea or hint where to start ? My main model: class Movies(models.Model): title = models.CharField(max_length=100) price = models.FloatField() max_seats = models.IntegerField(default=100) And the model where i need to create the objects: class Seat(models.Model): customer = models.ForeignKey(User, on_delete=models.CASCADE, default=None) movie = models.ForeignKey(Movies, on_delete=models.CASCADE) row = models.CharField(max_length=1) number = models.IntegerField() -
Generated file not saved in the file storage - django
Finally could save generated file for logged in user but the file actually doesn't save in the file storage. I'm not able to understand what am I doing wrong. views.py def schoolinput_view(request): if request.method == 'POST': worddocument = docx.Document() documenttitle = worddocument.add_heading( school_name_view.title(), 0) file_io = io.BytesIO() worddocument.save(file_io) file_io.seek(0) response = HttpResponse( content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') response['Content-Disposition'] = 'attachment; filename = timetable.docx' worddocument.save(response) path = join(settings.MEDIA_ROOT, 'word_documents', 'timetable.docx') documentfile = Timetables() documentfile.timetable_files.name = path if request.user.is_anonymous: pass elif request.user.is_authenticated: documentfile.user = request.user documenttitle = File(path, worddocument) documentfile.save(worddocument) return response class TimetablesView(ListView): model = Timetables template_name = 'quickmain/timeables_list.html' tablefiles = Timetables.objects.all() When checked in admin panel, it shows correct number of object for all users but the file is not actually saved in the folder. model.py class Timetables(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1, related_name='timetables_files', null=True, blank=True) timetable_files = models.FileField( null=True, blank=True, upload_to='word_documents') def __str__(self): return f'{self.user.email} Timetables' timetables_list.html {% for timetable_files in user.timetables_files.all %} <button><embed src = "{{timetable_files.timetable_files.url}}" target="__blank"></button> {% endfor %} On this page it shows the correct number of errorwindows (those small windows), for example if there are 4 objects for user x it'll show 4 windows like . Although the url it points to is correct. -
Aggregation in Django on DateTime fields whilst being TZ aware
I have a simple model like so: class Counter(models.Model): timestamp = models.DateTimeField(auto_now_add=True) views = models.IntegerField() I can get the sum of the views per day like so: Counter.objects.values("timestamp__date").annotate(Sum("views")) Since timestamp is being saved as a UTC timestamp, my __date annotation will be correct for UTC dates. How might I get a daily sum of views based on a different timezone? In SQL I might do something like this (untested!) at a guess. select date_trunc('day', timestamp + interval '1 hour') as day, sum(views) from counter group by 1 -
How to download a document generated with python-docx in Django project?
I'm trying to figure how to download a word document generated with python-docx in my django app (I'm still learning and this is the first time I working with documents); with the help of ajax I send all the information needed to the view and call a function that uses that information and returns the document, then I'm trying to send this document as response in order to download it with the help of a "Download" button (or show web browser download dialog) in the same template from where I'm submitting the data, but here is where I'm stuck. to send this document as response in order to download it with the help of a "Download" button (or show web browser download dialog) in the same template from where I'm submitting the data, but here is where I'm stuck. What I have until now is: 1) In javascript I'm sending the information as follows: data = { categoria: cat, familia: fam, Gcas: gcas, FI: FI, FF: FF, Test: test, Grafica: grafica }, $.ajax({ type: 'post', headers: { "X-CSRFToken": csrftoken }, url: url, data: { json_data: JSON.stringify(data) }, success: function (response) { $('#instrucciones').hide(); //Hide a div with a message $('#btndesc').show(); //Show … -
Django Join inner 2 different DB
i want to make inner join btw 2 database and 2 tables models.py class UsersMaster(models.Model): useruid = models.AutoField(db_column='UserUID',primary_key=True) # Field name made lowercase. userid = models.CharField(db_column='UserID', max_length=18) # Field name made lowercase. pw = models.CharField(db_column='Pw', max_length=12) # Field name made lowercase. status = models.SmallIntegerField(db_column='Status') # Field name made lowercase. point = models.IntegerField(db_column='Point') # Field name made lowercase. class Meta: managed = False db_table = 'Users_Master' class Chars(models.Model): serverid = models.SmallIntegerField(db_column='ServerID') # Field name made lowercase. userid = models.CharField(db_column='UserID', max_length=12) # Field name made lowercase. useruid = models.IntegerField(db_column='UserUID') # Field name made lowercase. charid = models.AutoField(db_column='CharID',primary_key=True) # Field name made lowercase. charname = models.CharField(db_column='CharName', max_length=30) # Field name made lowercase. class Meta: managed = False db_table = 'Chars' i Tryed to do it but it didn't works so i came here for help the question is how i can inner join 2 different database i am sorry for my bad english -
psycopg.errors.UndefinedTable : relation "newroom_article" does not exist
enter image description here this error appear when moving from sqlite into postgresql database cant make python manage.p makemigrations or migrate (appear this error) -
django using a variable in any templates
for example: in the templates you will use your site name a lot of times. in the future if you want to change your website name you must edit all templates files you wrote your site name in them is there a way to define a variable and use that variable in all templates without using context in views I tried to define and use settings.py properties with this code but doesn't work {{SITE_NAME}} -
Update a variable every 5 second using jquery
I am using django to create a webpage and this is the first time I am doing so. I am trying to fetch the value of a variable from .py file at an interval of 5 seconds. Below is the HTML code: <!DOCTYPE html> <html> <head> <title>Like Post App</title> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </head> <body> <div class = "display-3 color-red"><center>DataFlair AJAX Tutorial<br>Post APP</center></div> {% for post in posts %} <div class = 'container jumbotron'> <h3 class="display-5">{{ forloop.counter }}. {{ post.post_heading }}</h3> <p class="lead">{{ post.post_text }} </p> <p> <div type="text/css" class = "container">Author : {{ post.post_author }}</div> <a class="likebutton btn btn-primary btn-lg" id="like{{ post.id }}" data-catid="{{ post.id }}">Like({{ post.like_ref.counter }})</a> </p> <p id="message{{post.id}}"> </p> </div> {% endfor %} <script type="text/javascript"> setInterval(function() { getvalue(); // Do something every 5 seconds }, 5000); getvalue(); function getvalue(){ var id; id = $(this).attr("data-catid"); $.ajax( { type:"GET", url: "like", data:{ post_id: id }, success: function( data ) { $( '#like'+ id ).text("Like(" + data +")"); var i=parseInt(data); console.log("Value= "+i); } } ) } </script> </body> </html> Below is the views.py code: import json from django.shortcuts import render from .models import Post, Like from django.http import HttpResponse # … -
PyCharm Django form.save() and form.update() duplicates records
views.py @login_required() def acronis_view(request): allitems = Acronis.objects.all() acroniform_form = acroniform() if request.method == 'POST': acroniform_form = acroniform(request.POST) if acroniform_form.is_valid(): acroniss = acroniform_form.save(commit=True) acroniss.save() return redirect('/Verwaltung/Acronis') return render(request, 'blog/acr.html', {'acroniform_form': acroniform_form, 'allitems': allitems}) @login_required() def edit_acronis(request, id): item = get_object_or_404(Acronis, id=id) if request.method == "POST": form = acroniform(request.POST, instance=item) if form.is_valid(): form.save() return redirect('/Verwaltung/Acronis') else: form = acroniform(instance=item) return render(request, 'blog/editacronis.html', {'form': form}) ============================================================ urls.py path('EditAcronis/<int:id>', views.edit_acronis, name='edit_acronis'), ============================================================ blog/editacronis.html {% extends 'blog/base.html' %} {% load bootstrap4 %} <html lang="en"> <meta charset="UTF-8"> <title>{% block supertitle %} Home {% endblock %}</title> {% block Content %} <form class="form-inline, form-row" action="{% url 'blog:acr' %}" method="post"> {% csrf_token %} {% bootstrap_form form %} <button type="submit" class="btn btn-success">Update</button> </form> {% endblock %} ============================================================ forms.py class acroniform(forms.ModelForm): def clean_key(self): Key = self.cleaned_data['Key'] if Acronis.objects.filter(Key_iexact=Key).exists(): raise forms.ValidationError('Dieser Key ist bereits vergeben') return Key class Meta: model = Acronis fields = ('KN', 'Key', 'Release') labels = { 'KN': 'Kundennummer', 'Key': 'Key', 'Release': 'Release', } How to stop the duplication ?? I also tried "update_or_create"... -
Struggling to display django validation message
I am trying to display an inbuilt Django validation error for my login form on my template I can't get any error message such as 'Username and Password do not match'. What am I doing wrong? here is my forms.py from django import forms from django.contrib.auth.forms import AuthenticationForm class LoginForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Username'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Password'})) botcatcher = forms.CharField(widget=forms.HiddenInput, required=False) on my project url.py urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='frontend/login.html', form_class=LoginForm), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='frontend/logout.html')), # path('backend/', include('backend.urls')), path('mrc/', include('frontend.urls')), path('admin/', admin.site.urls), ] on login.html {% for my_field in form.visible_fields %} <!-- THIS IS FOR ERROR IN THE FORM --> {% if my_field.errors %} {% for err in my_field.errors %} <div class="alert alert-danger">{{ err }}</div> {% endfor %} {% endif %} <!-- THIS IS FOR THE FIELDS --> <div class="form-group"> {{ my_field.label_tag }} {{ my_field }} </div> <!-- END THE FIELDS --> {% endfor %} -
django Like dislike isn't working in post list .but its working on post detail
I cannot use the "is_liked" function in the forloop of home templates if else part. The post details views "is_liked" function works correctly. If the user like the particular post it will show dislike button. But i cant show the dislike button on the post lists. I have tried many ways to do that but can't find the solution. "if is_liked else" part is not working on the home.html home.html: {% for post in posts %} <p><a class="article-content" href="{% url 'post-detail' pk=post.pk %}" >{{ post.content }}</a></p> <a href="{% url 'post-likes' pk=post.pk %}"> {{ post.total_likes }}like{{ post.total_likes|pluralize}} </a> <form action="{% url 'like_post' %}" method="POST"> {% csrf_token %} {% if is_liked %} <button type="submit" id="like" name="post_id" value="{{ posts.id }}" class="btn btn-danger">dislike</button> {% else %} <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-primary">like</button> {% endif %} </form> <a href="{% url 'post-detail' pk=post.pk %}">{{ post.comments.count }}comment{{ post.comments.count|pluralize }}</a> {% endfor %} {% endblock content %}enter code here post_detail.html: <p>{{ posts.content }}</p> <a href="{% url 'post-likes' pk=posts.pk %}"> {{ total_likes }}like{{ total_likes|pluralize }} </a> <form action="{% url 'like_post' %}" method="POST"> {% csrf_token %} {% if is_liked %} <button type="submit" id="like" name="post_id" value="{{ posts.id }}" class="btn btn- danger">dislike</button> {% else %} <button type="submit" id="like" name="post_id" … -
How to do automated postgres db backups in google app engine for django app?
I have a Django app running in standard Google App Engine, using postgres SQL. I want to run a daily cron to save db snapshot in one of the buckets. Using django-extensions and django-dbbackup, I have created a cron job, which works locally. But on GAE I get this error: dbbackup.db.exceptions.CommandConnectorError: Error running: pg_dump db-duiteng-fdspranav-dev --host=35.200.172.96 --port=5432 --username=user-duiteng-fdspranav-dev --no-password --clean How do I set the psql password or use .pgpass file in GAE, preferably without sshing into GAE? Code: # cron.yaml cron: - description: "DB Backup CRON job" url: /core/cron-jobs # the path to your view schedule: every 2 minutes # the frequency for running the job retry_parameters: min_backoff_seconds: 120 max_doublings: 5 # views.py def my_background_job(request): call_command('runjobs', 'daily') return HttpResponse('Cron run success', status="200") # myapp>jobs>daily>db_backup.py (example documented in django_extensions) from django_extensions.management.jobs import DailyJob class Job(DailyJob): help = "Django Daily DB Backups" def execute(self): from django.core import management management.call_command("dbbackup") # settings.py INSTALLED_APPS = [ ... 'django_extensions', 'dbbackup', # django-dbbackup ] Postgres backup documention in https://cloud.google.com/sql/docs/postgres/backup-recovery/backing-up is vague. What Google terms as "automated backup", isnt much helpful for me, since I dont get the DB Dump in a *.psql file anywhere. They do mention "Currently, you can only use the API to … -
Django unit tests failing only when using django-nose and Django 2
I'm trying to upgrade from Django 1.11 to 2.2 and running into some issues with the unit tests. Previously on Django 1.11 I had django-nose installed and all the tests ran without issue. When I tried to upgrade to Django 2, every test that touches the database in any way now throws the error: ====================================================================== ERROR: Test the index page ---------------------------------------------------------------------- Traceback (most recent call last): File "/opt/puzzlehunt/puzzlehunt_server/huntserver/tests.py", line 115, in test_index response = get_and_check_page(self, 'huntserver:index', 200) File "/opt/puzzlehunt/puzzlehunt_server/huntserver/tests.py", line 42, in get_and_check_page response = test.client.get(reverse(page, kwargs=args)) File "/opt/puzzlehunt/puzzlehunt_server/venv/lib/python3.5/site-packages/django/test/client.py", line 517, in get response = super().get(path, data=data, secure=secure, **extra) File "/opt/puzzlehunt/puzzlehunt_server/venv/lib/python3.5/site-packages/django/test/client.py", line 332, in get return self.generic('GET', path, secure=secure, **r) File "/opt/puzzlehunt/puzzlehunt_server/venv/lib/python3.5/site-packages/django/test/client.py", line 404, in generic return self.request(**r) File "/opt/puzzlehunt/puzzlehunt_server/venv/lib/python3.5/site-packages/django/test/client.py", line 485, in request raise exc_value File "/opt/puzzlehunt/puzzlehunt_server/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/opt/puzzlehunt/puzzlehunt_server/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/opt/puzzlehunt/puzzlehunt_server/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/puzzlehunt/puzzlehunt_server/huntserver/info_views.py", line 17, in index curr_hunt = Hunt.objects.get(is_current_hunt=True) File "/opt/puzzlehunt/puzzlehunt_server/venv/lib/python3.5/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/opt/puzzlehunt/puzzlehunt_server/venv/lib/python3.5/site-packages/django/db/models/query.py", line 397, in get num = len(clone) File "/opt/puzzlehunt/puzzlehunt_server/venv/lib/python3.5/site-packages/django/db/models/query.py", line 254, in __len__ self._fetch_all() File "/opt/puzzlehunt/puzzlehunt_server/venv/lib/python3.5/site-packages/django/db/models/query.py", line 1179, in _fetch_all self._result_cache = list(self._iterable_class(self)) … -
How to make a like/dislike system with ajax
I'm trying to make a like/dislike system and nothing is working the way it should. The problem I'm having is replacing the element in the template and changing the value assigned to that element (so, I need <button class="like-post-btn" value="not-liked" >Like</button> to become <button class="like-post-btn" value="is-liked">Unlike</button> after clicking like). Before clicking either 'Like' or 'Dislike', it shows the Like and Dislike buttons with the correct counts. After clicking like the dislike count disappears, the Like button doesn't change and the like count doesn't update, the web console shows the debugs and then says cannot assign function to call I have no idea how to do this, please help. If you know of any good ajax with django tutorials, please let me know because none of the ones I've seen actually explain anything that's going on. main template snippet ( Checks if user has already liked or disliked ) {% if request.user not in post.get_liked_users %} <button class="like-post-btn" value="not-liked">Like</button> {% else %} <button class="unlike-post-btn" value="is-liked">Unlike</button> {% endif %} <div class="like-count">{{post.like_count}}<div> {% if request.user not in post.get_disliked_users %} <button class="dislike-post-btn" value="not-disliked">Dislike</button><div class="dislike-count">{{post.dislike_count}}</div> {% else %} <button class="dislike-post-btn" value="is-disliked">Undislike</button><div class="dislike-count">{{post.dislike_count}}</div> {% endif %} like_post() view snippet (I'm trying to keep these short) if … -
problems for play heavy videos with django and videos
I'm trying to play videos with django 3.0 and videojs. When I play light videos (like 5 MB) I can play the videos without any problem. But I need reproduce videos with a size of 1 GB for app that I'm developing. Here this the code for play de video. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="{% static 'css/video-js.css' %}" rel="stylesheet" type="text/css"> <script src="{% static 'js/videojs-ie8.min.js' %}"></script> <title>Smart City</title> <head> <body> <video id="my-video" class="video-js" controls preload="auto" width="640" height="264" > <source src="{% static 'videos/video1.mp4' %}" type="video/mp4"> </video> </body> </html> And Django said this error: Traceback (most recent call last): File "C:\path\to\Python\Python37-32\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\path\to\Python\Python37-32\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\path\to\Python\Python37-32\lib\wsgiref\handlers.py", line 279, in write self._write(data) File "C:\path\to\Python\Python37-32\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "C:\path\to\Python\Python37-32\lib\socketserver.py", line 796, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] Se ha anulado una conexión establecida por el software en su equipo host [13/Jan/2020 16:00:09] "GET /static/videos/10049.mp4 HTTP/1.1" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 60615) Traceback (most recent call last): File "C:path\to\Python\Python37-32\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\path\to\Python\Python37-32\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\path\to\Python\Python37-32\lib\wsgiref\handlers.py", line 279, in write self._write(data) File "C:\path\to\Python37-32\lib\wsgiref\handlers.py", line 453, … -
"[Errno 13] Permission denied": Django 3.0+Apache2+Ubuntu 18.04
I'm trying to rum my first project and get an easue: [Errno 13] Permission denied: form Django 3.0 in the debug mode. when I’m trying to create file in my directory I know that this easue is realted to access permisions in Ubuntu. I do all I have found lately in the internet: Granted all rights is needed to www-data user (even 777 – but it gives nothing) 2.Change DocumentRoot to /home/dmitri/OpenDRRP in my apahe2 .conf file DO the: added to .conf file but nothing helps... What I've mised? -
Multiple User types with a payed system
I am extremely new to the Django frame work and needed a little more insight. I am currently building a project to have two user types.Example would be a teacher and student type application. The main difference would be that I would like to have one of the users to have a payed tier. Example: I would love to have it so that the teacher can only log in if payed. My other question would be. I already have been working on the project before coming to realize the AbstractUser might be a better solution. Can I get around using AbstractUser with using OnetoOneModels with this type of setup? I found documentation saying it's best to use AbstractUser before any migrations are made, how would I go about changing my project to suit these new requirements "If AbstractUser is best"? If there is no easy way around it I'm not above starting over to make it right. Andrew -
How can I populate a django database using a script file?
I built a small django app and created some models. Now I would like to populate the database (the tables and rows do already exist) using a python script since I have to read the information I want to populate the database with, from multiple external files. Is there any way to do that? -
Connecting Django framework to python GUI scripts
I have make a django-framework based website and also a tkinter GUI game. Is is possible to execute the script of the Tkinter GUI game using a html button in django framework. -
Django models not getting updated
I have created a coupon system where each user has 500 as balance initially in the employee table. I want to decrease this balance by the amount provided by user through the html forms. Given below are my files: Models.py from django.db import models from django.contrib.auth.models import User import django import datetime # Create your models here. class vendor(models.Model): id = models.CharField(max_length=20, primary_key=True) name = models.CharField(max_length=30) class employee(models.Model): name = models.OneToOneField(User, on_delete=models.CASCADE) id = models.CharField(max_length=20, primary_key=True) balance = models.IntegerField(default=0) class transaction(models.Model): vendor_id = models.ForeignKey(vendor, on_delete=models.CASCADE) emp_id = models.ForeignKey(employee, on_delete=models.CASCADE) debit = models.IntegerField() credit = models.IntegerField() timestamp = models.DateField(("Date"), default=datetime.date.today) views.py def updatingBalance(request): if request.method=="POST": ven_id = request.POST["groupOfDefaultRadios"] amount = request.POST["amt"] x = employee.objects.get(name = request.user) x.balance = x.balance - int(amount) v = vendor.objects.get(id=ven_id) w = employee.objects.get(id=x.id) transaction.objects.create(vendor_id = v, emp_id=w,debit=amount,credit=0) y = employee.objects.get(name = request.user) #print(y.balance) return render(request, 'profiles/userLogin.html', {'model':employee}) return render(request, 'profiles/userLogin.html') html form: {% if model %} <h3>Balance amount is {{ model.balance }}</h3> {% endif %} <h3>Select vendor to pay!</h3> <br> <form method="POST" action="/profiles/userLogin/"> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" id="defaultGroupExample1" name="groupOfDefaultRadios" value="1"> <label class="custom-control-label" for="defaultGroupExample1">Vendor 1</label> </div> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" id="defaultGroupExample2" name="groupOfDefaultRadios" value="2"> <label class="custom-control-label" for="defaultGroupExample2">Vendor 2</label> </div> <input type="" class="form-control" id="amount1" name="amt" aria-describedby="emailHelp" … -
Error while sending JavaScript generated image to Django ModelForm
I’m trying to use https://github.com/szimek/signature_pad to attach a signature to a form and send it to the server. I’ve been able to successfully upload images with a standard ImageField, and have also used szimek/signature_pad to download the signature. But when I try to get the signature to the server, I get "(Hidden field signature) No file was submitted. Check the encoding type on the form." So I think I’m at least successfully sending an image to the field, but am not sure how to encode it. HTML <form id="form" action="{% url ‘my_app:testFormPage' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <div id="signature-pad"> <canvas></canvas><br> </div> <input type="hidden" name="signature" value=“signatureImage”> <button type="submit" data-action="formSig">Submit</button> </form> Python # Models.py class testModel(models.Model): name = models.CharField(max_length=50) date = models.DateTimeField(default=timezone.now) signature = models.ImageField (null=True, max_length=3000) # Forms.py class testForm(forms.ModelForm): class Meta: model = testModel fields = ‘__all__’ widgets = { 'signature': forms.HiddenInput(),} # Views.py def testFormPage(request): if request.method == 'POST': form = testForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect('/thanks/') else: form = testForm() context = {'form': form} return render(request, 'client_visits/testFormPage.html', context) Javascript The full javascript app can be found at https://github.com/szimek/signature_pad/tree/master/docs/js. Here’s just what I added var formSig = wrapper.querySelector("[data-action=formSig]"); formSig.addEventListener("submit", function (event) { var signatureImage … -
how come I could create a json-type file in django project?
I just start to learn django and Vue.js and now face this problem. I have built a small python + django + Vue.js project according to the sample. It works well now. the main codes are as follows: testdjango.vue <template> <div id="mineapp"> {{msg}} <form @submit.prevent ="submitNote"> <label>Title</label> <input type="text" v-model="formData.title"/> <label>Content</label> <textarea v-model="formData.content"></textarea> <br/> <button type="submit">Submit</button> </form> </div> </template> <script> import api from './api/index.js' .... methods: { submitNote(){ api.fetchNotes('post',null, this.formData).then(res=>{ this.msg = 'Saved' }).catch((e)=>{ this.msg = e.response }) }, index.js import axios from 'axios' export default{ fetchNotes(method, params, data){ if(method ==='post'){ return ajax('api/notes/', method,{data}) } else{ return ajax('api/notes/', 'get', {}) } ... function ajax(url,method,options){ if(options !== undefined){ var{params=[], data={}} = options } else{ params = data = {} } return new Promise((resolve, reject)=>{ axios({ url, method, params, data }).then(res => { resolve(res) }, res=>{ reject(res) }) }) models.py class Note(models.Model): title = models.CharField(max_length=225, unique=True) content = models.TextField() created = models.DateTimeField(auto_created=True, auto_now_add=True) def _str_(self): return self.title views.py class NoteViewSet(viewsets.ModelViewSet): #check permissions permission_classes={ IsAuthenticated, } queryset = Note.objects.all() serializer_class = NoteSerializer lookup_field ="id" I successfully stored the front-end data into backend-side(django) and checked admin panel. Next problem is that: when I send a ajax request "/api/notes" can I create a json-type file …