Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use the value of an input field in calculation, and display the result in another element
I have a shopping cart, with a price, quantity, and subtotal field for each product. The quantity field can be changed by the user, but the other fields are static. Is there a way to calculate the subtotal when the quantity is changed by the user? I want to multiply the quantity with the price, then update the subtotal, without the need for the user to submit the form. Also, when a subtotal is calculated, the total should be updated as well. Visual representation here My code is a Django template and looks like this, with the relevant part in the loop: <div class="container"> <table id="cart" class="table table-hover table-condensed"> <thead> <tr> <th style="width:50%">Product</th> <th style="width:10%">Price</th> <th style="width:8%">Quantity</th> <th style="width:22%" class="text-center">Subtotal</th> </tr> </thead> {% for crops_ordered_names,crops_ordered_images,crops_ordered_cost,crops_ava in total %} <tbody> <tr> <td data-th="Product"> <div class="row"> <div class="col-sm-2 hidden-xs"><img src="http://placehold.it/100x100" alt="..." class="img-responsive"/></div> <div class="col-sm-10"> <h4 class="nomargin">{{crops_ordered_names}}</h4> <p>Available amount: {{crops_ava}}</p> </div> </div> </td> <td data-th="Price" id="price">{{crops_ordered_cost}}</td> <td data-th="Quantity"> <input type="number" class="form-control text-center" id="quan" min="1" max="{{crops_ava}}"> </td> <td data-th="Subtotal" class="text-center" id="subtotal"></td> <td class="actions" data-th=""> <button class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i></button> </td> </tr> </tbody> {% endfor %} <tfoot> <tr class="visible-xs"> <td class="text-center"><strong>Total 1.99</strong></td> </tr> <tr> <td colspan="2" class="hidden-xs"></td> <td class="hidden-xs text-center" id="total"><strong>Total </strong></td> </tr> </tfoot> … -
Does Django have a built-in application for location awareness?
I will be asking users when signing up to provide their location. Does Django have a built-in application for this? If not, can anyone recommend a third-party package? The idea is for users to search for other users based on a certain mile range. -
How to redirect from a Django View to some other view
For example if I have a view where I do some conversion according to the text-box input. Then I want to redirect to somewhere after the conversion is done, where the user can see the results. def main(){ //Some Conversion going on // After the conversion is done redirect to somewhere else if(conversion == done): return redirect('/somewhere') return render('index.html') } -
Efficiently update multiple fields in Django
Django beginner here. I have a many-to-many model and want to update multiple values at once. This is the model (simplified): class Inventory(models.Model): item = models.ForeignKey(Items, models.CASCADE) player = models.ForeignKey(Players, models.CASCADE) count = models.PositiveIntegerField() What I do right now is this: for key in dict: change_value = Inventory.objects.get(player=player, item=key) change_value.count += dict[key] change_value.save() At least on my HDD test environment this is very slow. Is there a more efficient way of doing this? In other posts it was suggested to use update instead, so this would be: for key in dict: Inventory.objects.get(player=player, item=key).update(count=dict[key]) Would this be faster? Could this be improved even further by updating multiple entries at once? Also, is there an efficient way of adding multiple new entries? -
How to override river-admin template?
Firstly , i would like to say that this package is amazing in the sense where there can be so much flexibility. Im relatively new to this package and im just trying to figure a way to fiddle around with the provided front end in the river-admin package. Could someone point me in the correct direction in doing so? -
Django, environment variables. Error: SMTPRecipientsRefused at /password_reset/
it's my first post here. I'm learning Django, and i'm trying to send an email to reset my password. There is one problem.. When I send an email with my username and password assigned to these constants, everything works well: EMAIL_HOST_USER = 'abc.def@gmail.com' EMAIL_HOST_PASSWORD = 'Abc123' But when i try to use environment variables instead: EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') i got an error SMTPRecipientsRefused at /password_reset/ {'abc.def@gmail.com': (501, b': sender address must contain a domain')} Am I doing something wrong? Maybe I should use environment variables in different ways? In advance, thanks for your help, guys! -
can we work with Django authentication without builtin Django forms
I want to use input field for authentication but if I search for authentication tutorial they are using built-in Django forms which I can't design it using html -
how to implement a movie review system using sentimental analysis in python using django
Take a movie as a input from a user and pass it as a argument to our python file and our program will do a sentimental analysis on movie comments and give output wheather a movie is worth watching or not . framework used is django , backend language python and movie reviews collected from rottentomatoes. -
How to specify basehref in Django
Is it possible to launch Django app depending on .env configuration with BASEPATH=/api or just BASEPATH=/? -
404 error when deploying django project with apache2
I tried to create a new django project on apache2, but I got 404 error. Here are what I did. -In /home/ubuntu/django directory, type django-admin startproject proj -Edit proj/proj/wsgi.py as follows. import os import sys from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') sys.path.append('/home/ubuntu/django/proj'); sys.path.append('/home/ubuntu/django/proj/proj'); application = get_wsgi_application() -Edit ALLOWED_HOSTS in proj/proj/settings.py as follows. ALLOWED_HOSTS = ['example.com'] -Edit /etc/apache2/conf-available/wsgi.conf as follows. WSGIScriptAlias /proj /home/ubuntu/django/proj/proj/wsgi.py WSGIPythonPath /home/ubuntu/django/proj <Directory /home/ubuntu> Require all granted </Directory> <Directory /home/ubuntu/proj/proj> <Files wsgi.py> Require all granted </Files> </Directory> -Restart apache2 as /etc/init.d/apache2 restart -Access to http://example.com/proj, and then got 404 error as follows. Page not found (404) Request Method: GET Request URL: http://example.com/proj/ Using the URLconf defined in proj.urls, Django tried these URL patterns, in this order: admin/ The empty path didn't match any of these. My enviroment is as follows. Ubuntu 18.04 LTS (AWS) Apache/2.4.29 Python 3.6.9 Django 3.0.5 How can I solve this 404 error? -
Django graphql JWT authentication gives anonymous user although valid token is given
I'm following this tutorial on authentication with django-graphql-jwt. I'm failing at step Testing the Authentication. I get a valid token via ObtainJSONWebToken but when I insert this token into the HTTP header authorization and perform a query (me) that checks the user status it gives an anonymous user. When I am logged in via django admin page it works without any token. It seems like the middleware is not working properly but that is just a guess. Here my code and what I do: settings.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] GRAPHENE = { 'SCHEMA': 'schema.py', 'MIDDLEWARE': [ 'graphql_jwt.middleware.JSONWebTokenMiddleware' ] } schema.py class Query(teamorgaisation_queries.Query, users_queries.Query, graphene.ObjectType): # this class inherits multiple Queries as we add more apps with their own schema pass class Mutation(teamorganisation_mutations.Mutation, users_mutations.Mutation, graphene.ObjectType): token_auth = graphql_jwt.ObtainJSONWebToken.Field() verify_token = graphql_jwt.Verify.Field() refresh_token = graphql_jwt.Refresh.Field() me-query import graphene from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from voss_be_django.users.graphql.types import UserType class Query(graphene.ObjectType): me = graphene.Field(UserType) def resolve_me(self, info): user = info.context.user if user.is_anonymous: raise Exception('Not logged in!') return user Postman query without authorization header: mutation tokenAuth($username: String!, $password: String!){ tokenAuth(username: $username, password: $password){ token } } variables: { "username": "testUser", "password": "UserTest#1234" } response (inside … -
Django static url with digitalocean spaces
I have an droplet on digitalocean which for the most part is working great, however i have enabled the cdn option in digitalocean spaces (similar to aws s3 storage) and in trying to load static files using the cdn url, i cannot seem to get the url working correctly so suspect i am missing the obvious? For example when i change the STATIC_URL in settings to the cdn no change is seen in the web page source? If i change the AWS_S3_ENDPOINT_URL and MEDIA_ENDPOINT_URL then the source does change but the files are not found and as one can guess a collectstatic no longer works, So i assume that the AWS_S3_ENDPOINT_URL & MEDIA_ENDPOINT_URL need to remain as is and i merely need to ensure the static_url is used? I did read somewhere that it was not good practice to change the templates from {%static.... to {%static_url so have not done that, is this something i should update or not? Settings: AWS_S3_ENDPOINT_URL = 'https://nyc3.digitaloceanspaces.com' MEDIA_ENDPOINT_URL = 'https://nyc3.digitaloceanspaces.com/media/' AWS_STORAGE_BUCKET_NAME = 'mysitestaging' #STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # if False it will create unique file names for every uploaded file AWS_S3_FILE_OVERWRITE = False STATICFILES_STORAGE = 'mysite.settings.storage_backends.StaticStorage' DEFAULT_FILE_STORAGE = 'mysite.settings.storage_backends.MediaStorage' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } … -
How to limits some users to view Django admin content by default permission
Am new to Django I have developed app in Django, when I assign view permission allowed to view content Question is this how can I override default view permission to allow user to his own created content on admin site Any help appreciated -
how does django get_next_by_FOO() query work?
i want to know how get_next_by_FOO()/get_previous_by_FOO() fetch data from database. anyone know the SQL code for that?. can anyone tell me how it works behind the scene? -
Django Authentication - Page redirecting to home even it goes in to exception
I am doing Simple User Registration part of my project, using Django's User table. Which supposed to redirect to home page after successful user registration and its login only, but even though I am filling up duplicate (incorrect)entry for username, its going to home page instead of showing the error on Sign up page. P.S - Tried to keep the question short, not displayed unnecessary code Please do read comments in the code and logs, added extra explanation there def register(request): if request.method == 'POST': reqdict = to_reqdict(request) print("user.is_authenticated", reqdict) # This statement printed in the logs username = reqdict.get('email') first_name = reqdict.get('first_name') last_name = reqdict.get('last_name') raw_password = reqdict.get('password') try: clear_old_sessions(request) user = User.objects.create_user(username=username,first_name=first_name, last_name=last_name,email=username, password=raw_password) user.save() user = authenticate(username=username, password=raw_password) login(request, user) print("user.is_authenticated>>>>>", user.is_authenticated) # This does not get printed in the logs return redirect(reverse('home')) # Only this line redirects page to home page except IntegrityError as e: messages.error(request, "User already exists!") print("error", e) except Exception as e: print("Other error", e) messages.error(request, "User already exists!") return render(request, template_name="signup.html") else: return render(request, template_name="signup.html") See the logs for detail: System check identified no issues (0 silenced). April 13, 2020 - 15:51:54 Django version 3.0.5, using settings 'backend.settings' Starting development server at … -
Change function to class view django
I'm doing a django app and at first I've done methods to my view, but I'd like now to change to class. Here's an exemple of how I tried : def register(response): if response.method == "POST": form = RegisterForm(response.POST) if form.is_valid(): form.save() return redirect("/login") else: form = RegisterForm() return render(response, "register/register.html", {"form":form}) And tried to change like this : class RegisterView(generic.View): def post(self, request): form = RegisterForm(response.POST) if form.is_valid(): form.save() return redirect("/login") else: form = RegisterForm() return render(response, "register/register.html", {"form":form}) But I keep getting a 405 Error Method not allowed, I guess it's because I'm not doing right the changing from method to class. Any idea ? -
How to calculate the value of two html tags and output it to other tag
Is there any way to calculate the subtotal using (price * quantity), quantity is the number tag which needs to be entered by the user. Then all the subtotals should be added to the total. Can this all be done without submitting any form?(Price * quantity = Subtotal) -
Where is Django's own database?
This question asks where the Django installation is. This question is about the table django_migrations. I've looked under the path from the command django in the interactive console, where I find a subdirectory db, along with middleware, etc. But I've no idea where this table django_migrations (i.e. the data in it) is in fact kept. I want to know firstly because I want to know what happens if this data is lost. I'm just learning Django and I don't quite understand how much of a problem this would be. The path to the Django location is under a directory in my home folder where I keep my Python virtual environments, the name of which begins with a ".". I tend to exclude such directories from my backup plans... Having just deleted db.sqlite in my project I see that it gets regenerated when you do migrate, together with a list of (in my present case) some 15 migration operations. I'm quite mystified by some of these: the first 10 or so seem to have occurred before I started doing anything to my models.py file. Are they documented or explained somewhere? -
Managing timer based threads
I'll give some back story for context before the question. I'm currently creating a small Django based web site with some code on the back. This is basically a security scan website, so a Recon module is part of it. A user fills up a form and recon begins. Because many users can access the website at the same time, I handeled the call to recon method with threads, this way more than one user can actually use the website. Something like the following def recon_view(request): if request.method == 'POST': form = ReconForm(request.POST) if form.is_valid(): recon_thread = threading.Thread(name='Recon Process', target=recon.run_recon, args=(form,)) recon_thread.start() The next step is to implement some sort of monitoring mode, from what I have searched, one can use threads this way. threading.Timer(1, foo).start() The recon will run once a week or few days so time is not an issue. Would this be the correct approach? Woulnd't this mean that everytime the user starts a recon, the Thread will continue running basically until the server stops (Meaning possibly hundreds of threads at the same time). The other option I can think of is using a separate script that makes an API call to the website, triggering the recon -
Fetch modal data with Ajax from Django Model
Sorry for repeating this question, and Ajax integration since its very broad subject, but I just can't figure it out. I have a html table with 4k+ rows of data, and each of rows has some basic information like name, address, last name, phone, and a button which triggers a bootstrap modal which contains additional data like phone2, address 2, etc. My problem is, since my modal is located inside a for loop like this - <tbody> {% for opp in optika %} <tr> <td>{{ opp.example }}</td> <td>{{ opp.some_field }}</td> <td> <button id="testbtn" type="button" class="btn btn-success btn-sm btn-detail" data-toggle="modal" data-target="#detalji_modal{{ opp.pk }}" Detalji </button> </td> ... </tr> {% include "opportunity/partials/_detalji_modal.html" %} {% endfor %} </tbody> And this is modal detail - <div class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" id="detalji_modal{{ opp.pk }}" aria-labelledby="detalji_modalLabel"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="detalji_modalLabel">Detalji</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body" id=""> <div class="container-fluid"> <h5>{{ opp.... }}</h5> <p>{{ opp.....title }}</p> ... </div> </div> <div class="modal-footer"> <p style="margin-right: auto">Zahtev uneo/la : {{ opp.... }}</p> ... ... <button type="button" class="btn btn-outline-primary" data-dismiss="modal"> Close </button> </div> </div> </div> </div> I'll pass the view also : @login_required(login_url='registration/login') def OptikaList(request): user_groups = request.user.groups.all() … -
Django runserver on BASEHREF
I have such bash script #!/bin/bash BASEHREF="0.0.0.0:8000/python-api" exec ./manage.py runserver "$BASEHREF" --settings api.settings.local But after launch I got such error CommandError: "0.0.0.0:8000/python-api/" is not a valid port number or address:port pair. How can I runserver with relative path? -
Django: How to iterate over form fields choices without knowing the fields name?
I have a form whose fields are created in its __init__method: class Form(forms.Form): def __init__(self, modelInstance, *args, **kwargs): super(Form, self).__init__(*args, **kwargs) # create fields based of modelInstance data (because it might change) self.fields[modelInstance.name] = models.ChoiceField(choices=SomeChoices, widget=forms.RadioSelect()) Therefore i can not know in advance how the field may be named. Now how can I iterate over the field choices without knowing its name? What I'd like: {% for field in form %} <p>sometext</p> {% for value, text in field.NAME.choices %} <input type="radio" name="{{ field.name }}" value="{{value}}" id="id_{{ field.name }}_{{forloop.counter0}}"> <label>{{text}}</label> </div> {% endfor %} {% endfor %} I know field.NAME only returns the actual field name and does not give me access to its choices. But how else can I do this? Any help is greatly appreciated! -
After inherited from AbstractUser, Django admin can not change user's permissions any more
I change django user model by inherited from AbstractUser, codes like the following. But I can not modify user permissions and change the group which user belong to any more in Django admin site. When I logon to admin as super user, go to the user page. The user'permissions can not be changed. Can anyone help? from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib import admin class UserProfile(AbstractUser): mobile = models.CharField(max_length=20, null=True, blank=True) avatar = models.CharField(max_length=100, null=True, blank=True) admin.site.register(UserProfile) #settings.py add this AUTH_USER_MODEL = 'users.UserProfile' -
Django. Hash password in models.py
I have a trigger in my database to create a password from another column and update it in the current database. Then I insert this password to another table. The problem is my project doesn't need a registration form as a new page. So only admin can add new users. The question sounds like: is there an opportunity to create a hash password in models? Or from another hand how to create password fill in models.py? models.py class Student(models.Model): studentIndex = models.IntegerField() studentName = models.CharField(max_length=50) studentSurname = models.CharField(max_length=50, default='') studentPhoneNumber = models.CharField(max_length=12, default='+48') studentPesel = models.CharField(max_length=11, default='') studentStudyMode = models.CharField(max_length=12, default='') studentFaculty = models.CharField(max_length=30, default='') studentSemester = models.IntegerField(default='') studentAddress = models.CharField(max_length=255, default='') studentMotherName = models.CharField(max_length=100, default='') studentBirth = models.DateField(help_text='year-month-day') studentEmail = models.EmailField(max_length=255, default='') studentImage = models.ImageField(default='default.jpg', upload_to='profile_pics') studentPassword = models.CharField(max_length=100, default='12345678', help_text='Do not modify this field. Password will be generated automatically') studentDateJoined = models.DateTimeField(default=datetime.datetime.now()) def __str__(self): return f'{self.studentIndex} - {self.studentName} {self.studentSurname}' Trigger in user_student table CREATE TRIGGER add_new_student_with_correct_password after insert on users_student begin update users_student set studentPassword = strftime('%Y', studentBirth) || substr(strftime('%m', studentBirth), 2, 1) || strftime('%d', studentBirth) || substr(studentMotherName, 1, 1) || lower(substr(studentName, 1, 1)) where studentPassword = '12345678'; insert into auth_user(password, last_login, is_superuser, username, first_name, email, is_staff, is_active, … -
I'm trying to apply celery to Class based view(apis) in django. How can I do this?
Is it a correct way to apply celery to class based views? I think APIs are sync tasks... And, if it is, how can I apply celery to class based Views? I can’t apply just tagging @app.task above functions inside class. I failed to apply making tasks.py with functions and calling them inside functions in class.(it throws not JSON serializable error..) Please can someone give me the keryword to search with?