AJAX not Making POST request in FLASK - javascript

Have poured over SO and every blog and/or video I can find. I'm new to JS/AJAX/JQUERY, and have recently tried to incorporate these guys into my Flask apps, much to my current dismay. Trying to simply submit the form data to my MySQL DB via an AJAX call, without refreshing the page. This is far as I've gotten. Don't even see the post request being made in the inspector. Maybe it's not hitting the route? Here's my code:
Form HTML
<form name="race_form" id="race_form">
<input type="text" id="characterID" value="{{ character.id }}" />
<input type="text" id="raceID" value="{{ attribute.id }}" />
<button type="submit" id="toggleoption-{{ attribute.attribute_name }}"
class="btn btn-default char_gen_options_btn" style="margin: 10px 0px 0px 10px;
background:url(/static/img/blacksmith.jpg) right center no-repeat; background-size:contain;
background-color:#B5B6AF;font-weight:900;">Select {{ attribute.attribute_name }}</button>
</form>
AJAX
$(document).ready(function() {
$('#race_form').submit(function(event) {
event.preventDefault();
var character_id = $('#characterID').val();
var attribute_id = $('#raceID').val();
$.ajax({
url: "{{ url_for('auth.register_race') }}",
type: 'POST',
data: { character_id: character_id, attribute_id: attribute_id }
});
});
});
Flask View (committing to many to many table)
#auth.route('/register_race', methods=['POST'])
#login_required
def register_race():
character = Character.query.filter_by(id=request.form['characterID']).first()
character.character_attributes.character_id = request.form['characterID']
character.character_attributes.attribute_id = request.form['raceID']
db.session.commit()
return jsonify({'result': 'success'})
And the tables from models.py that the view is referencing:
class Character(db.Model):
"""
Create a Player Character table - all characters assigned to user
"""
__tablename__ = 'characters'
id = db.Column(db.Integer, primary_key=True, unique=True)
character_name = db.Column(db.String(60), index=True, unique=True)
experience_points = db.Column(db.Integer) # Refers to proprietary character build points
character_lives = db.Column(db.Integer, default=0)
character_img = db.Column(db.String(300)) # Path to character img on server
create_date = db.Column(db.DateTime, default=func.now())
last_update = db.Column(db.DateTime, onupdate=func.now())
# Keys
users = db.relationship('User', secondary='user_character')
attribute = db.relationship('Attribute', secondary='character_attributes')
items = db.relationship('Items', secondary='inventory')
files = db.relationship('File', secondary="character_files")
def __repr__(self):
return '<Character Name: {}>'.format(self.character_name)
class CharacterAttributes(db.Model):
"""
Many to many table for characters and assigned attributes
"""
__tablename__ = 'character_attributes'
id = db.Column(db.Integer, primary_key=True, unique=True)
create_date = db.Column(db.DateTime, default=func.now())
last_update = db.Column(db.DateTime, onupdate=func.now())
amount_purchased = db.Column(db.Integer)
# Keys
character_id = db.Column(db.Integer, db.ForeignKey('characters.id'))
attribute_id = db.Column(db.Integer, db.ForeignKey('attributes.id'))
character = db.relationship('Character', backref=backref('character_attributes', cascade='all, delete-orphan'))
attribute = db.relationship('Attribute', backref=backref('character_attributes', cascade='all, delete-orphan'))

Related

I have a problem in submitting comments to server using json and fetch in django

I am working on a bookstore project using django and javascript. I want to allow user to add comments on each book and send the comment without reloading the page using JSON
html:
<h3 id="authorname">{{book.authorname}}</h3>
<h1 id="bookname"> {{book.name}}</h1>
<p id="slogan">-{{book.slogan}}-</p>
<h2 id="price">Price:- <span>${{book.price}}</span></h2>
<form id="addcomment">
{% csrf_token %}
<input hidden name='thecommentuser' value="{{ request.user.id }}" id="commentsubmitter">
<input hidden name='thecommentbook' value="{{ book.id }}" id="commentbook">
<textarea name='thecomment'id="comment"></textarea>
<input type="submit">
</form>
script:
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#addcomment').onsubmit = function() {
fetch('/comments', {
method: 'POST',
body: JSON.stringify({
thecomment: document.querySelector('#comment').value,
thecommentuser: document.querySelector('#commentsubmitter').value,
thecommentbook: document.querySelector('#commentbook').value,
})})}});
models.py:
class books(models.Model):
bookuser= models.ForeignKey('User', on_delete=models.CASCADE, default= None, blank=True)
name = models.CharField(max_length=80)
slogan = models.CharField(max_length=200, null=True,
price = models.IntegerField()
authorname= models.CharField(max_length=30)
class comments(models.Model):
comment = models.CharField(max_length= 100)
commentuser = models.ForeignKey('User', on_delete=models.CASCADE, default=None)
commentbook = models.ForeignKey('books', on_delete=models.CASCADE, default=None)
def serialize(self):
return {
'thecomment': self.comment,
'thecommentuser': self.commentuser,
'thecommentbook': self.commentbook
}
urls.py:
urlpatterns = [
path('book/<int:id>', views.book, name='book'),
path('comments', views.addcomments, name='comments')
]
views.py:
from django.views.decorators.csrf import csrf_exempt
from .models import *
from django.contrib.auth.decorators import login_required
import json
def book(request, id):
submitedbook = books.objects.get(id=id)
bkchapters = chapters.objects.filter(chapterbook=submitedbook)
bkrewards = rewards.objects.filter(rewardbook = submitedbook)
return render(request, 'network/book.html', {'book':submitedbook, 'chapters':bkchapters, 'rewards':bkrewards})
#csrf_exempt
#login_required
def addcomments(request):
if request.method == 'POST':
print('posted')
data= json.loads(request.body)
comment = data.get('thecomment', '')
commentuser = data.get('thecommentuser')
commentbook = data.get('thecommentbook', '')
cuser = User.objects.get(id = commentuser)
cbook = books.objects.get(id = commentbook)
thecommentt = comments(
thecomment=comment,
thecommentuser=cuser,
thecommentbook=cbook
)
thecommentt.save()
when I open the comments in the admin page I don't find any submitted data and the page reload upon submitting a comment. the order of print('posted') in views.py isn't displayed to me upon adding a comment and that means that the request isn't sent but I don't know why
this appears to me in the terminal window upon adding the comment:
[30/Oct/2022 01:47:19] "GET /book/1?csrfmiddlewaretoken=9QgGiDOUnVxMlxZQ6UkSmiO4auq5BLojV6iWW55qE9LER929Qj7WB8LVtkBfpnJ4&thecommentuser=1&thecommentbook=1&thecomment=Book HTTP/1.1" 200 14927
I tried to delete if request.method == 'POST': in views and to print in views but nothing changed. Also I tried to console.log('submitted') on submitting the comment but nothing appeared
new update:
I find that the error comes from the browser itself as I find that data is sent upon submitting from another browser so although the two browsers are updated. so how could I solve this?

Django ImageField Form upload works in admin but not in actual user form

I am trying to upload an image within a form that has an animal type, description, and the image file. This should save to image in an "images" file within my project and this works fine when adding a model object from the admin page but when trying to use the actual form on my site, only the animal type and description gets saved to the admin page.
model code:
class Post(models.Model):
BISON = 'Bison'
WOLF = 'Wolf'
ELK = 'Elk'
BLACKBEAR = 'Black Bear'
GRIZZLY = 'Grizzly Bear'
MOOSE = 'Moose'
MOUNTAINLION = 'Mountain Lion'
COYOTE = 'Coyote'
PRONGHORN = 'Pronghorn'
BIGHORNSHEEP = 'Bighorn Sheep'
BALDEAGLE = 'Bald Eagle'
BOBCAT = 'Bobcat'
REDFOX = 'Red Fox'
TRUMPETERSWAN = 'Trumpeter Swan'
YELLOWBELLIEDMARMOT = 'Yellow-bellied Marmot'
RIVEROTTER = 'River Otter'
LYNX = 'Lynx'
SHREW = 'Shrew'
PIKA = 'Pika'
SQUIRREL = 'Squirrel'
MULEDEER = 'Mule Deer'
SANDHILLCRANE = 'Sandhill Crane'
FLYINGSQUIRREL = 'Flying Squirrel'
UINTAGROUNDSQUIRREL = 'Uinta Ground Squirrel'
MONTANEVOLE = 'Montane Vole'
EASTERNMEADOWVOLE = 'Eastern Meadow Vole'
BUSHYTAILEDWOODRAT = 'Bushy-tailed Woodrat'
CHIPMUNK = 'Chipmunk'
UINTACHIPMUNK = 'Uinta Chipmunk'
WHITETAILEDJACKRABBIT = 'White-tailed Jackrabbit'
BEAVER = 'Beaver'
AMERICANMARTEN = 'American Marten'
MOUNTAINCHICKADEE = 'Mountain Chickadee'
BOREALCHORUSFROG = 'Boreal Chorus Frog'
CUTTHROATTROUT = 'Cutthroat Trout'
GREATHORNEDOWL = 'Great Horned Owl'
SNOWSHOEHARE = 'Snowshoe Hare'
ROCKYMOUNTAINELK = 'Rocky Mountain Elk'
NORTHWESTERNWOLF = 'Northwestern Wolf'
BLACKFOOTEDFERRET = 'Black-footed Ferret'
WOLVERINE = 'Wolverine'
ANIMALS = [
(BISON, ('Bison')),
(WOLF, ('Wolf')),
(ELK, ('Elk')),
(BLACKBEAR, ('Black Bear')),
(GRIZZLY, ('Grizzly Bear')),
(MOOSE, ('Moose')),
(MOUNTAINLION, ('Mountain Lion')),
(COYOTE, ('Coyote')),
(PRONGHORN, ('Pronghorn')),
(BIGHORNSHEEP, ('Bighorn Sheep')),
(BALDEAGLE, ('Bald Eagle')),
(BOBCAT, ('Bobcat')),
(REDFOX, ('Red Fox')),
(TRUMPETERSWAN, ('Trumpeter Swan')),
(YELLOWBELLIEDMARMOT, ('Yellow-bellied Marmot')),
(RIVEROTTER, ('River Otter')),
(LYNX, ('Lynx')),
(SHREW, ('Shrew')),
(PIKA, ('Pika')),
(SQUIRREL, ('Squirrel')),
(MULEDEER, ('Mule Deer')),
(SANDHILLCRANE, ('Sandhill Crane')),
(FLYINGSQUIRREL, ('Flying Squirrel')),
(UINTAGROUNDSQUIRREL, ('Uinta Ground Squirrel')),
(MONTANEVOLE, ('Montane Vole')),
(EASTERNMEADOWVOLE, ('Eastern Meadow Vole')),
(BUSHYTAILEDWOODRAT, ('Bushy-tailed Woodrat')),
(CHIPMUNK, ('Chipmunk')),
(UINTACHIPMUNK, ('Uinta Chipmunk')),
(WHITETAILEDJACKRABBIT, ('White-tailed Jackrabbit')),
(BEAVER, ('Beaver')),
(AMERICANMARTEN, ('American Marten')),
(MOUNTAINCHICKADEE, ('Mountain Chickadee')),
(BOREALCHORUSFROG, ('Boreal Chorus Frog')),
(CUTTHROATTROUT, ('Cutthroat Trout')),
(GREATHORNEDOWL, ('Great Horned Owl')),
(SNOWSHOEHARE, ('Snowshoe Hare')),
(ROCKYMOUNTAINELK, ('Rocky Mountain Elk')),
(NORTHWESTERNWOLF, ('Northwestern Wolf')),
(BLACKFOOTEDFERRET, ('Black-footed Ferret')),
(WOLVERINE, ('Wolverine'))
]
animal = models.CharField(max_length=32, choices=ANIMALS, default=BISON)
image = models.ImageField(upload_to='images', null=True, blank=True)
description = models.TextField(null=True, blank=True)
def __str__(self):
return self.animal
form code
class PostForm(ModelForm):
class Meta:
model = Post
fields = '__all__'
view for where the form is
def homePage(request):
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponse('')
else:
form = PostForm()
context = {'form': form}
return render(request, 'home.html', context)
home template for displaying the form
const postpopup = new mapboxgl.Popup({ offset: [0, -15] })
.setLngLat([lt, lg])
.setHTML(
`<div style="margin-left: 10px;">
<h2 style="font-size: 30">Post Forum :) </h2>
<div>
<form id="post-form" enctype="multipart/form-data">
{% csrf_token %}
{{form}}
<p></p>
<img src="images/{{ form.image.name }}" style="width: 190px"/>
<p></p>
<input type="submit"/>
</form>
<p></p>
</div>
</div>`
)
I have gone through the Django documentation for file uploads here but I cannot seem to find the issue. I imagine it must be something to do with the code in my homePage view but I cannot seem to spot the issue. It doesn't make sense to me why the animal type and description gets sent to the admin page but the image file is always blank when submitting a post how I intend the user to.

Error while sending JavaScript generated image to Django ModelForm

I’m trying to use https://github.com/szimek/signature_pad to attach a signature to a form and send it to the server. I’ve been able to successfully upload images with a standard ImageField, and have also used szimek/signature_pad to download the signature. But when I try to get the signature to the server, I get "(Hidden field signature) No file was submitted. Check the encoding type on the form." So I think I’m at least successfully sending an image to the field, but am not sure how to encode it.
HTML
<form id="form" action="{% url ‘my_app:testFormPage' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<div id="signature-pad">
<canvas></canvas><br>
</div>
 <input type="hidden" name="signature" value=“signatureImage”>
<button type="submit" data-action="formSig">Submit</button>
</form>

Python
# Models.py
class testModel(models.Model):
name = models.CharField(max_length=50)
date = models.DateTimeField(default=timezone.now)
signature = models.ImageField (null=True, max_length=3000)
# Forms.py
class testForm(forms.ModelForm):
class Meta:
model = testModel
fields = ‘__all__’
widgets = { 'signature': forms.HiddenInput(),}
# Views.py
def testFormPage(request):
if request.method == 'POST':
form = testForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/thanks/')
else:
form = testForm()
context = {'form': form}
return render(request, 'client_visits/testFormPage.html', context)
Javascript

The full javascript app can be found at https://github.com/szimek/signature_pad/tree/master/docs/js. Here’s just what I added
var formSig = wrapper.querySelector("[data-action=formSig]");
formSig.addEventListener("submit", function (event) {
var signatureImage = signaturePad.toDataURL();
});

How can i connect my django like button to ajax to refresh automatically

I have a django project that im working on. Users will be able to like and dislike post.
models.py
class Tweet(models.Model):
tweet_user = models.ForeignKey(User, on_delete=models.CASCADE)
tweet_message = models.TextField()
tweet_date = models.DateTimeField(auto_now_add=True)
tweet_like_counter = models.IntegerField(default=0)
tweet_picture = models.FileField(null=True,blank=True)
def __str__(self):
return self.tweet_message
class Like(models.Model):
user = models.ManyToManyField(User)
tweet = models.ForeignKey(Tweet, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.tweet.tweet_message
class Disike(models.Model):
user = models.ManyToManyField(User)
tweet = models.ForeignKey(Tweet, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.tweet.tweet_message
views.py
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
#login_required
def like(request, pk):
currentTweet = get_object_or_404(Tweet,pk=pk)
username = User.objects.get(pk=request.user.id)
like_queryset = Like.objects.filter(tweet=currentTweet, user=username)
dislike_queryset = Disike.objects.filter(tweet=currentTweet, user=username)
if like_queryset.exists():
Like.objects.filter(tweet=currentTweet, user=username).delete()
dislikeobject = Disike.objects.filter(tweet=currentTweet).count()
likeobject = Like.objects.filter(tweet=currentTweet).count()
currentTweet.tweet_like_counter = likeobject - dislikeobject
currentTweet.save()
if dislike_queryset.exists():
Disike.objects.filter(tweet=currentTweet, user=username).delete()
dislikeobject = Disike.objects.filter(tweet=currentTweet).count()
likeobject = Like.objects.filter(tweet=currentTweet).count()
currentTweet.tweet_like_counter = likeobject - dislikeobject
currentTweet.save()
like = Like.objects.create(tweet=currentTweet)
like.user.add(username)
dislikeobject = Disike.objects.filter(tweet=currentTweet).count()
likeobject = Like.objects.filter(tweet=currentTweet).count()
currentTweet.tweet_like_counter = likeobject - dislikeobject
currentTweet.save()
return JsonResponse({
'like_counter': currentTweet.tweet_like_counter
})
#csrf_exempt
#login_required
def dislike(request, pk):
currentTweet = get_object_or_404(Tweet, pk=pk)
username = User.objects.get(pk=request.user.id)
like_queryset = Like.objects.filter(tweet=currentTweet, user=username)
dislike_queryset = Disike.objects.filter(tweet=currentTweet, user=username)
if dislike_queryset.exists():
Disike.objects.filter(tweet=currentTweet, user=username).delete()
dislikeobject = Disike.objects.filter(tweet=currentTweet).count()
likeobject = Like.objects.filter(tweet=currentTweet).count()
currentTweet.tweet_like_counter = likeobject - dislikeobject
currentTweet.save()
if like_queryset.exists():
Like.objects.filter(tweet=currentTweet, user=username).delete()
dislikeobject = Disike.objects.filter(tweet=currentTweet).count()
likeobject = Like.objects.filter(tweet=currentTweet).count()
currentTweet.tweet_like_counter = likeobject - dislikeobject
currentTweet.save()
dislike = Disike.objects.create(tweet=currentTweet)
dislike.user.add(username)
dislikeobject = Disike.objects.filter(tweet=currentTweet).count()
likeobject = Like.objects.filter(tweet=currentTweet).count()
currentTweet.tweet_like_counter = likeobject - dislikeobject
currentTweet.save()
return JsonResponse({
'like_counter': currentTweet.tweet_like_counter
})
template
<p class='id{{ post.tweet_user }}' name="tweetlikes" class="card-text" style="background-color: lightgray;"><strong>{{ post.tweet_like_counter }} likes </strong></p>
<form id="like{{ post.tweet_user }}" method="POST" name="likeform" action="{% url 'like' pk=post.pk %}" style="float:left;">
{% csrf_token %}
<button type="submit" class="like-form" name="like" class="btn btn-primary" >Like</button>
</form>
<script>
$('#like{{ post.tweet_user }}').on('submit', function(event){
event.preventDefault();
var oldVal = parseInt($(".id{{ post.tweet_user }}").text())
var url = $('#like{{ post.tweet_user }}').attr('action');
$.ajax({
type: 'POST',
url:url,
data:{
'like_counter':oldVal
},
dataType: 'json',
success:function(data){
$(".id{{ post.tweet_user }}").html(data.like_counter + " " + "likes");
}
})
})
</script>
<form id="dislike{{ post.tweet_user }}" name="dislikeform" method="POST" action="{% url 'dislike' pk=post.pk %}" style="float:right;" >
{% csrf_token %}
<button type="submit" class="btn btn-primary">Dislike</button>
</form>
<script>
$('#dislike{{ post.tweet_user }}').on('submit', function(e){
e.preventDefault();
var oldVal = parseInt($(".id{{ post.tweet_user }}").text())
var url = $('#dislike{{ post.tweet_user }}').attr('action');
$.ajax({
type: 'POST',
url:url,
data:{
'like_counter':oldVal
},
dataType: 'json',
success:function(data){
$(".id{{ post.tweet_user }}").html(data.like_counter + " " + "likes");
}
})
})
</script>
</div>
The problem lies in my ajax. The functionality of my website works great. Its just the ajax. When A user clicks the like button on the first post, it allows the user to only like the button one time Like it should. When another user makes a post (which makes two post on the page), the button post like buttons dont work anymore, and it changes the like number tag, and also it makes the data comes out diffent. Help please?
Why are users linked to likes/dislikes with ManyToManyField? Can a single "like" be shared among users? ForeignKey would work fine here.
Also, since your code state that a user cannot have Like and Dislike on the same "tweet" both at the same time, I suggest you to collapse these two models into one with Boolean or numeric field meaning +1 or -1.
Instead of turturing database with that many queries you could use [update_or_create][1] and F() or Subquery() expression, or Count/Sum aggregation. The latter will also fix race conditions issue in update queries.
def like(request, pk):
Like.objects.update_or_create(tweet_id=pk, user=request.user,
defaults={"value": <+1/-1>})
Tweet.objects.filter(pk=pk, ).annotate(likes_count=Sum(tweet__like__value), ).\
update(tweet_like_counter=F(likes_count), )
like_counter = Tweet.objects.values_list('tweet_like_counter', flat=True).get(pk=pk,)
return JsonResponse({
'like_counter': like_counter
})
The first statement will create or update if it exists a Like object with user_id and tweet_id. Note, user value already exists in request object so you don't need to make additional queries to achieve it.
Also you don't need to instantiate a Tweet object with given tweet_id (equal to pk arg) - pk/tweer_id is enough here.
The next statement will update tweet_like_counter based on aggregation of all existent likes/dislikes. And this update performs a single SQL command instead of 4 commands in your code: get Tweet object, get two counters, save Tweet object with new counter.
Statement three will retrieve current like_counter. Note, it selects a single column instead of instantiating full Tweet object.

Why I get empty form? How to automatically create Iniline models?

There are 2 forms on one page.
There are 2 models: 1. Product. 2. SpeciallyPrice. SpeciallyPrice is linked via FK to Product. At the same time, SpeciallyPrice is Inline model in Product.
The fields of the SpecialPriceForm are automatically created using JS. That is, them may be the n-th number. It is necessary to create a record for each created field. In principle, I guess how to do it - use the cycle to drive the values obtained. But the problem is that for some reason None comes from the form. Please help me.
class ProductsCreate(CreateView):
model = Product
form_class = ProductCreateForm
http_method_names = ['get', 'post']
def get_initial(self):
initial = super(ProductsCreate, self).get_initial()
initial['request'] = self.request
return initial
def get_context_data(self, *args, **kwargs):
ctx=super(ProductsCreate, self).get_context_data(*args, **kwargs)
ctx['special_form'] = SpeciallyPriceForm()
return ctx
def get(self, request, *args, **kwargs):
self.object = None
if kwargs.get('slug'):
category = Category.objects.filter(slug=kwargs.get('slug')).first()
self.initial.update({'category': category})
return self.render_to_response(self.get_context_data())
def post(self, request, *args, **kwargs):
self.object = None
form = ProductCreateForm(request.POST, request.FILES, initial={'request': request})
special_form = SpeciallyPriceForm(request.POST)
print(special_form) #Template of form, without values.
if form.is_valid() and special_form.is_valid():
return self.form_valid(form, special_form)
else:
return self.form_invalid(form, special_form)
def form_valid(self, form, special_form):
product = form.save(commit=False)
product.user = self.request.user
product.save()
special = special_form.save(commit=False)
#Here I think, depending on the number of list items, to cycle through it and create the corresponding number of `special` records associated with this` product`. Is the logic correct?
special.product = product
special.save()
for spec_price in special_form.cleaned_data.get('adittional_specially_price'):
print(spec_price)
special.adittional_specially_price = spec_price
for spec_numb in special_form.cleaned_data.get('adittional_specially_number'):
print(spec_numb)
special.adittional_specially_number = spec_numb
forms
class SpeciallyPriceForm(forms.ModelForm):
class Meta:
model = SpeciallyPrice
fields = ['adittional_specially_price', 'adittional_specially_number']
def clean(self):
cleaned_data = super(SpeciallyPriceForm, self).clean()
cd_adittional_specially_price = cleaned_data.get('adittional_specially_price')
print(cd_adittional_specially_price) #None
cd_adittional_specially_number = cleaned_data.get('adittional_specially_number')
print(cd_adittional_specially_number) #None
template + js
<html><body>
Special price from {{ special_form.adittional_specially_price }} kg {{ special_form.adittional_specially_number }} usd
<script>
(function(){
var copy = document.querySelector('.field.inline.specially').cloneNode(true);
document.querySelector('html').addEventListener('input', function(e){
if(e.target.classList.contains('event') && e.target.tagName == 'INPUT'){
var error = 0;
for(var evt of document.querySelectorAll('.field.inline.specially input.event')){
evt.value = evt.value.replace(/[^\d]/,'');
if(!evt.value || +evt.value < 1) error++;
}
if(!error){
var last = document.querySelectorAll('.field.inline.specially');
last[last.length-1].insertAdjacentHTML('afterEnd', copy.outerHTML);
}
}
});
})();
</script>
</body></html>
This form i get in views, when print form for checking
<label for="specially" class="subhead">Special price from</label>
<span class="id_specially_price"><input type="text" name="adittional_specially_price" style="width: 165px" class="event" id="id_adittional_specially_price"></span>
<span>kg</span>
<span class="id_specially_number"><input type="text" name="adittional_specially_number" style="width: 100px" class="event" id="id_adittional_specially_number"></span>
<span>usd</span>
I looked in the views - the form is rendered there, but only with one field, and not with everything. And the form is empty .. How to solve this issue? Maybe Ajax should be connected and it somehow process the request? Or is there a more Django's option?
Answering this bit of comments: "And really come the last two empty created with JS fields. How to make all fields come, tell me, please?"
To save an inline formset in a CBV:
def form_valid(self, form):
context = self.get_context_data()
inline_form = context['inline_form']
if inline_form.is_valid():
self.object = form.save()
inline_form.instance = self.object
inline_form.save()
Clearly you'll have to use the right name for inline_form within the context.

Categories

Resources