How do i filter Django list using my bootstrap form?
I have been using Django and its default admin templates for my app. There is a certain list view for which I have decided to create my own bootstrap form for filtering objects. I want the values in the form fields to be used to filter on the queryset. How do I POST the data to Django and tell it to reload the page bearing in mind the choices in the form? Basically, how do I tell Django to "refresh this page" but apply the values in the form to queryset? Here is my code for the customized list
{% extends 'admin/change_list.html' %}
{% load i18n admin_urls static admin_list %}
{% block extrastyle %}
{{ block.super }}
<link rel="stylesheet" type="text/css" href="{% static "admin/css/changelists.css" %}" />
{% if cl.formset %}
<link rel="stylesheet" type="text/css" href="{% static "admin/css/forms.css" %}" />
{% endif %}
{% if cl.formset or action_form %}
<script type="text/javascript" src="{% url 'admin:jsi18n' %}"></script>
{% endif %}
{{ media.css }}
{% if not actions_on_top and not actions_on_bottom %}
<style>
#changelist table thead th:first-child {width: inherit}
</style>
{% endif %}
{% endblock %}
{% block content_title %}
<h1> Activity Summary </h1>
{% endblock %}
{% block object-tools-items %}
{% if has_add_permission %}
{{ block.super }}
<!-- Modal -->
<button type="button" data-toggle="modal" data-target="#filterModal" class="btn btn-primary">Launch modal</button>
<div class="modal fade" id="filterModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Filter</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="user">Users:</label>
<input type="text" class="form-control" id="user">
</div>
<div class="form-group">
<label for="text">Date</label>
<input type="text" class="form-control" id="text">
</div>
<div class="checkbox">
<label><input type="checkbox"> Verified </label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn">Close</a>
<a href="#" class="btn btn-primary">Save changes</a>
</div>
</div>
</div>
</div>
{% endif %}
{% endblock %}
{% load humanize %}
{% block result_list %}
<script type="text/javascript">
$(document).ready(function() {
$("#user").autocomplete(
{
minLength: 2,
source: function (request, response)
{
$.ajax(
{
url: "/autocomplete/",
data: {term: request.term},
dataType: "json",
appendTo : "ui-id-1",
success: function (jsonDataReceivedFromServer)
{
//alert (JSON.stringify (jsonDataReceivedFromServer));
// console.log (jsonDataReceivedFromServer);
response ($.map(jsonDataReceivedFromServer, function (item)
{
console.log (item.firstname);
return {
id: item.firstname, value: item.email, label: item.firstname };
}));
}
});
},
});
});
</script>
<div class="results">
<table>
<thead>
<tr>
<th>
<div class="text">
<a href="#">Employee</a>
</div>
</th>
<th>
</table>
</div>
{% endblock %}
{% block pagination %}{% endblock %}
/r/djangolearning
https://redd.it/7d2kaj
I have been using Django and its default admin templates for my app. There is a certain list view for which I have decided to create my own bootstrap form for filtering objects. I want the values in the form fields to be used to filter on the queryset. How do I POST the data to Django and tell it to reload the page bearing in mind the choices in the form? Basically, how do I tell Django to "refresh this page" but apply the values in the form to queryset? Here is my code for the customized list
{% extends 'admin/change_list.html' %}
{% load i18n admin_urls static admin_list %}
{% block extrastyle %}
{{ block.super }}
<link rel="stylesheet" type="text/css" href="{% static "admin/css/changelists.css" %}" />
{% if cl.formset %}
<link rel="stylesheet" type="text/css" href="{% static "admin/css/forms.css" %}" />
{% endif %}
{% if cl.formset or action_form %}
<script type="text/javascript" src="{% url 'admin:jsi18n' %}"></script>
{% endif %}
{{ media.css }}
{% if not actions_on_top and not actions_on_bottom %}
<style>
#changelist table thead th:first-child {width: inherit}
</style>
{% endif %}
{% endblock %}
{% block content_title %}
<h1> Activity Summary </h1>
{% endblock %}
{% block object-tools-items %}
{% if has_add_permission %}
{{ block.super }}
<!-- Modal -->
<button type="button" data-toggle="modal" data-target="#filterModal" class="btn btn-primary">Launch modal</button>
<div class="modal fade" id="filterModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Filter</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="user">Users:</label>
<input type="text" class="form-control" id="user">
</div>
<div class="form-group">
<label for="text">Date</label>
<input type="text" class="form-control" id="text">
</div>
<div class="checkbox">
<label><input type="checkbox"> Verified </label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn">Close</a>
<a href="#" class="btn btn-primary">Save changes</a>
</div>
</div>
</div>
</div>
{% endif %}
{% endblock %}
{% load humanize %}
{% block result_list %}
<script type="text/javascript">
$(document).ready(function() {
$("#user").autocomplete(
{
minLength: 2,
source: function (request, response)
{
$.ajax(
{
url: "/autocomplete/",
data: {term: request.term},
dataType: "json",
appendTo : "ui-id-1",
success: function (jsonDataReceivedFromServer)
{
//alert (JSON.stringify (jsonDataReceivedFromServer));
// console.log (jsonDataReceivedFromServer);
response ($.map(jsonDataReceivedFromServer, function (item)
{
console.log (item.firstname);
return {
id: item.firstname, value: item.email, label: item.firstname };
}));
}
});
},
});
});
</script>
<div class="results">
<table>
<thead>
<tr>
<th>
<div class="text">
<a href="#">Employee</a>
</div>
</th>
<th>
</table>
</div>
{% endblock %}
{% block pagination %}{% endblock %}
/r/djangolearning
https://redd.it/7d2kaj
reddit
How do i filter Django list using my bootstrap... • r/djangolearning
I have been using Django and its default admin templates for my app. There is a certain list view for which I have decided to create my own...
Registration form shows too many fields after I make custom register form model
I'm trying to make a custom registration form, but am running into trouble.
My `forms.py` has this:
class RegisterForm(UserCreationForm):
'''
Form that makes user using just email as username
'''
error_messages= {
"password_mismatch": _("Passwords do not match."),
"duplicate_email": _("Email already exists."),
"unique": _("Email already exists"),
}
register_username= forms.EmailField(label=_("Email"), widget=forms.TextInput(attrs={"placeholder":"Email"}))
register_password1= forms.CharField(label=_("Password"), widget=forms.PasswordInput(attrs={"placeholder":"Password"}))
register_password2= forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput(attrs={"placeholder":"Confirm password"}))
def clean_username(self):
username = self.cleaned_data["username"]
try:
User._default_manager.get(username=username)
#if the user exists, then let's raise an error message
raise forms.ValidationError(self.error_messages['duplicate_email'], #user my customized error message
code='duplicate_email', #set the error message key
)
except User.DoesNotExist:
return username # great, this user does not exist so we can continue the registration process
class Meta:
model= User
fields= ("username",)
My `views.py` looks like this:
def login_register(request, template="pages/login_register.html"):
registration_form= RegisterForm()
return render(request, template, {"registration_form": registration_form})
Which leads to my registration form in `login_register.html` rendering like this:
<form method="post">
<input type="hidden" name="csrfmiddlewaretoken" value="CSRF-TOKEN-HERE">
<p><input autofocus="" id="id_username" maxlength="150" name="username" type="text" required=""></p>
<p><input id="id_password1" name="password1" type="password" required=""></p>
<p><input id="id_password2" name="password2" type="password" required=""></p>
<p><input id="id_register_username" name="register_username" placeholder="Email" type="text" required=""></p>
<p><input id="id_register_password1" name="register_password1" placeholder="Password" type="password" required=""></p>
<p><input id="id_register_password2" name="register_password2" placeholder="Confirm password" type="password" required=""></p>
<button class="btn btn-primary" type="submit">Register</button>
</form>
I only want the last three `input` tags to be used. My goal is for my registration form to have three fields: Email, password, and password confirmation. Why is Django loading the three extra top `input` fields and how do I prevent that?
/r/django
https://redd.it/7xn7pe
I'm trying to make a custom registration form, but am running into trouble.
My `forms.py` has this:
class RegisterForm(UserCreationForm):
'''
Form that makes user using just email as username
'''
error_messages= {
"password_mismatch": _("Passwords do not match."),
"duplicate_email": _("Email already exists."),
"unique": _("Email already exists"),
}
register_username= forms.EmailField(label=_("Email"), widget=forms.TextInput(attrs={"placeholder":"Email"}))
register_password1= forms.CharField(label=_("Password"), widget=forms.PasswordInput(attrs={"placeholder":"Password"}))
register_password2= forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput(attrs={"placeholder":"Confirm password"}))
def clean_username(self):
username = self.cleaned_data["username"]
try:
User._default_manager.get(username=username)
#if the user exists, then let's raise an error message
raise forms.ValidationError(self.error_messages['duplicate_email'], #user my customized error message
code='duplicate_email', #set the error message key
)
except User.DoesNotExist:
return username # great, this user does not exist so we can continue the registration process
class Meta:
model= User
fields= ("username",)
My `views.py` looks like this:
def login_register(request, template="pages/login_register.html"):
registration_form= RegisterForm()
return render(request, template, {"registration_form": registration_form})
Which leads to my registration form in `login_register.html` rendering like this:
<form method="post">
<input type="hidden" name="csrfmiddlewaretoken" value="CSRF-TOKEN-HERE">
<p><input autofocus="" id="id_username" maxlength="150" name="username" type="text" required=""></p>
<p><input id="id_password1" name="password1" type="password" required=""></p>
<p><input id="id_password2" name="password2" type="password" required=""></p>
<p><input id="id_register_username" name="register_username" placeholder="Email" type="text" required=""></p>
<p><input id="id_register_password1" name="register_password1" placeholder="Password" type="password" required=""></p>
<p><input id="id_register_password2" name="register_password2" placeholder="Confirm password" type="password" required=""></p>
<button class="btn btn-primary" type="submit">Register</button>
</form>
I only want the last three `input` tags to be used. My goal is for my registration form to have three fields: Email, password, and password confirmation. Why is Django loading the three extra top `input` fields and how do I prevent that?
/r/django
https://redd.it/7xn7pe
reddit
Registration form shows too many fields after I make... • r/django
I'm trying to make a custom registration form, but am running into trouble. My `forms.py` has this: class RegisterForm(UserCreationForm): ...
How do I use/ access a foreign key in views in Django?
I am making a programing etymology site in Django. It will have the etymology/history of programing terms. or
For example the term LET (in ECMA6):
> Let is a mathematical statement that was adopted by early programming languages like Scheme and Basic.
I am not clear on how to write views.
For instance, I want to return the term let and the text of the let terms. Let is in the Term table and text is in the Etymology table.
**EXAMPLE**
Here is what I would like to see returned for term_name=Let.
LET:
Let is a mathematical statement that was adopted by early programming languages like Scheme and Basic. Variables are considered low level entities not suitable for higher levels of abstraction, thus the desire of many language designers to introduce similar but more powerful concepts like in Clojure, F#, Scala, where let might mean a value, or a variable that can be assigned....
**MODELS**
Here are my models.
class Term(models.Model):
term_name=models.CharField(max_length=150)
term_type=models.CharField(max_length=150) #type of command
term_pub_date=models.DateTimeField('Term Pub Date')
def __str__(self):
return self.term_name
class Etymology(models.Model):
term = models.ForeignKey(Term, on_delete=models.CASCADE)
etymology_text=models.TextField()
classification=models.CharField(max_length=150) #prog or tool reference
etymology_votes = models.IntegerField(default=0)
# rating=
# user=
etymology_pub_date=models.DateTimeField('Ety date published')
def __str__(self):
return self.etymology_text[:50] + "..."
class Comment(models.Model):
etymology = models.ForeignKey(Etymology, on_delete=models.CASCADE)
comment_text= models.TextField()
comment_votes = models.IntegerField(default=0)
#rating=
#user=
comment_pub_date=models.DateTimeField('com pub date')
def __str__(self):
return self.comment_text[:50] + "..."
How do I write a view which accesses two tables at once. How would I write the view to return what I want to see from my models?
FYI:
Using Django 2.02 and Python 3.6. Also, I not highly experienced so simple
Citation:
JavaScript?, W. (2018). Why was the name 'let' chosen for block-scoped variable declarations in JavaScript?.
/r/django
https://redd.it/8ad8pe
I am making a programing etymology site in Django. It will have the etymology/history of programing terms. or
For example the term LET (in ECMA6):
> Let is a mathematical statement that was adopted by early programming languages like Scheme and Basic.
I am not clear on how to write views.
For instance, I want to return the term let and the text of the let terms. Let is in the Term table and text is in the Etymology table.
**EXAMPLE**
Here is what I would like to see returned for term_name=Let.
LET:
Let is a mathematical statement that was adopted by early programming languages like Scheme and Basic. Variables are considered low level entities not suitable for higher levels of abstraction, thus the desire of many language designers to introduce similar but more powerful concepts like in Clojure, F#, Scala, where let might mean a value, or a variable that can be assigned....
**MODELS**
Here are my models.
class Term(models.Model):
term_name=models.CharField(max_length=150)
term_type=models.CharField(max_length=150) #type of command
term_pub_date=models.DateTimeField('Term Pub Date')
def __str__(self):
return self.term_name
class Etymology(models.Model):
term = models.ForeignKey(Term, on_delete=models.CASCADE)
etymology_text=models.TextField()
classification=models.CharField(max_length=150) #prog or tool reference
etymology_votes = models.IntegerField(default=0)
# rating=
# user=
etymology_pub_date=models.DateTimeField('Ety date published')
def __str__(self):
return self.etymology_text[:50] + "..."
class Comment(models.Model):
etymology = models.ForeignKey(Etymology, on_delete=models.CASCADE)
comment_text= models.TextField()
comment_votes = models.IntegerField(default=0)
#rating=
#user=
comment_pub_date=models.DateTimeField('com pub date')
def __str__(self):
return self.comment_text[:50] + "..."
How do I write a view which accesses two tables at once. How would I write the view to return what I want to see from my models?
FYI:
Using Django 2.02 and Python 3.6. Also, I not highly experienced so simple
Citation:
JavaScript?, W. (2018). Why was the name 'let' chosen for block-scoped variable declarations in JavaScript?.
/r/django
https://redd.it/8ad8pe
reddit
How do I use/ access a foreign key in views in Django? • r/django
I am making a programing etymology site in Django. It will have the etymology/history of programing terms. or For example the term LET (in...
Django DRF + Djoser reset activation code
I have been successfully able to setup a Django app with Djoser token based authentication. I want to generate a activation code / url and make the user activate through that code / link for account activation or reset password.
The [Base Endpoints](https://djoser.readthedocs.io/en/latest/base_endpoints.html#user-resend-activation-e-mail) explains how to enable and utilize the activation using the endpoints. But how do I get to create the db models and generate activation code for the users? Am I missing something ?
/r/django
https://redd.it/evkr6d
I have been successfully able to setup a Django app with Djoser token based authentication. I want to generate a activation code / url and make the user activate through that code / link for account activation or reset password.
The [Base Endpoints](https://djoser.readthedocs.io/en/latest/base_endpoints.html#user-resend-activation-e-mail) explains how to enable and utilize the activation using the endpoints. But how do I get to create the db models and generate activation code for the users? Am I missing something ?
/r/django
https://redd.it/evkr6d
KeyError: 'id' in django rest framework when trying to use updateorcreate() method
I am trying to update the OrderItem model using update_or_create() method. OrderItem model is related to the Order model with many to one relationship ie with a Foreignkey.
I am trying to query the orderitem object using id and update the related fields using default as you can see, but got this error.
My models:
class Order(models.Model):
user = models.ForeignKey(User, ondelete=models.CASCADE, blank=True)
ordereddate = models.DateTimeField(autonowadd=True)
ordered = models.BooleanField(default=False)
totalprice = models.CharField(maxlength=50,blank=True,null=True)
#billingdetails = models.OneToOneField('BillingDetails',ondelete=models.CASCADE,null=True,blank=True,relatedname="order")
def str(self):
return self.user.email
class Meta:
verbosenameplural = "Orders"
ordering = ('-id',)
class OrderItem(models.Model):
#user = models.ForeignKey(User,ondelete=models.CASCADE,
/r/django
https://redd.it/mfka4n
I am trying to update the OrderItem model using update_or_create() method. OrderItem model is related to the Order model with many to one relationship ie with a Foreignkey.
I am trying to query the orderitem object using id and update the related fields using default as you can see, but got this error.
My models:
class Order(models.Model):
user = models.ForeignKey(User, ondelete=models.CASCADE, blank=True)
ordereddate = models.DateTimeField(autonowadd=True)
ordered = models.BooleanField(default=False)
totalprice = models.CharField(maxlength=50,blank=True,null=True)
#billingdetails = models.OneToOneField('BillingDetails',ondelete=models.CASCADE,null=True,blank=True,relatedname="order")
def str(self):
return self.user.email
class Meta:
verbosenameplural = "Orders"
ordering = ('-id',)
class OrderItem(models.Model):
#user = models.ForeignKey(User,ondelete=models.CASCADE,
/r/django
https://redd.it/mfka4n
reddit
KeyError: 'id' in django rest framework when trying to use...
I am trying to update the OrderItem model using update\_or\_create() method. OrderItem model is related to the Order model with many to one...
Setting up Django with uWSGI and nginx - I've been trying to figure this out for 5 days now. Please help...
I'm trying to set up nginx server with my django app and uWSGI, by following this tutorial: https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html
I've been able to follow it up until the socket testing. The test itself doesn't produce an error, but localhost:8000 always returns 502 bad gateway error. I have been troubleshooting this for hours but can't figure out what I'm doing wrong.
/etc/nginx/nginx.conf:
```
#user http;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
# load configs
include /etc/nginx/sites-enabled/*;
types_hash_max_size 4096;
server_names_hash_bucket_size 128;
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root /home/<userprofile>/Projects/<project-name>/mymoon/journey/templates/journey/; # /usr/share/nginx/html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
}
```
/etc/nginx/sites-available/mymoon.conf
```
# mymoon_nginx.conf
# the upstream component nginx needs to connect to
upstream django {
server unix:///home/Projects/<project-name>/mymoon/journey/journey.sock; # for a file socket
server 127.0.0.1:8001; # for a web port socket (we'll use this first)
}
# configuration of the server
server {
# the port your site will be served on
listen
/r/djangolearning
https://redd.it/sc7jt2
I'm trying to set up nginx server with my django app and uWSGI, by following this tutorial: https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html
I've been able to follow it up until the socket testing. The test itself doesn't produce an error, but localhost:8000 always returns 502 bad gateway error. I have been troubleshooting this for hours but can't figure out what I'm doing wrong.
/etc/nginx/nginx.conf:
```
#user http;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
# load configs
include /etc/nginx/sites-enabled/*;
types_hash_max_size 4096;
server_names_hash_bucket_size 128;
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root /home/<userprofile>/Projects/<project-name>/mymoon/journey/templates/journey/; # /usr/share/nginx/html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
}
```
/etc/nginx/sites-available/mymoon.conf
```
# mymoon_nginx.conf
# the upstream component nginx needs to connect to
upstream django {
server unix:///home/Projects/<project-name>/mymoon/journey/journey.sock; # for a file socket
server 127.0.0.1:8001; # for a web port socket (we'll use this first)
}
# configuration of the server
server {
# the port your site will be served on
listen
/r/djangolearning
https://redd.it/sc7jt2
reddit
Setting up Django with uWSGI and nginx - I've been trying to...
I'm trying to set up nginx server with my django app and uWSGI, by following this tutorial:...
How to make a thread to make 100 concurrent request to db in Python ?
I want to simulate 120 people booking 120 seats all at once, how should I do that!!
This is what I am doing for the same
for i in range(120):
thread = Thread(target=book, args=(GetUser(i),)).start()
thread.join()
This is what my book function looks like:
def book(user): #user -> airline.User, seat -> airline.Seat
print(user1 + "with id " + str(user0) + " trying to book seat ")
seats = availableseats()
print("Total Available seats: " + str(seats[0]))
#selecting the seat at random
seat = random.randint(1, seats[0])
seat = GetSeat(seat)
print("Seat selected: " + str(seat[1]))
mycursor.execute("UPDATE seats SET USERID = " + str(user0) + " WHERE id = " + str(seat0))
mydb.commit()
But with this approach I am getting 2
/r/django
https://redd.it/ywqm7a
I want to simulate 120 people booking 120 seats all at once, how should I do that!!
This is what I am doing for the same
for i in range(120):
thread = Thread(target=book, args=(GetUser(i),)).start()
thread.join()
This is what my book function looks like:
def book(user): #user -> airline.User, seat -> airline.Seat
print(user1 + "with id " + str(user0) + " trying to book seat ")
seats = availableseats()
print("Total Available seats: " + str(seats[0]))
#selecting the seat at random
seat = random.randint(1, seats[0])
seat = GetSeat(seat)
print("Seat selected: " + str(seat[1]))
mycursor.execute("UPDATE seats SET USERID = " + str(user0) + " WHERE id = " + str(seat0))
mydb.commit()
But with this approach I am getting 2
/r/django
https://redd.it/ywqm7a
reddit
How to make a thread to make 100 concurrent request to db in Python ?
Posted in r/django by u/suraj_78797 • 9 points and 12 comments
Runtime error: working outside of app context - confused by this
I've got the error above when I try execute a simple:
>User.query.all() #User is a model
This works fine on one device/environment. I can query in the app.py file, or from another file by importing app and User from app.py
I pushed to git, cloned the repo, and now I get this error when running the line above on a different device and environment. The app itself will run, but not the queries.
I'm confused as to why the same code would work on one env but not another, if it was dependency related wouldn't I be getting 'module not found' or something else, not this runtime error?
/r/flask
https://redd.it/z0wmuo
I've got the error above when I try execute a simple:
>User.query.all() #User is a model
This works fine on one device/environment. I can query in the app.py file, or from another file by importing app and User from app.py
I pushed to git, cloned the repo, and now I get this error when running the line above on a different device and environment. The app itself will run, but not the queries.
I'm confused as to why the same code would work on one env but not another, if it was dependency related wouldn't I be getting 'module not found' or something else, not this runtime error?
/r/flask
https://redd.it/z0wmuo
reddit
Runtime error: working outside of app context - confused by this
I've got the error above when I try execute a simple: >User.query.all() #User is a model This works fine on one device/environment. I can query...
How to refresh a div without refreshing the whole page ?
I have a view that is used to block and unblock users. In my template all the users are listed inside a table. What I want to do is I want to refresh a specific portion of the div rather than the whole page while clicking block and unblock user. How to do that?
​
views.py
​
def block_user(request, id):
blocked_user = MyUser.objects.get(id=id)
blocked_user.is_active = False
blocked_user.save()
print("Blocked user is", blocked_user)
print("Is active status of blocked user is", blocked_user.is_active)
return redirect("usermanager")
​
​
def unblock_user(request, id):
user_to_unblock = MyUser.objects.get(id=id)
user_to_unblock.is_active = True
user_to_unblock.save()
print("Unblocked user is", user_to_unblock)
print("Is active status of blocked user is", user_to_unblock.is_active)
return redirect("usermanager")
​
templates
<div class="page-title text-center mt-4 mb-3">
<h5>User List</h5>
</div>
<div class="page-subtitle ms-3 mt-5">
<p style="color: black;">All Users : {{no_of_filtered_users}}</p>
</div>
<div class="table-wrapper" id="user-table">
<table class="table ms-4 me-3">
<tr>
<th>#</th>
<th>Email ID</th>
<th>Customer Name</th>
<th>Mobile Number</th>
<th>Blocked Status</th>
<th>Actions</th>
</tr>
{% for item in users %} {% if not item.is_superuser %}
<tr>
<td>
<img src="{% static 'images/user.png'%}" style="height: 30px;" alt="head" />
</td>
<td>{{item.email}}</td>
<td>{{item.first_name}} {{item.last_name}}</td>
<td>{{item.mobile_number}}</td>
<td>
{% if item.is_active %} {{'Authorized'}} {% else %} {{'Blocked!'}} {% endif %}
</td>
<td>
{% if item.is_active %}
<button class="btn btn-sm btn-danger" onclick="blockUser();refreshDiv()" id="blockbtn" data-url="{% url 'blockuser' item.id %}">Block User</button>
{% else %}
<button class="btn btn-sm btn-success" onclick="unblockUser();refreshDiv()" id="unblockbtn" data-url="{% url 'unblockuser' item.id %}">Unblock User</button>
{% endif %}
</td>
</tr>
{% endif %} {% endfor %}
</table>
</div>
In scripts I have given a jquery function, but it does not seem to work. Please help me out.
​
<script>
function refreshDiv(){
$('#user-table').load(location.href + "#user-table");
/r/django
https://redd.it/z9naoz
I have a view that is used to block and unblock users. In my template all the users are listed inside a table. What I want to do is I want to refresh a specific portion of the div rather than the whole page while clicking block and unblock user. How to do that?
​
views.py
​
def block_user(request, id):
blocked_user = MyUser.objects.get(id=id)
blocked_user.is_active = False
blocked_user.save()
print("Blocked user is", blocked_user)
print("Is active status of blocked user is", blocked_user.is_active)
return redirect("usermanager")
​
​
def unblock_user(request, id):
user_to_unblock = MyUser.objects.get(id=id)
user_to_unblock.is_active = True
user_to_unblock.save()
print("Unblocked user is", user_to_unblock)
print("Is active status of blocked user is", user_to_unblock.is_active)
return redirect("usermanager")
​
templates
<div class="page-title text-center mt-4 mb-3">
<h5>User List</h5>
</div>
<div class="page-subtitle ms-3 mt-5">
<p style="color: black;">All Users : {{no_of_filtered_users}}</p>
</div>
<div class="table-wrapper" id="user-table">
<table class="table ms-4 me-3">
<tr>
<th>#</th>
<th>Email ID</th>
<th>Customer Name</th>
<th>Mobile Number</th>
<th>Blocked Status</th>
<th>Actions</th>
</tr>
{% for item in users %} {% if not item.is_superuser %}
<tr>
<td>
<img src="{% static 'images/user.png'%}" style="height: 30px;" alt="head" />
</td>
<td>{{item.email}}</td>
<td>{{item.first_name}} {{item.last_name}}</td>
<td>{{item.mobile_number}}</td>
<td>
{% if item.is_active %} {{'Authorized'}} {% else %} {{'Blocked!'}} {% endif %}
</td>
<td>
{% if item.is_active %}
<button class="btn btn-sm btn-danger" onclick="blockUser();refreshDiv()" id="blockbtn" data-url="{% url 'blockuser' item.id %}">Block User</button>
{% else %}
<button class="btn btn-sm btn-success" onclick="unblockUser();refreshDiv()" id="unblockbtn" data-url="{% url 'unblockuser' item.id %}">Unblock User</button>
{% endif %}
</td>
</tr>
{% endif %} {% endfor %}
</table>
</div>
In scripts I have given a jquery function, but it does not seem to work. Please help me out.
​
<script>
function refreshDiv(){
$('#user-table').load(location.href + "#user-table");
/r/django
https://redd.it/z9naoz
Cant register users using this view with REST (Invalid password format or unknown hashing algorithm)
@api_view(['POST'])
def register(request):
serializer=UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
#user=User.objects.create_user(username=request.data['username'])
#user.set_password(request.data['password']) #hash password
#user.save()
user=User.objects.get(username=request.data['username'])
token=Token.objects.create(user=user) #create token
return Reponse({"token":token.key, "user":serializer.data})
else:
return Response(serializer.errors)
Everything commented is something i tried before
imports:
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
User serializer:
class UserSerializer(serializers.ModelSerializer):
class Meta(object):
model= User
fields = ['id','username','password','email']
​
/r/djangolearning
https://redd.it/181xhg4
@api_view(['POST'])
def register(request):
serializer=UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
#user=User.objects.create_user(username=request.data['username'])
#user.set_password(request.data['password']) #hash password
#user.save()
user=User.objects.get(username=request.data['username'])
token=Token.objects.create(user=user) #create token
return Reponse({"token":token.key, "user":serializer.data})
else:
return Response(serializer.errors)
Everything commented is something i tried before
imports:
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
User serializer:
class UserSerializer(serializers.ModelSerializer):
class Meta(object):
model= User
fields = ['id','username','password','email']
​
/r/djangolearning
https://redd.it/181xhg4
Reddit
From the djangolearning community on Reddit
Explore this post and more from the djangolearning community
Send email with Flask
Hello everyone, does anyone know why I can only send emails to my email, which is where the app was created? When I try to send a message to another email, I don't get any error, but the email doesn't arrive. You can see the code in the pictures.
project.config'MAIL_SERVER' = 'smtp.gmail.com'
project.config'MAIL_PORT' = 465
project.config'MAIL_USERNAME' = 'my email'
project.config'MAIL_PASSWORD' = 'app password'
project.config'MAIL_USE_SSL' = True
project.config'MAIL_USE_TLS' = False
Or here:
def renderregistration():
message = ''
if flask.request.method == "POST":
emailform = flask.request.form"email"
numberform = flask.request.form["phonenumber"]
nameform = flask.request.form["name"]
surnameform = flask.request.form"surname"
mentorform = flask.request.form["mentor"]
#User.query.filterby(email =
/r/flask
https://redd.it/1kc4wv1
Hello everyone, does anyone know why I can only send emails to my email, which is where the app was created? When I try to send a message to another email, I don't get any error, but the email doesn't arrive. You can see the code in the pictures.
project.config'MAIL_SERVER' = 'smtp.gmail.com'
project.config'MAIL_PORT' = 465
project.config'MAIL_USERNAME' = 'my email'
project.config'MAIL_PASSWORD' = 'app password'
project.config'MAIL_USE_SSL' = True
project.config'MAIL_USE_TLS' = False
Or here:
def renderregistration():
message = ''
if flask.request.method == "POST":
emailform = flask.request.form"email"
numberform = flask.request.form["phonenumber"]
nameform = flask.request.form["name"]
surnameform = flask.request.form"surname"
mentorform = flask.request.form["mentor"]
#User.query.filterby(email =
/r/flask
https://redd.it/1kc4wv1
Reddit
From the flask community on Reddit
Explore this post and more from the flask community
What could I have done better here?
Hi, I'm pretty new to Python, and actual scripting in general, and I just wanted to ask if I could have done anything better here. Any critiques?
import time
import colorama
from colorama import Fore, Style
color = 'WHITE'
colorvar2 = 'WHITE'
#Reset colors
print(Style.RESETALL)
#Get current directory (for debugging)
#print(os.getcwd())
#Startup message
print("Welcome to the ASCII art reader. Please set the path to your ASCII art below.")
#Bold text
print(Style.BRIGHT)
#User-defined file path
path = input(Fore.BLUE + 'Please input the file path to your ASCII art: ')
color = input('Please input your desired color (default: white): ' + Style.RESETALL)
#If no ASCII art path specified
if not path:
print(Fore.RED +
/r/Python
https://redd.it/1p4ffmh
Hi, I'm pretty new to Python, and actual scripting in general, and I just wanted to ask if I could have done anything better here. Any critiques?
import time
import colorama
from colorama import Fore, Style
color = 'WHITE'
colorvar2 = 'WHITE'
#Reset colors
print(Style.RESETALL)
#Get current directory (for debugging)
#print(os.getcwd())
#Startup message
print("Welcome to the ASCII art reader. Please set the path to your ASCII art below.")
#Bold text
print(Style.BRIGHT)
#User-defined file path
path = input(Fore.BLUE + 'Please input the file path to your ASCII art: ')
color = input('Please input your desired color (default: white): ' + Style.RESETALL)
#If no ASCII art path specified
if not path:
print(Fore.RED +
/r/Python
https://redd.it/1p4ffmh
Reddit
From the Python community on Reddit
Explore this post and more from the Python community