Sending db QuerySelectField to Flask over AJAX with postgresql - javascript

I am trying to implement AJAX in my forms but I'm not able to submit optional QuerySelectField data to the database.
The field itself is populated with values from another table, it should be optional and hidden for users with lower access level (should ne NULL in such case). If selected, it should insert value of id column corresponding to the selected entry.
The problem is that AJAX seems to completely ignore it and always submits it as NULL.
I am completely new to this, tried searching for possible solution but couldn't find anything.
my forms.py:
class DodajAdmin(FlaskForm):
name = StringField(_l('Imię'), validators=[DataRequired()])
surname = StringField(_l('Nazwisko'), validators=[DataRequired()])
email = StringField(_l('Email'), validators=[DataRequired(), Email()])
phone = StringField(('Nr telefonu'), validators=[DataRequired(),
Length(min=8, max=12, message='Nieprawidłowy nr telefonu')])
PESEL = StringField(('PESEL'), validators=[DataRequired(), Length(min=11, max=11, message='Nieprawidłowy PESEL')])
pkk = StringField(('Numer PKK'), validators=[DataRequired(), Length(min=20, max=20, message='PKK musi składać się z dokładnie 20 znaków')])
res_city = StringField(('Miasto zamieszkania'), validators=[DataRequired()])
res_address = StringField(('Ulica i nr domu/mieszkania'), validators=[DataRequired()])
notes = StringField(('Uwagi'))
submit = SubmitField(_l('Dodaj kursanta'))
def validate_pkk(self, pkk):
kursant = Kursant.query.filter_by(PKK=pkk.data).first()
if kursant is not None:
raise ValidationError(_('Kursant o podanym numerze PKK już istnieje!'))
def validate_email(self, email):
kursant = Kursant.query.filter_by(email=email.data).first()
if kursant is not None:
raise ValidationError(_('Kursant o podanym adresie email już istnieje!'))
def validate_pesel(self, PESEL):
kursant = Kursant.query.filter_by(PESEL=PESEL.data).first()
if kursant is not None:
raise ValidationError(_('Kursant o podanym numerze PESEL już istnieje!'))
def instructors():
return User.query.all()
def getformclass():
formclass = DodajAdmin
if current_user.access_level > 1 :
setattr(formclass, "instructor", QuerySelectField('Instruktor prowadzący', query_factory=instructors, blank_text='Brak (jeszcze nie wybrano)', allow_blank=True))
return formclass
routes.py
#bp.route('/students/add/', methods=['GET', 'POST'])
#login_required
def dodaj_kursanta():
form_class = getformclass()
form = form_class()
access_level = User.query.filter(User.id == current_user.id)
icon = 'fas fa-user-plus'
if request.method == 'POST':
if form.validate():
if current_user.access_level > 1:
kursant = Kursant(name=form.name.data, surname=form.surname.data, email=form.email.data, PKK=form.pkk.data, \
PESEL=form.PESEL.data, phone=form.phone.data, res_city=form.res_city.data, res_address=form.res_address.data, instruktor=form.instructor.data, notes=form.notes.data, added_by=current_user.id)
kursant = Kursant(name=form.name.data, surname=form.surname.data, email=form.email.data, PKK=form.pkk.data, \
PESEL=form.PESEL.data, phone=form.phone.data, res_city=form.res_city.data, res_address=form.res_address.data, added_by=current_user.id)
db.session.add(kursant)
db.session.commit()
return '<div id="success-message" class="alert alert-success">Pomyślnie dodano kursanta.</div>'
return jsonify(form.errors), 400
return render_template('pages/dodaj-kursanta.html', title='Dodaj kursanta', form=form, icon=icon)
template
<form id="form" method="POST">
{{ form.csrf_token }}
<div class="text-danger my-2" id="csrf_token-error">
</div>
<div class="form-group">
{{ form.name(class="form-control", placeholder="Imię") }}
<div id="name-error" class="invalid-feedback"></div>
</div>
<div class="form-group">
{{ form.surname(class="form-control", placeholder="Nazwisko") }}
<div id="surname-error" class="invalid-feedback"></div>
</div>
<div class="form-group">
{{ form.email(class="form-control", placeholder="Adres email") }}
<div id="email-error" class="invalid-feedback"></div>
</div>
<div class="form-group">
{{ form.phone(class="form-control", type="number", placeholder="Telefon") }}
<div id="phone-error" class="invalid-feedback"></div>
</div>
<div class="form-group">
{{ form.PESEL(class="form-control", type="number", placeholder="PESEL") }}
<div id="pesel-error" class="invalid-feedback"></div>
</div>
<div class="form-group">
{{ form.pkk(class="form-control", placeholder="PKK") }}
<div id="pkk-error" class="invalid-feedback"></div>
</div>
<div class="form-group">
{{ form.res_city(class="form-control", placeholder="Miasto") }}
<div id="res_city-error" class="invalid-feedback"></div>
</div>
<div class="form-group">
{{ form.res_address(class="form-control", placeholder="Ulica/Dom") }}
<div id="res_address-error" class="invalid-feedback"></div>
</div>
{% if current_user.access_level > 1 %}
<div class="form-group">
<label class="my-1 me-2">Instruktor prowadzący</label>
{{ form.instructor(class="form-control") }}
</div>
{% endif %}
<div class="form-group">
{{ form.submit(class="btn-lg btn-primary", style="width: 100%") }}
</div>
</form>
<script>
const form = document.getElementById('form');
const successMessage = document.getElementById('success-message');
const fields = {
csrf_token: {
input: document.getElementById('csrf_token'),
error: document.getElementById('csrf_token-error')
},
name: {
input: document.getElementById('name'),
error: document.getElementById('name-error')
},
surname: {
input: document.getElementById('surname'),
error: document.getElementById('surname-error')
},
email: {
input: document.getElementById('email'),
error: document.getElementById('email-error')
},
phone: {
input: document.getElementById('phone'),
error: document.getElementById('phone-error')
},
PESEL: {
input: document.getElementById('PESEL'),
error: document.getElementById('pesel-error')
},
pkk: {
input: document.getElementById('pkk'),
error: document.getElementById('pkk-error')
},
res_city: {
input: document.getElementById('res_city'),
error: document.getElementById('res_city-error')
},
res_address: {
input: document.getElementById('res_address'),
error: document.getElementById('res_address-error')
},
instructor: {
input: document.getElementById('instructor'),
error: document.getElementById('instructor-error')
}
}
form.addEventListener('submit', async (e) => {
e.preventDefault();
const response = await fetch('/students/add/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
csrf_token: fields.csrf_token.input.value,
name: fields.name.input.value,
surname: fields.surname.input.value,
email: fields.email.input.value,
phone: fields.phone.input.value,
PESEL: fields.PESEL.input.value,
pkk: fields.pkk.input.value,
res_city: fields.res_city.input.value,
res_address: fields.res_address.input.value,
instructor: fields.instructor.input.value
})
});
if (response.ok) {
successMessage.innerHTML = await response.text();
form.style.display = 'none';
successMessage.style.display = 'block';
} else {
const errors = await response.json();
Object.keys(errors).forEach((key) => {
fields[key].input.classList.add('is-invalid');
fields[key].error.innerHTML = errors[key][0];
});
}
});
</script>

Ok, I've managed to resolve the issue although I'm not certain why it behaved like described in the first place.
Turns out that moving second occurrence of variable 'kursant' in routes.py into else condition (see below) caused the form to pass all information correctly. For some reason it was attempting to insert the data twice within a single db session.
updated routes.py
#bp.route('/students/add/', methods=['GET', 'POST'])
#login_required
def dodaj_kursanta():
form_class = getformclass()
form = form_class()
access_level = User.query.filter(User.id == current_user.id)
icon = 'fas fa-user-plus'
if request.method == 'POST':
if form.validate():
if current_user.access_level > 1:
kursant = Kursant(name=form.name.data, surname=form.surname.data, email=form.email.data, PKK=form.pkk.data, \
PESEL=form.PESEL.data, phone=form.phone.data, res_city=form.res_city.data, res_address=form.res_address.data, instruktor=form.instructor.data, notes=form.notes.data, added_by=current_user.id)
else:
kursant = Kursant(name=form.name.data, surname=form.surname.data, email=form.email.data, PKK=form.pkk.data, \
PESEL=form.PESEL.data, phone=form.phone.data, res_city=form.res_city.data, res_address=form.res_address.data, added_by=current_user.id)
db.session.add(kursant)
db.session.commit()
return '<div id="success-message" class="alert alert-success">Pomyślnie dodano kursanta.</div>'
return jsonify(form.errors), 400
return render_template('pages/dodaj-kursanta.html', title='Dodaj kursanta', form=form, icon=icon)

Related

How to allow JSON access to the text within a textarea in HTML>

I am trying to create a button that allows users to save edits to a post, which they write in a textarea, through JSON. I am trying to save the data through a PUT request, but I get the following error:
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
javascript function:
function save_edit(id){
console.log("save button is clicked");
const edit_area = document.querySelector(`#edit_area_${id}`);
//save the post
fetch(`/edit/${id}`,{
method: 'PUT',
post: JSON.stringify({
post: edit_area.value
})
})
fetch(`/edit/${id}`)
.then(response => response.json())
.then(post => {
const post_itself =
document.querySelector(`#post_itself_${id}`);
post_itself.value = `${post.post}`;
post_itself.style.display = 'block';
})
}
django.views:
def edit(request, post_id):
try:
post = Post.objects.get(pk=post_id)
except Post.DoesNotExist:
return JsonResponse({"error": "Post not found."}, status=404)
if request.method == "POST":
edited_post = request.POST.get('post')
try:
post.post = edited_post
post.save()
except:
return JsonResponse({"error": "Editing the post did not work."}, status=404)
elif request.method == "GET":
return JsonResponse(post.serialize())
elif request.method == "PUT":
data = json.loads(request.body)
edited_post = data["edit_area"]
post.post = data["edited_post"]
post.save()
else:
return JsonResponse({"error": "Need a GET request."}, status=404)
html
{% for post in page_obj.object_list %}
<div class = "individual_posts">
<h5 id="p_user" class = "post_user">{{ post.user }}</h5>
<h6 id = "post_itself_{{ post.id }}" class="post_itself">{{ post.post }}</h6>
{% if post.user == request.user %}
<button id="{{ post.id }}" class="edit_button" value="{{ post.id }}">Edit</button>
{% endif %}
<textarea class="textarea" id="edit_area_{{ post.id }}" cols="220" rows="5"></textarea>
<button class="edit_save" id="save_{{ post.id }}">Save</button>
</div>
{% endfor %}
models.py serialization
def serialize(self):
return{
"id": self.pk,
"post": str(self.post),
"user": self.user.pk,
}
The GET request works correctly, but I am receiving the previously stated error from the PUT request. I think that it is because of the way I am getting the value through edited_post = data["edit_area"]. How do I correctly get access to the text within the textarea to pass to JSON?
In your save_edit PUT function you are using
post: JSON.stringify({
post: edit_area.value
})
But in your view you are looking for
data = json.loads(request.body)
edited_post = data["edit_area"]
post.post = data["edited_post"]
The JSON you are sending looks like
{"post": "Here's my edits"}
So you probably want something like:
data = json.loads(request.body)
post.post = data["post"]
Also - fetch uses "body" not "post" so you might want to amend your put function to
body: JSON.stringify({
post: edit_area.value
})

How to stop Getting 405 error Method not allowed?

I am trying to make my django project to work but somehow I always come to get this error
Method Not Allowed (POST): /
I have tried using decorators like #csrf_exempt like in the django documentation as to not encounter csrf errors and yet I came to this error.Please tell me what's the problem with my code...
urls.py
from test.views import HomePageView,predict
urlpatterns = [
path('', HomePageView.as_view(), name="homepage"),
path('predict', predict, name="predict"),]
views.py
class HomePageView(Notif, TemplateView):
template_name = "homepage.html"
def predict(self, request, *args, **kwargs):
if request == 'POST':
text = self.request.get_json().get('message')
# check if text is valid
response = get_response(text)
message = {'answer': response}
return JsonResponse(message)
#method_decorator(csrf_exempt)
def dispatch(self, *args, **kwargs):
return super(HomePageView, self).dispatch(*args, **kwargs)
app.js
onSendButton(chatbox) {
var textField = chatbox.querySelector('input');
let text1 = textField.value
if (text1 === "") {
return;
}
let msg1 = { name: "User", message: text1 }
this.messages.push(msg1);
fetch( $SCRIPT_ROOT+'/predict',{
method: 'POST',
body: JSON.stringify({ message: text1 }),
mode: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-CSRFToken':csrftoken,
},
})
.then(r => r.json())
.then(r => {
let msg2 = { name: "Sam", message: r.answer };
this.messages.push(msg2);
this.updateChatText(chatbox)
textField.value = ''
}).catch((error) => {
console.error('Error:', error);
this.updateChatText(chatbox)
textField.value = ''
});
}
homepage.html
<div class="container">
{% csrf_token %}
<div class="chatbox">
<div class="chatbox__support">
<div class="chatbox__header">
<div class="chatbox__image--header">
<img src="https://img.icons8.com/color/48/000000/circled-user-female-skin-type-5--v1.png" alt="image">
</div>
<div class="chatbox__content--header">
<h4 class="chatbox__heading--header">Chat support</h4>
<p class="chatbox__description--header">Hi. My name is Sam. How can I help you?</p>
</div>
</div>
<div class="chatbox__messages">
<div></div>
</div>
<div class="chatbox__footer">
<input type="text" placeholder="Write a message...">
<button class="chatbox__send--footer send__button">Send</button>
</div>
</div>
<div class="chatbox__button">
<button class="btn-light"><img src="./images/chatbox-icon.svg" width="45px" height="45px"/></button>
</div>
</div>
</div>
<script type="text/javascript">
$SCRIPT_ROOT='{{ request.path }}'
</script>
Method Not Allowed (POST): / - means your function is not accepting post methos it accpets only get or other safe methods.
you're not changing any state of your database so you don't have to use post request you can use get intead of post
class HomePageView(Notif, TemplateView):
template_name = "homepage.html"
#staticmethod
def predict(self, request, *args, **kwargs):
if request == "POST":
text = self.request.get_json().get("message")
# check if text is valid
response = get_response(text)
message = {"answer": response}
return JsonResponse(message)
#method_decorator(csrf_exempt)
def dispatch(self, *args, **kwargs):
return super(HomePageView, self).dispatch(*args, **kwargs)
and change your urls like this
urlpatterns = [
path('predict', HomePageView.predict, name="predict"),
]
and in your javascript change method post to get
fetch($SCRIPT_ROOT + '/predict', {
method: 'GET',
body: JSON.stringify({
message: text1
}),
mode: 'same-origin',
})

How to blacklist words in a HTML form?

I was wondering how I am able to blacklist certain words from being entered in my form. Specifically, the username field. I'm not sure if I need access to the PHP/JS files, but I have limited access to those.
<div class="form-group">
<label for="username" class="control-label">{{ lang('signup.username') }}</label>
<input type="text" class="form-control" id="username" value="{{ data['login'] }}" name="RegistrationForm[login]" placeholder="Enter username">'===
</div>
{% if name_fields %}
<script>
function is_banned_name($data) {
$banned_names = array(
'socialwizards', 'socialwizard', 'bulkfollow', 'bulkfollows'
);
foreach($banned_names as $banned_name) {
$pattern = '/('.$banned_name.')/';
$match = preg_match($pattern,$data);
if($match) {
return true;
}
}
return false;
}
if(is_banned_name($_POST['username'])) {
<div class="alert alert-dismissible alert-danger {% if site['rtl'] %} rtl-alert {% endif %}">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ errorMessage }}
</div>
}
</script
(Added this to the end of my form)
You can do it with PHP using javascript is not secure as user can manipulated or disable JavaScript.
function is_banned_name($data) {
$banned_names = array(
'admin', 'test', 'user', 'fake', 'hack', 'error'
);
foreach($banned_names as $banned_name) {
$pattern = '/('.$banned_name.')/';
$match = preg_match($pattern,$data);
if($match) {
return true;
}
}
return false;
}
Then you can say
if(is_banned_name($_POST['username'])) {
// do something
}
You can do it with JavaScript but its not advisable. The code below is an example of how JavaScript code will do it. The code will return true if the name consist of the banned names.
function is_banned_name(str) {
var banned_names = ['admin', 'hacker', 'test', 'user', 'free']; banned_names.forEach(element => {
if(str.match(element)) { return true; }
});
} ```

Imagefield not saving in django cms plugin form working with AJAX

Hi I am new on django i was creating custom plugin in django cms it is the form other fields get saved easily, but the image field is not getting saved.
Here is my code let me know if I am missing something I am really stuck over here your help will be really appreciated.
models.py
class Blogs(models.Model):
name = models.CharField(u'Name',
blank=True,
default='',
help_text=u'Your name',
max_length=64,
)
description = models.TextField(u'Description',
blank=True,
default='',
help_text=u'Enter your Blog.',
)
comments = models.TextField(u'Short Description',
blank=True,
default='',
help_text=u'Short title of the Blog.',
)
images = models.ImageField(
upload_to='blog_image',
default='blog_image/black.png',
blank=True
)
# Meta, non-form data
contact_date = models.DateTimeField(
u'contact date',
blank=True,
default=timezone.now,
help_text=u'When this person completed the contact form.',
)
was_contacted = models.BooleanField(u'has been contacted?',
default=False,
help_text=u'Check this if someone has already reached out to this person.',
)
notes = models.TextField(u'contact notes',
blank=True,
default='',
help_text=u'Internal notes relating to contacting this person.',
)
referer = models.CharField(u'referring page',
blank=True,
default='',
help_text=u'This is the page the visitor was on before coming to the contact page.',
max_length=2048,
)
def send_notification_email(self):
subject.txt', {
'contact': self,
})
email_body = render_to_string('contacts/notification-body.txt', {
'contact': self,
})
try:
send_mail(
email_subject,
email_body,
settings.SERVER_EMAIL,
settings.MANAGERS,
fail_silently=(not settings.DEBUG)
)
except Exception:
if (settings.DEBUG):
raise
def save(self, *args, **kwargs):
if not self.pk:
try:
self.send_notification_email()
except:
pass
super(Blogs, self).save(*args, **kwargs)
def __unicode__(self):
return '%s (%s)' % (self.name, str(self.contact_date),)
class BlogPluginModel(CMSPlugin):
title = models.CharField(u'title',
blank=True,
help_text=u'Optional. Title of the widget.',
max_length=64,
)
def __unicode__(self):
return self.title
cms_plugins.py
class BlogPlugin(CMSPluginBase):
model = BlogPluginModel
name = _("Blog Form")
render_template = "blogs/_blogs_widget.html"
def render(self, context, instance, placeholder):
try:
path = context['request'].path
except:
path = ''
form = BlogAjaxForm(initial={'referer': path})
context.update({
"title": instance.title,
"form": form,
"form_action": reverse("blogging_form"),
})
return context
plugin_pool.register_plugin(BlogPlugin)
forms.py
class BlogBaseForm(ModelForm):
class Meta:
abstract = True
required_css_class = 'required'
verify_email = forms.EmailField(
label=u'Verify email',
help_text=u'Please retype your email address here.',
max_length=255,
required=True,
)
required_fields = []
class blogForm(BlogBaseForm):
images=forms.ImageField(help_text="Upload image: ", required=False)
class Meta:
model = Blogs
fields = [
'name','images', 'description', 'comments', 'referer',
]
widgets = {
'referer': forms.HiddenInput(),
}
required_fields = ['name', 'email', 'verify_email', ]
class BlogAjaxForm(BlogBaseForm):
images=forms.ImageField(help_text="Upload image: ", required=False)
class Meta:
model = Blogs
fields = ['name','images', 'description','comments','referer', ]
widgets = { 'referer': forms.HiddenInput(),}
view.py
class BlogFormView(FormView):
form_class = BlogBaseForm
template_name = 'contacts/contact_form.html'
def get_initial(self):
"""
still preserve this original HTTP_REFERER.
"""
initial = super(BlogFormView, self).get_initial()
initial['referer'] = self.request.META.get('HTTP_REFERER', ''),
return initial
def get_success_url(self):
page = get_object_or_404(
Page,
reverse_id='blog_form_submission',
publisher_is_draft=False
)
return page.get_absolute_url()
def form_valid(self, form):
self.object = form.save()
return super(BlogFormView, self).form_valid(form)
class AjaxableResponseMixin(object):
def __init__(self):
self.request = None
self.object = Blogs
def render_to_json_response(self, context, **response_kwargs):
data = json.dumps(context)
response_kwargs['content_type'] = 'application/json'
return HttpResponse(data, **response_kwargs)
def form_invalid(self, form):
response = super(AjaxableResponseMixin, self).form_invalid(form)
if self.request.is_ajax():
return self.render_to_json_response(form.errors) # , status=400)
else:
return response
def form_valid(self, form):
response = super(AjaxableResponseMixin, self).form_valid(form)
if self.request.is_ajax():
data = {
'pk': self.object.pk,
}
return self.render_to_json_response(data)
else:
return response
class BlogFormAjaxView(AjaxableResponseMixin, FormView):
form_class = BlogAjaxForm
http_method_names = [u'post']
template_name = 'contacts/_contact_widget.html'
form = BlogAjaxForm(http_method_names)
def get_success_url(self):
page = get_object_or_404(
Page,
reverse_id='blog_form_submission',
publisher_is_draft=False
)
return page.get_absolute_url()
def form_valid(self, form):
self.object = form.save(commit=True)
return super(BlogFormAjaxView, self).form_valid(form)
urls.py
urlpatterns = [
url(
r'^blogging_form/$',
BlogFormAjaxView.as_view(),
name='blogging_form'
),
url(r'^$', BlogFormView.as_view(), name='Blog_Form'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
_blog_widget.html
{% load i18n static sekizai_tags %}
{% addtoblock "js" %}<script src="{% static 'blogs/scripts/Blogs.js' %}"></script>
{% endaddtoblock %}
{% addtoblock "css" %}
<link rel="stylesheet" href="{% static 'contacts/css/styles.css' %}">
{% endaddtoblock %}
{% addtoblock "js" %}
<script src="{% static 'http://malsup.github.com/jquery.form.js' %}"></script>
{% endaddtoblock %}
<div class="Blogs-plugin plugin">
<div class="inner">
<div class="Blog-form">
{% if title %}<h3>{{ title }}</h3>{% endif %}
<form method="post" action="{{ form_action }}" enctype="multipart/form-data">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{% if hidden.name == 'referer' %}
<input type="hidden" name="{{ hidden.name }}" value="{{ hidden.value }}">
{% endif %}
{% endfor %}
{% for visible in form.visible_fields %}
<div class="field-wrapper field-row half {{ visible.css_classes }}">
{{ visible.label_tag }}
<div class="help-text">{{ visible.help_text }}</div>
<div class="error empty"></div>
{{ visible }}
</div>
{% endfor %}
<input type="submit" value="Submit">
</form>
<div class="legend"><span class="required">*</span> Required field
</div>
<div class="success" style="display:none">Thank you, a member of our
team will contact you shortly, if appropriate.
</div>
<div class="errors" style="display:none"><span class="form-errors">
</span>
</div>
</div>
</div>
</div>
Blogs.js
(function($){
"use strict";
$(function(){
$('.Blogs-plugin input[type=submit]').on('click',
function(evt){
var $form = $(this).parents('form').eq(0);
function handleResponse(data){
if (data.pk) { // Success!
$form.siblings('.success').html(data.success).show(100);
$form.add('.legend').hide(100);
}
else { // Validation Issues...
//
// data will a dictionary like so:
// { 'field_name': ['error1', 'error2'], ... }
//
$form.find('.error').empty();
$.each(data, function(key, value){
var $field = $form.find('input[name='+key+']').first();
$field.parents('.fieldwrapper').find('.error').html(value.join(' '));
});
if (data.__all__) {
$form.siblings('.errors').find('.form-
errors').html(data.__all__.join(' '));
}
else {
$form.siblings('.errors').find('.form-errors').empty();
}
$form.siblings('.errors').show(100);
}
}
evt.preventDefault();
$form.siblings('.errors, .success').hide(100);
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: $form.serialize(),
}).always(handleResponse);
});
});
}(window.jQuery));

how to upload user avatar in django through angular?

I want to give the registration is possible the user to download your picture.
I have custom user model:
class UserManager(BaseUserManager):
def create_user(self,username, email, password):
if not email:
raise ValueError('Email непременно должен быть указан')
user = self.model(
username = username,
email=UserManager.normalize_email(email),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username,email, password):
user = self.create_user(username, email, password)
user.is_superuser = True
user.is_admin = True
user.save(using=self._db)
return user
class ExtUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
'Электронная почта',
max_length=255,
unique=True,
blank=True
)
avatar = models.ImageField(
'Аватар',
blank=True,
null=True,
upload_to="user/avatar"
)
firstname = models.CharField(
'Фамилия',
max_length=40,
null=True,
blank=True
)
username = models.CharField(
_('username'),
max_length=30,
unique=True,
help_text=_('Required. 30 characters or fewer. Letters, digits and #/./+/-/_ only.'),
validators=[
validators.RegexValidator(
r'^[\w.#+-]+$',
_('Enter a valid username. This value may contain only '
'letters, numbers ' 'and #/./+/-/_ characters.')
),
],
error_messages={
'unique': _("A user with that username already exists."),
},
)
lastname = models.CharField(
'Имя',
max_length=40,
null=True,
blank=True
)
middlename = models.CharField(
'Отчество',
max_length=40,
null=True,
blank=True
)
date_of_birth = models.DateField(
'Дата рождения',
null=True,
blank=True
)
register_date = models.DateField(
'Дата регистрации',
auto_now_add=True
)
is_active = models.BooleanField(
'Активен',
default=True
)
is_admin = models.BooleanField(
'Суперпользователь',
default=False
)
balance = models.DecimalField(
'Деньги пользователя',
default=0.00,
decimal_places = 2,
max_digits = 200
)
subscriptions = models.ManyToManyField(Season, blank=True)
#
def get_full_name(self):
return self.email
#property
def is_staff(self):
return self.is_admin
def get_short_name(self):
return self.email
def __str__(self):
return self.username
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
objects = UserManager()
class Meta:
verbose_name = 'Пользователь'
verbose_name_plural = 'Пользователи'
register API:
#api_view(['POST'])
def register(request):
VALID_USER_FIELDS = [f.name for f in get_user_model()._meta.fields]
DEFAULTS = {
# you can define any defaults that you would like for the user, here
}
serialized = UserSerializer(data=request.data)
if serialized.is_valid():
user_data = {field: data for (field, data) in request.data.items() if field in VALID_USER_FIELDS}
user_data.update(DEFAULTS)
user = get_user_model().objects.create_user(
**user_data
)
return Response(UserSerializer(instance=user).data, status=status.HTTP_201_CREATED)
else:
return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
register function in JS controller:
$scope.register = function(email, password, username, avatar) {
return $http.post('/api/v1/auth/register/', {
username: username,
password: password,
email: email,
'avatar':avatar
}).success(function(data, status) {
return $scope.login(username, password)
window.location = '/'
})
}
HTML-form:
<form role="form" ng-submit="register(email,password,username, avatar)">
<div class="form-group">
<label for="register__email">Email</label>
<input type="email" class="form-control" id="register__email" ng-model="email" placeholder="email#email.com" />
</div>
<div class="form-group">
<label for="register__username">Username</label>
<input type="text" class="form-control" id="register__username" ng-model="username" placeholder="Bon Jovi" />
</div>
<div class="form-group">
<label for="register__username">Avatar</label>
<input name="pic" type="file" id="pic" accept="image/*">
</div>
<div class="form-group">
<label for="register__password">Password</label>
<input type="password" class="form-control" id="register__password" ng-model="password" placeholder='12345' />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
What do I need to do in terms of api , and javascript, to make it work ?

Categories