Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How does Django detect test mode?
I'm running tests on Django (2.2) with Postgres. According to Django's docs, when running tests, it should create a throw away database named by prefixing the normal database name with test_. However this is not happening for me: the tests use the normal database! Here are the relevant settings: # Another module where I define these values from conf.vars import DB_HOST, DB_NAME, DB_PASSWORD, DB_USER DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': DB_HOST, 'NAME': DB_NAME, 'USER': DB_USER, 'PASSWORD': DB_PASSWORD, # I added the following to see if it makes a difference, but no. 'TEST': { 'NAME': 'test_' + DB_NAME, }, } } My manage.py file has the usual stuff including this line: execute_from_command_line(sys.argv) I'm guessing there is something I'm doing which is causing Django not to recognise it is in test mode, as the only alternative explanation is that this is a bug in Django and that seems unlikely as it's a pretty serious one. This also makes me wonder, how does Django know when it is in test mode? Trying to search for this only throws up people asking how to detect test mode for their own purposes. -
binary data on websocktes with additional information
I am trying to develop a chat application on django, for live communication I am using websockets. Messaging is working fine but I am in trouble with files, if any one attach multiples files then how to send and receive it with some additional data. I had set - chatSocket.binaryType = 'arraybuffer'; For simple messaging - chatSocket.send(JSON.stringify( {'id': next_id, 'message': message, 'karma' : karma.val(), 'cert': cert.attr('data'), } )); if someone try to send multiple images then - let files = document.getElementById("attach_img").files; // files.item = '092' console.log('files send requested',files); chatSocket.send(files, { binary: true }); In my consumers.py async def receive(self, bytes_data=None, text_data=None): print('recieved',bytes_data, text_data) It is printing - recieved None [object FileList] but when I change my files as - let files = document.getElementById("attach_img").files['0']; then received bytes_data will be something like- b'\xff\xd8\xff\xe0\x00\x10JFIF\..... I want to send the images + id + cert to server. I search a lot on internet but unable to get the solution how I can send files with additional information over websockets. -
Django-REST: The database driver doesn't support modern datatime types
I'm trying to make a rest API with Django Rest on Debian, but when I run the command "python3 manage.py migrate" throws this exception Error: The database driver doesn't support modern datatime types.") django.core.exceptions.ImproperlyConfigured: The database driver doesn't support modern datatime types. Already installed: msodbcsql17 is already the newest version (17.3.1.1-1). freetds-bin is already the newest version (0.91-6.1+b4). freetds-dev is already the newest version (0.91-6.1+b4). tdsodbc is already the newest version (0.91-6.1+b4). unixodbc-dev is already the newest version (2.3.7). unixodbc is already the newest version (2.3.7). file:odbc.ini [MYSERVER] Description = Django SQLServer Driver = FreeTDS Trace = Yes TraceFile = /tmp/sql.log Database = DjangoDB Servername = MYSERVER UserName = sa Password = ******* Port = 1433 Protocol = 8.0 file:odbcinst.ini [FreeTDS] Description=FreeTDS Driver for Linux & MSSQL on Win32 Driver=/usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so Setup =/usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so UsageCount=1 [ODBC Driver 17 for SQL Server] Description=Microsoft ODBC Driver 17 for SQL Server Driver=/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.3.so.1.1 UsageCount=1 file:freetds.conf [global] # TDS protocol version tds version = 8.0 [MYSERVER] host = localhost port = 1433 tds version = 8.0 -
Nginx "502 Bad Gateway" when using uWSGI Emperor with multiple django projects on CentOS6
I set up a Django website on a CentOS 6 server using Nginx and uWSGI, and I would like to expand this to include more unique Django sites on the same IP. I have been trying uWSGI Emperor, but it has been fighting me along the way. Both sites now give "502 Bad Gateway" errors, and I'm stuck on how to best setup uWSGI emperor to work with it all. The CentOS 6 server has python 2 installed, but I'm using rh-python36 for all the Django sites and uWSGI. I tried following this guide: https://www.digitalocean.com/community/tutorials/how-to-set-up-uwsgi-and-nginx-to-serve-python-apps-on-centos-7 , though the uwsgi didn't work for some reason. I've mostly been trying to mess with the .config and .ini files for nginx and uwsgi, though I'm not confident what I've added has helped. The virtualenv location for both sites: /root/Env/mysite1_env /root/Env/mysite2_env Nginx: /etc/nginx/conf.d/mysite1.conf (mysite2.conf is similiar) server { listen 80; server_name mysite1.net www.mysite1.net; root /home/serveruser/svr/sites/mysite1; access_log /home/serveruser/svr/sites/mysite1/logs/access.log; error_log /home/serveruser/svr/sites/mysite1/logs/error.log; charset utf-8; location = /favicon.ico { access_log off; log_not_found off; } # Django admin media location /media { alias /home/serveruser/svr/sites/mysite1/media; } # ag_jobs static media location /static { autoindex on; alias /home/serveruser/svr/sites/mysite1/static; } # Non-media requests to django server location / { uwsgi_pass unix:/home/serveruser/svr/sites/mysite1/mysite1.sock; include … -
Django Login Redirection Not Working -- User Not authenticated
The code redirects but runs the condition suite that redirects to index.html-- indicating the user was not authenticated( user is None) I'm trying to create a sign in/ login page. My registration form works but the login page runs in a way that indicates that the user was not successfully authenticated Note: This is the code in my views.py file from django.shortcuts import render, redirect from django.utils.safestring import mark_safe from django.contrib.auth.models import User, auth from django.contrib import messages import json def index(request): return render(request, 'chat/index.html', {}) def enter_chat_room(request): return render(request, 'chat/chat_room.html') def login(request): if request.method == 'POST': username = request.POST['userlogin'] password = request.POST['loginpassword'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect('enter_chatroom') else: # messages.info('Invalid') return redirect('index') else: return render(request, 'chat/index.html') I want the user to enter the chatroom once he/she has been authenticated -
how to make an update function in django
i have an update function that allow user to update a form with pre-populated data using django the problem once the user try to enter to the update page the system display the below error : local variable 'form' referenced before assignment views.py def update(request,pk): instance = get_object_or_404(suspect,pk=pk) if request.method == "POST": form = suspectForm(request.POST or None,instance=instance) if form.is_valid(): instance = form.save(commit = false) instance.user = request.user instance.save() return redirect('result',pk = instance.pk) else: form = suspectForm(instance = instance) return render(request,'blog/update.html',{'form':form}) update.html {% extends "testbootstarp.html" %} {% load static %} {% block content %} <div class="offset-3 col-md-6"> <form method="post"> <div class="form-group">{% csrf_token %} {% for field in form %} <div class="field"> <label>{{field.label_tag}}</label> {{field}} {% for error in field.errors %} <p class="help is-danger">{{error}}</p> {% endfor %} </div> {% endfor %} </div> <button type="submit">edit</button> </form> </div> {% endblock content %} -
How To Fix Miscased Procfile in Heroku
Heroku will not reload my corrected Procfile I have ran git status which shows me the Procfile and I realized that I spelled Procfile with a lower case p. I saw the error and updated the file name in my project but when I saved and ran git status again it stills shows it lower case. Of course now its not showing the site on Heroku. Changes not staged for commit: (use "git add ..." to update what will be committed) (use "git checkout -- ..." to discard changes in working directory) modified: procfile remote: -----> Discovering process types remote: remote: ~ Mis-cased procfile detected; ignoring. remote: ~ Rename it to Procfile to have it honored. remote: remote: Procfile declares types -> (none) Total newbie on my first project. Should I delete the project on Heroku and just start all over fresh or can I just do a git init and then just push everything up again to Heroku? -
Autocomplete with ajax and jquery does not work with Bootstrap styling
I try to implement a simple jquery autocomplete widget with an input form on the main page but it does not work. I work in Django 2.2. When I try to put the autocomplete widget on the main page it is not working. Ajax queryset is not getting generated. When I put the same code on a blank page without any styling, it works fine. So, when I put the same widget on the main page(with Bootstrap styling) but connecting to a predetermined (hard coded) queryset, it works. In blog/base.html file: <!-- Bootstrap CSS --> <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"> <link rel="stylesheet" type = "text/css" href = "{% static 'blog/main.css' %}"> <!-- for Autocomplete --> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.12.4.js"></script> <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <!-- Input --> <div class="ui-widget"> <label for="search"> Search </label> <input id="search" placeholder="Search by ticker"> </div> <script type="text/javascript"> $(document).(function() { $("#search").autocomplete({ source: "{% url 'ajax_load_project' %}", minLength: 1, }); }); </script> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> views.py def ajax_load_project(request): if request.is_ajax(): q = request.GET.get('term', '') projects = Project.objects.filter(title__istartswith=q)[:7] results = [] for project in projects: project_json = {} project_json['id'] = project.pk project_json['value'] = … -
Can log in from django shell but cannot log from views
Having the exact same problem as in Python logging works in shell, but not in views settings:py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'myapp_error.log', }, }, 'loggers': { '': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } views.py import logging logger = logging.getLogger(__name__) logger.warning('Hi this is the warning logger working') -
How to assign Group permissions to individual records in Django
I have a model in which I would like to assign specific records to a user group (or several user groups), so that an individual record is editable/viewable only by members of those groups associated with it. I want the user who creates a record in the model to be able to assign the group permissions for that record. What's the best way to do this? E.g. can I assign a OneToMany field? Something like: from django.contrib.auth.models import Group, Permission class MyModel(models.Model): title = models.CharField(max_length=200, null=True) groups = [ What comes next? ] -
problems registering using user extend
I created a system where I have the user that is the default of django and I created the Model Fotografos, which extends the User. The problem is that it does not save, it always returns to the form. I already tried to take some fields. I think the error occurs after these two lines form = PhotographersForm (request.POST) if form.is_valid (): after them nothing else happens. model.py class Photographers(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50, blank=False) lastname = models.CharField(max_length=50, blank=False) email = models.EmailField(blank=False) phone = models.CharField(max_length=20, blank=False) cpf = models.CharField(max_length=19, blank=False) cnpj = models.CharField(max_length=19, blank=False) birthday = models.CharField(max_length=10, blank=False) address = models.CharField(max_length=50, blank=False) number = models.CharField(max_length=10, blank=False) district = models.CharField(max_length=30, blank=False) zip_code = models.CharField(max_length=25, blank=False) city = models.CharField(max_length=30, blank=False) state = models.CharField(default='RS', max_length=50, choices=STATE_CHOICES, blank=False) password1 = models.CharField(max_length=15, blank=False) def __unicode__(self): return self.name @receiver(post_save, sender=User) def new_register(sender, instance, created, **kwargs): if created: Photographers.objects.create(user=instance) instance.photographers.save() views.py def register(request): usuario = Photographers.objects.all() form = PhotographersForm() data = {'usuario': usuario, 'form': form} return render(request, 'paneladmin/register.html', data) def new_register(request): if request.method == 'POST': form = PhotographersForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.is_staff = True user = form.save() user.refresh_from_db() user.photographers.name = form.cleaned_data.get('name') user.photographers.lastname = form.cleaned_data.get('lastname') user.photographers.email = form.cleaned_data.get('email') #user.photographers.picture = … -
Getting "App crashed" error after deploying Django app on Heroku
I am getting these following two errors after deploying my Django application on Heroku: 2019-07-21T22:09:21.799421+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=myapp.herokuapp.com request_id=aa4c90d2-f8de-4244-abf8-1cfdde758a7f fwd="188.253.234.137" dyno= connect= service= status=503 bytes= protocol=https 2019-07-21T22:09:22.317447+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=myapp.herokuapp.com request_id=fbe1e39e-5f98-4439-8031-848937843144 fwd="188.253.234.137" dyno= connect= service= status=503 bytes= protocol=https -
Django doesn't log the user in
I have a login function, however when I try to login with a user that is not admin Django's authenticate function returns None even though the user exists in the database and the function receives the right username and password. def login_user(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] print(username, password) user = authenticate(username=username, password=password) print(user) if user is not None: login(request, user) return redirect("/") else: return render(request, "orders/login.html", {"message":"Username and password did not match."}) else: return render(request, "orders/login.html") -
Most performant way to integrate a crawler inside flask page
I've made a simple crawler that use multiprocessing.dummy.Pool to create a ThreadPool to open a bunch of urls together and check for links then open them to search for a specific word then return a list of links containing that word if any were found. The thing is, when i run it directly from terminal .. it runs very fast. But when i run it from Flask page as an external script with subprocess.call(["python", "myscript.py", "urls_file.txt", "word_to_search_for"]) it runs very slow and hangs unlike the first one. In flask, the data is submitted via POST as a form. Please, i would like to know what is the best way for apps like that. Thanks. -
How do I aggregate values in a python list or dictionary based on book title?
Currently, my data is like this or a dictionary, not aggregated by title: {Great Expectations, Bookstore 1, $8.99}, {Great Expectations, Bookstore 2, $12.99}, {Great Expectations, Bookstore 3, $6.99}, {Tales from the Crypt, Bookstore 1, $5.99}, {The Sisterhood of the Traveling Pants, Bookstore 3, $8.99} {Oprah: The Icon, Bookstore 2, $6.99} {Oprah: The Icon, Bookstore 3, $9.99} I'd like to create list of a dictionary of prices that's aggregated by title that looks like this: [Great Expectations, {price1: $6.99, price2: $8.99, price3: $12.99}], [Tales from the Crypt, {price1: $5.99}], [The Sisterhood of the.., {price1: $6.99}], [Oprah: The Icon, {price1: $6.99, price2: $9.99}] Thanks for your help. I will eventually pass this data into a Django view as a list. If you could help that would be great. There can be more than 3 prices, n prices. -
How to create a video blog with Django?
I am learning Django. I have started with Django girls blog tutorial which is very basic. Now I want to convert this with the conceptual video blog where user can upload a video like Youtube and user will be able to play on my blog; and some description will be there. Besides, I want every post will be moderated by admin. Can anyone expert help me with some coding suggestion as I am newcomer. Thanks in advance! I have Already complete the Django girls blog tutorial and now moving for advance opting that it has offered for expanding the blog. So I will be very thankful to the solution provider. This is my assignment but I can't find any solution on my own. I hope some expert might have some time to provide me a solution. Thank you very much! -
GeoDjango: Finding objects in radius
I'm currently trying to get a list of points contained within a radius but I can't get it working. Here is the code of my view so far: from django.contrib.gis.geos import Point from django.contrib.gis.measure import Distance class AreaInfoViewSet(viewsets.ViewSet): queryset = models.AreaInfoRequest.objects.all() serializer_class = serializers.AreaInfoRequestRequestSerializer def list(self, request): center_point = 'POINT(48.80033 2.49175)' radius = "50.0" data = {"center_point": center_point, "radius": radius, "source_ip": utils.get_client_ip(request)} serializer = serializers.AreaInfoRequestRequestSerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() # Contains an object with field "from_location"="SRID=4326;POINT (2.49157 48.80029)" objs = models.PointsResult.objects.all() float_radius = serializer.data["radius"] center_point = serializer.data["center_point"] # Point object res = models.PointsResult.objects.filter(from_location__distance_lte=( center_point, Distance({"meter": float_radius}))) # Here the res doesn't contain the unique object in the db even if it's within the radius return Response(res) Any idea why it's not working? Thank you -
How can i validate a field in a model class with another field in a separate model class in django
I'm working with django_rest_framework and i'm supposed to great an application where a Group exists with a group admin who will set some parameters for other groupmembers to use as their acceptance criteria. I have two models instances, Group and Groupmembers, Groupmembers has a foreignKey relationship to Group. Inside the Group, i have a field that holds a minimum value(number=money) a Groupmember can deposit. Please, how can i 1. Ensure that when a groupmembers selects anything less than what was specified by the group admin while creating the group, an error is raised 2)Calculate the total amount deposited by a user for a given duration from this field in the GroupMember deposit = models.PositiveIntegerField() This is a custom validation i made to ensure the group admin is restricted to a minimum value and a maximum value from django.db import models class IntergerRangeField(models.IntegerField): def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs): self.min_value, self.max_value = min_value, max_value models.IntegerField.__init__(self, verbose_name, name, **kwargs) def formfield(self, **kwargs): defaults = {"min_value": self.min_value, "max_value": self.max_value} defaults.update(**kwargs) return super(IntergerRangeField, self).formfield(**defaults) Here's my model from django.db import models from django.shortcuts import reverse from django.contrib.auth.models import User # importing fixed amount file from .import fixed_amount class Group(models.Model): name = models.CharField(max_length=100) description … -
Cannot change column 'id': used in a foreign key constraint of table error on Django
Im trying to create models taking a MySQL database as reference using Django, but when I try to migrate it throws me the next error: Cannot change column 'id': used in a foreign key constraint 'fk_post' of table 'demoniosmv.images'" My models looks like this: from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Images(models.Model): #id = models.IntegerField(primary_key=True) fk_post = models.ForeignKey('Post', related_name="images", blank=True, null=True, on_delete = models.CASCADE) img_url = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = True class Post(models.Model): #id = models.IntegerField(primary_key=True) author = models.ForeignKey(User, related_name="posts", on_delete = models.CASCADE) title = models.CharField(max_length=200, blank=True, null=True) text = models.TextField(blank=True, null=True) created_date = models.DateTimeField(default = timezone.now) class Meta: managed = True And the SQL script from which I'm creating the database is this: -- MySQL Script generated by MySQL Workbench -- Sun Jul 21 14:14:44 2019 -- Model: New Model Version: 1.0 -- MySQL Workbench Forward Engineering SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'; -- ----------------------------------------------------- -- Schema demoniosmv -- ----------------------------------------------------- -- ----------------------------------------------------- -- Schema demoniosmv -- ----------------------------------------------------- CREATE SCHEMA IF NOT EXISTS `demoniosmv` DEFAULT CHARACTER SET utf8 ; USE `demoniosmv` ; -- ----------------------------------------------------- -- Table `demoniosmv`.`post` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `demoniosmv`.`post` ( `id` INT … -
Calling script from Django on a webserver
I made a website and I deployed it with Nginx and Gunicorn on an Ubuntu server (18.04). In my site I call with subprocess some python scripts that are in my project folder. If I start them on terminal they work as well, but with subprocess they don't work. This problem also belongs to commands on terminal. @staff_member_required() def get_all_process(request): process = subprocess.Popen(["ps a"], shell=True, executable='/bin/bash', stdout=subprocess.PIPE) # /bin/bash -c output = process.stdout.readline().decode("utf-8") out = (process.communicate()[0]).decode("utf-8") return HttpResponse('{}, {}'.format(output, out)) @staff_member_required() def start_script(request): process = subprocess.Popen(["nohup /home/user/project/source/test.py >/dev/null 2>&1 &"], shell=True, executable='/bin/bash', stdout=subprocess.PIPE) # /bin/bash -c output = process.stdout.readline().decode("utf-8") out = (process.communicate()[0]).decode("utf-8") pid = process.pid + 1 return HttpResponse('{}, {}'.format(output, out)) How can I solve? -
How do I pass url path argument to view success url, in url patterns?
I want to pass the <int:pk> of my view_submission path to the success_url. Can you please help? I can't seem to find a way to do this here, without changing the code in my views file, which I'd really not like to do because I want to keep these all in the urls file. urlpatterns = [ path('', login_required(SubmissionsList.as_view()), name='all_submissions'), path('create', login_required(SubmissionCreate.as_view( success_url=reverse_lazy('all_submissions'))), name='create_submission'), path('view/<int:pk>', login_required(SubmissionDetail.as_view()), name='view_submission'), path('edit/<int:pk>', login_required(SubmissionUpdate.as_view( success_url=reverse_lazy('view_submission', kwargs={'pk': pk}))), name='edit_submission'), path('delete/<int:pk>', login_required(SubmissionDelete.as_view( success_url=reverse_lazy('all_submissions'))), name='delete_submission'), ] Thanks! -
django-simple-history Sum of columns for each historical snapshot
I've been trying to get the sum of one colum in my database. I know how to do it but when it comes to using django-simple-history and get the value for each snapshot (24 hours), I can't. It just returns the value for all snapshots together. How would I construct the correct ORM to get the individual value of each snapshot, so that I can use it inside my template to create a time graph with a for loop, that grabs each single snapshot in the db and the Node_Cores sum for that snapshot? Example of what i'm looking for: 17/07/19 - Sum = 190302 18/07/19 - Sum = 190583 19/07/19 - Sum = 190703 Views.py def networkOverview(request): GolemDatadb2 = GolemData.history.aggregate(Sum('Node_Cores')) print(GolemDatadb2) return render(request, 'golemstats/networkOverview.html', { 'GolemData':GolemDatadb2, }) Template: <script> var timeFormat = 'DD-MM-YYYY'; var config2 = { type: 'line', data: { datasets: [{ label: "Lorem", data: [{%for h in GolemData %} { x: "{{ h.history_date|date:" d / m / Y " }}", y: {{ h.Node_Cores}} }, {% endfor %}], fill: false, borderColor: 'red' }, ] }, options: { responsive: true, title: { display: false, text: "Core count by day" }, legend: { display: false }, scales: { xAxes: [{ … -
Is there a way to use an active Bootstrap element as an input to a Django form?
I want to use a Bootstrap list group as seen here as a choice selection tool in a form. One of the list items in the said Bootstrap list can have an active attribute at a time. I was hoping to map that active attribute to a choice in a Django forms.ChoiceField, thus making the list into a radio button of sorts. -
Django App not compatible with buildpack: App not compatible with buildpack: https://.../python.tgz
I want to deploy my django application on Heroku. But it seems impossible. after git push heroku master it says: Counting objects: 99, done. Delta compression using up to 4 threads. Compressing objects: 100% (97/97), done. Writing objects: 100% (99/99), 2.51 MiB | 98.00 KiB/s, done. Total 99 (delta 22), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to mammadovs. remote: To https://git.heroku.com/mammadovs.git Although, I didn't forget declaring heroku buildpacks:set heroku/python -
How to change data in database by clicking a button in HTML with Django
I have a mini project with Django. I have just a model with a counter total : class Reponse(models.Model): total = models.IntegerField() I have this view: def questions(request): _reponse = get_object_or_404(Reponse, id= 1) return render(request, 'vautmieux/test.html', {'reponse': _reponse}) And my HTML test display the variable total: <p id="block1"> {{reponse.total}} </p> My question is : I would like when I click on a button in the HTML, the variable total increases by 1. How can I do that ? With a form POST or GET ? May be there is a better method ?