I try to update database using ajax query
I get row table id on click to send to view for updating data
but as my ajax is called twice (why?), second call reverse first call
<table>
<tbody>
{% for dcf in datacorrections %}
<tr>
<td data-toggle="tooltip" data-placement="top" title="">{{ dcf.ide }}</td>
<td data-toggle="tooltip" data-placement="top" title="" id="{{ dcf.ide }}">{{ dcf.deativated }}</td>
</tr>
{% endfor %}
</tbody>
</table>
$('body').on('click','td', function() {
var _id = $(this).attr('id');
$.ajax({
type: 'POST',
url: "{% url 'monitoring:deactivate_dcf' %}",
data: { "id" : _id },
dataType: 'html',
success: function (response) {
obj = JSON.parse(response);
},
});
});
#login_required
#csrf_exempt
def deactivate_dcf(request):
if request.is_ajax() and request.method == "POST":
datacorrection_id = request.POST.get("id")
if DataCorrection.objects.filter(ide = datacorrection_id).exists():
if DataCorrection.objects.get(ide = datacorrection_id).deativated == False:
DataCorrection.objects.filter(ide = datacorrection_id).update(deativated=True)
else:
DataCorrection.objects.filter(ide = datacorrection_id).update(deativated=False)
return JsonResponse({"response": "success",}, status=200)
else:
return JsonResponse({"response": "failed","exist":"datacorrection not exist"}, status=404)
return JsonResponse({"response":"not_ajax"}, status=200)
Add class "clickable-td" to the clickable td:
<td data-toggle="tooltip" class="clickable-td" data-placement="top" title="" id="{{ dcf.ide }}">{{ dcf.deativated }}</td>
add this instead, it will trigger the event on this td and it should stop the propagation.
$('.clickable-td').click(function(e) {
e.preventDefault();
e.stopImmediatePropagation();
var _id = $(this).attr('id');
console.log(_id);
$.ajax({
method: 'POST',
url: "{% url 'monitoring:deactivate_dcf' %}",
data: { "id" : _id },
dataType: 'json',
success: function (response) {
console.log("we went throught !");
console.log(response);
},
})
});
If you go in the console inspector and find the console log of the ID then it should be fine.
Related
I have a problem,Django my ajax post is not working. when i look at the console quantity is not undefined. But my request.post is not working.
<form method="POST">
{% csrf_token %}
<ul>
<li>
<div class="form-group quantity-box">
<label class="control-label">Quantity</label>
<input
class="form-control"
id="quantity"
value="0"
min="0"
max="20"
type="number"
/>
</div>
</li>
</ul>
<div class="price-box-bar">
<div class="cart-and-bay-btn">
<a class="btn hvr-hover" data-fancybox-close="" href="#"
>Buy New</a>
<button type = "submit">
<a class="btn hvr-hover" data-fancybox-close="" id= "qtyButton" data-fancybox-close="" href="{% url 'addCart' %}">Add to cart</a>
</button>
</form>
my js script
$('#qtyButton').click(function(e){
e.preventDefault();
var qty = $('#quantity').val();
var id = {{product.id}};
$.ajax({
type: "POST",
url: "{% url 'addCart' %}",
dataType: 'json',
data: {
"quantity":qty,
"product_id":{{product.id}},
}
});
});
my view.py file
def addCart(request):
if request.method == 'POST':
post = request.POST
quantity = post.get('quantity')
id = post.get('product_id')
item = Product.objects.get(id=id)
Cart.objects.get_or_create(user_id=request.user, product_id=item, quantity=quantity)
else:
return render(request, 'cart.html')
return redirect(request.META.get("HTTP_REFERER", "/"))
I tried so many things. But none of them is working. What should i do ?
You need to pass Jsonresponse() response instead of render() response like this
views.py
from django.http import JsonResponse
def CreditSaveView(request):
if request.method == 'POST':
creditform = CreditForm(request.POST)
if creditform.is_valid():
amt = request.POST['amt']
tag = request.POST['tag']
crs = request.POST['csrfmiddlewaretoken']
CreditModel(amt=amt,tag=tag).save()
return JsonResponse({'status':'done'}
script
<script>
document.getElementById("creditbtn").addEventListener("click", function () {
let id_amt = document.getElementById('id_amt').value;
let id_tag = document.getElementById('id_tag').value;
let crs = document.getElementsByName('csrfmiddlewaretoken')[0].value
my_data = { csrfmiddlewaretoken: crs, amt: id_amt, tag: id_tag };
console.log(my_data)
$.ajax({
url: "/creditsave/",
method: "POST",
data: my_data,
// dataType: "json",
success: function (data) {
if (data.status == 'done') {
// document.getElementById('creditform').reset()
console.log(data)
document.getElementsByTagName('form')[1].reset()
}
}
});
});
</script>
I am trying to do a Django Blog in Class Based Views. They're proving very difficult to me anyway. I feel like I'm pretty close...I suspect it's creating a new one because I'm combining DetailView and trying to include an UpdateView in my page. I'm overriding POST on the DetailView...and perhaps that's why when I try to do my Update of the comment the overriden Post on DetailView is overriding that action?
Here's my code....
HTML...
<!DOCTYPE html>
<form method='POST' class="comment-form">
{% csrf_token %}
<div class="spacer284">
{{ form.comment }}
</div>
<button class="button7" type="submit">Submit</button>
</form>
<div class="spacer285">
{% include 'suggestion_comments.html' %}
</div>
</div>
{% endblock %}
Note that I'm doing an include so that I can loop through the comments more easily...
Here's the include template...
{% if suggestion_comments %}
<h2>Comments</h2>
{% for comment in object.suggestion_comments.all %}
<div class="spacer291">
<p>{{ comment.author }} {{ comment.created_on }}</p>
<p class="spacer290">{{ comment.comment }}</p>
<div class="spacer289">
<div class="upvote-comment-count">{{ comment.total_comment_upvotes }}</div>
<div class="hide-delete">
<button type="button" class="button6" data-href="{% url 'Suggestions:suggestion_comment_like' comment.id %}">Like</button>
</div>
<div class="hide-delete">
<button type="button" class="button2" data-href="">Reply</button>
</div>
{% if comment.author == request.user %}
<button type="button" class="button4" id="{{ comment.id }}" pk="{{ object.pk }}" href="{% url 'Suggestions:suggestion_comment_edit' object.pk comment.id %}">Edit</button>
<div class="spacer159" id="hide_payment" style="display:none;">
<input name="comment" id="commentInput" value="{{ comment.comment }}" class="name"/>
<button class="button7">Submit</button>
</div>
<div class="hide-delete">
{% if user.userprofile.eDirector_queue_delete_confirm == "Yes" %}
<button type="button" class="button5" data-href="{% url 'Suggestions:suggestion_delete' comment.id %}">Delete</button>
{% else %}
<button type="button" class="button3" data-href="{% url 'Suggestions:suggestion_delete' comment.id %}">Delete</button>
{% endif %}
</div>
{% endif %}
</div>
</div>
{% endfor %}
{% else %}
<h2>No Comments Yet</h2>
{% endif %}
I'm attempting to use AJAX to do a replace...
$(document).on('submit', '.comment-form', function(e) {
e.preventDefault();
var $this = $(this);
$.ajax({
type: "POST",
url: $this.data("href"),
data: $this.serialize(),
dataType: "json",
csrfmiddlewaretoken: "{{ csrf_token }}",
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
},
success: function(response){
console.log("so far");
$('.spacer285').html(response['form']);
$(".comment-form")[0].reset();
$('.spacer288').empty('spacer288');
},
error: function (request, status, error) {
console.log(request.responseText);
showAjaxFormErrors(JSON.parse(request.responseText));
},
});
});
$(document).on('click', '.button7', function(e) {
e.preventDefault();
console.log("working123");
var $this = $(this);
var comment = $('#commentInput').val();
console.log(comment);
$.ajax({
type: "POST",
url: $this.data("href"),
data: { comment: comment},
csrfmiddlewaretoken: "{{ csrf_token }}",
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
},
success: function(data){
console.log(data);
$('.comment-form1').html(data);
},
});
});
My DetailView...
class SuggestionDetailView(LoginRequiredMixin,DetailView):
model = Suggestion
context_object_name = 'suggestion_detail'
template_name = 'suggestion_detail.html'
def get_context_data(self, **kwargs):
context = super(SuggestionDetailView, self).get_context_data(**kwargs)
attachments = SuggestionFiles.objects.filter(suggestion=self.object.pk).all()
form = SuggestionCommentForm()
suggestion_comments = SuggestionComment.objects.filter(suggestion_id=self.object.pk).order_by('-created_on').all()
context['attachments'] = attachments
context['form'] = form
context['suggestion_comments'] = suggestion_comments
return context
def post(self, request, *args, **kwargs):
form = SuggestionCommentForm(request.POST)
if form.is_valid():
new_comment = form.save(commit=False)
new_comment.author = request.user
new_comment.suggestion = self.get_object()
new_comment.save()
self.object = self.get_object()
context = self.get_context_data(object=self.object)
html = render_to_string('suggestion_comments.html', context, request=self.request)
return JsonResponse({'form': html})
else:
form_errors = form.errors.as_json()
response = HttpResponse(form_errors, status=400)
response['content_type'] = 'application/json'
return response
MyCommentUpdateView...
class SuggestionCommentUpdateView(LoginRequiredMixin, UpdateView):
model = SuggestionComment
fields = ["comment"]
def form_valid(self, form):
form.instance.suggestion_id = self.kwargs["pk"]
return super().form_valid(form)
And my URLs...
path("a7900f81-b66a-41ea-afc2-d7735e6d4824/suggestion_detail/<uuid:pk>/suggestion_comment_edit/<int:id>",views.SuggestionCommentUpdateView.as_view(), name='suggestion_comment_edit'),
path("a7900f81-b66a-41ea-afc2-d7735e6d4824/suggestion_detail/<uuid:pk>/",views.SuggestionDetailView.as_view(), name='suggestion_detail'),
This is all almost working....My issue is when I click on the edit button and attempt to edit the comment....it works...and updates the database...but it's adding a new updated comment instead of just editing the existing comment. Thanks in advance for any thoughts on what I might be doing wrong.
I am trying to implement a search function to search for users of my blog. In my base.html I have my navbar and within the navbar I have the following search form:
<form class="form-inline" method="POST">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">#</span>
</div>
{% csrf_token %}
<input id="user_search" type="text" class="form-control" placeholder="Username" aria-label="Username" aria-describedby="basic-addon1">
<ul class="list-group" id="results"></ul>
</div>
</form>
My ajax code looks as follows:
$('#user_search').keyup(function(){
$.ajax({
type: 'POST',
url: "{% url 'user-search' %}",
data: $(this).serialize(),
dataType: 'json',
success: function(response){
$('#results').html(response['form']);
console.log($('.profile-section').html(response['form']));
},
error: function(rs, e){
console.log(rs.responseText);
},
});
});
and my views.py search view looks as follows:
def user_search(request):
if request.method == 'POST':
search_text = request.POST['search_text']
else:
search_text = ''
users = User.objects.filter(username__icontains=search_text)
context = {
'users': users,
}
if request.is_ajax():
html = render_to_string('feed/user_search.html', context, request=request)
return JsonResponse({'form': html})
and the relevant part of my urls.py looks like this:
path('search/', login_required(views.user_search), name="user-search"),
When entering data in the input field I am getting a 403 HTTP error that says I am not using the csrf_token correctly, however I have included it as I did it before and it worked the other times before...
Any idea how I can solve the 403 error?
I had to change the JS part like this:
$(document).on('keyup', '.user-search-form', function(event){
event.preventDefault();
var input = $('#user_search').val();
console.log(input);
if (input.length > 2) {
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
success: function(response){
$('#results').html(response['form']);
console.log($('#results').html(response['form']));
},
error: function(rs, e){
console.log(rs.responseText);
},
});
}
else {
$('#results').empty();
}
});
and the python part in the views.py like that:
def user_search(request):
if request.method == 'POST':
search_text = request.POST.get('input')
users = User.objects.filter(username__icontains=search_text)
context = {
'users': users,
}
if request.is_ajax():
html = render_to_string('feed/user_search.html', context, request=request)
return JsonResponse({'form': html})
and now the search works!
Good day.
I'm trying to understand how to use ajax by deleting a object.
Main problem, i don't understand how to pass slug argument to url in AJAX call.
path('posts/<slug:slug>/delete/', DeletePost.as_view(), name='delete_post')
class DeletePost(CsrfExemptMixin, DeleteView):
queryset = Post.objects.all()
def get_object(self, queryset=None):
obj = super(DeletePost, self).get_object()
profile = Profile.objects.get(user_id__exact=self.request.user.id)
if obj.profile_id != profile.id:
raise Http404
return obj
def delete(self, request, *args, **kwargs):
self.get_object().delete()
payload = {'delete': 'ok'}
return JsonResponse(payload)
What i also want to understand, is the functionality correct? I've tested without json and get_object returns the correct object.
{% for post in user_posts %}
<tr id="post_table">
<th scope="row">
<input type="checkbox" aria-label="Checkbox" style="display: none">
</th>
<td class="tm-product-name">{{ post.title }}</td>
<td class="text-center">145</td>
<td class="text-center">{{ post.total_likes }}</td>
<td>{{ post.created_at }}</td>
<td><button class="delete-icon" onclick='deletePost({{ post.slug }})'>btn</button></td>
{#<td><i class="fas fa-trash-alt tm-trash-icon delete-icon" id="{{ post.id }}"></i></td>#}
<td>
{#<form method="post" action="{% url 'post:delete_post' post.slug %}" id="delete">#}
{#{% csrf_token %}#}
{#<i class="fas fa-trash-alt tm-trash-icon"></i>#}
{#</form>#}
</td>
</tr>
{% endfor %}
<script>
function deletePost(slug) {
let action = confirm('Are you sure you want to delete this post?');
if (action !== false) {
$.ajax({
method: 'POST',
url: '{% url 'post:delete_post'%}',
success: function (data) {
if (data.delete()) {
$('#post_table').remove()
}
}
});
}
}
</script>
Obviously this is the error that i currently have.
Reverse for 'delete_post' with no arguments not found. 1 pattern(s) tried: ['posts/(?P<slug>[-a-zA-Z0-9_]+)/delete/$']
Technically i just need a ping to the correct DeleteView url with a correct slug, is there a need to parse json in the DeleteView ?
Anyway found a solution.
Changed my view to
class DeletePost(CsrfExemptMixin, SingleObjectMixin, View):
model = Post
def post(self, *args, **kwargs):
self.object = self.get_object()
self.object.delete()
data = {'success': 'OK'}
return JsonResponse(data)
and modified the ajax request
var slug = document.getElementById('delete-icon').getAttribute('data-id');
function deletePost() {
let action = confirm('Are you sure you want to delete this post?');
let url = '/posts/' + slug + '/delete/';
if (action != false) {
$.ajax({
method: 'POST',
url: url,
dataType: 'json',
success: function (data) {
$('#post_table').remove()
}
});
}
}
So I have a model called Organization inside core/models.py. I am trying to implement CRUD Ajax on a single page. Inspired by this post. Every time I save an object of this model I get this error as shown below. I want to have multiple organizations that are unique.
core/models.py
class Organization(models.Model):
name = models.CharField(max_length=255, unique=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
gstin = models.CharField(max_length=15)
address = models.CharField(max_length=500)
city = models.CharField(max_length=50)
state = models.CharField(max_length=50)
zipcode = models.CharField(max_length=6)
country = models.CharField(max_length=50)
is_billed = models.BooleanField(default=False)
def __str__(self):
return f'{self.name} Organization'
core/forms.py
class OrganizationForm(forms.ModelForm):
class Meta:
model = models.Organization
fields = ('name', 'address', 'state', 'city', 'zipcode', 'country', 'gstin')
core/views.py
def save_organization_form(request, form, template_name):
data = dict()
if request.method == 'POST':
if form.is_valid():
stock = form.save(commit=False)
stock.user = request.user
stock.save()
data['form_is_valid'] = True
organizations = Organization.objects.all()
data['html_book_list'] = render_to_string('core/includes/partial_organization_list.html', {
'organizations': organizations
})
else:
data['form_is_valid'] = False
context = {'form': form}
data['html_form'] = render_to_string(template_name, context, request=request)
return JsonResponse(data)
#login_required(login_url="/accounts/login/")
def organization_create(request):
if request.method == 'POST':
form = OrganizationForm(request.POST)
else:
form = OrganizationForm()
return save_organization_form(request, form, 'core/includes/partial_organization_create.html')
templates/base.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>{% block head_title %}{% endblock %}</title>
{% block extra_head %}
{% endblock %}
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link href='https://fonts.googleapis.com/css?family=Russo One' rel='stylesheet'>
<link rel="stylesheet" type="text/css" href="{% static 'font/flaticon.css' %}">
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
{% block body %}
{% if messages %}
<div class="text-center">
<strong>Messages:</strong>
<ul>
{% for message in messages %}
<li>{{message}}</li>
{% endfor %}
</ul>
</div>
{% endif %}
{% block content %}
{% endblock %}
{% endblock %}
{% block extra_body %}
{% endblock %}
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
{% block javascript %}
{% endblock %}
</body>
</html>
templates/core/organization_list.html
{% extends 'base.html' %}
{% load static %}
{% block javascript %}
<script src="{% static 'organizations/js/organizations.js' %}"></script>
{% endblock %}
{% block content %}
<h1 class="page-header">Organizations</h1>
<!-- BUTTON TO TRIGGER THE ACTION -->
<p>
<button type="button"
class="btn btn-primary js-create-book"
data-url="{% url 'organization_create' %}">
<span class="glyphicon glyphicon-plus"></span>
New Organization
</button>
</p>
<table class="table" id="book-table">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Address</th>
<th>State</th>
<th>City</th>
<th>Zipcode</th>
<th>Country</th>
<th>Billing Active</th>
</tr>
</thead>
<tbody>
{% include 'core/includes/partial_organization_list.html' %}
</tbody>
</table>
<!-- THE MODAL WE WILL BE USING -->
<div class="modal fade" id="modal-book">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
</div>
{% endblock %}
templates/core/partial_organization_list.html
{% for organization in organizations %}
<tr>
<td>{{ organization.id }}</td>
<td>{{ organization.name }}</td>
<td>{{ organization.address }}</td>
<td>{{ organization.state }}</td>
<td>{{ organization.city }}</td>
<td>{{ organization.zipcode }}</td>
<td>{{ organization.country }}</td>
<td>{{ organization.is_billed }}</td>
<td>
<button type="button"
class="btn btn-warning btn-sm js-update-book"
data-url="{% url 'organization_update' organization.id %}">
<span class="glyphicon glyphicon-pencil"></span> Edit
</button>
<button type="button"
class="btn btn-danger btn-sm js-delete-book"
data-url="{% url 'organization_delete' organization.id %}">
<span class="glyphicon glyphicon-trash"></span> Delete
</button>
</td>
</tr>
{% empty %}
<tr>
<td colspan="8" class="text-center bg-warning">No Organization</td>
</tr>
{% endfor %}
static/organizations/js/organizations.js
$(function () {
$(".js-create-book").click(function () {
$.ajax({
url: '/profile/organization/create/',
type: 'get',
dataType: 'json',
beforeSend: function () {
$("#modal-book").modal("show");
},
success: function (data) {
$("#modal-book .modal-content").html(data.html_form);
}
});
});
});
$("#modal-book").on("submit", ".js-book-create-form", function () {
var form = $(this);
$.ajax({
url: form.attr("action"),
data: form.serialize(),
type: form.attr("method"),
dataType: 'json',
success: function (data) {
if (data.form_is_valid) {
$("#book-table tbody").html(data.html_book_list); // <-- Replace the table body
$("#modal-book").modal("hide"); // <-- Close the modal
}
else {
$("#modal-book .modal-content").html(data.html_form);
}
}
});
return false;
});
$(".js-create-book").click(function () {
var btn = $(this); // <-- HERE
$.ajax({
url: btn.attr("data-url"), // <-- AND HERE
type: 'get',
dataType: 'json',
beforeSend: function () {
$("#modal-book").modal("show");
},
success: function (data) {
$("#modal-book .modal-content").html(data.html_form);
}
});
});
$(function () {
/* Functions */
var loadForm = function () {
var btn = $(this);
$.ajax({
url: btn.attr("data-url"),
type: 'get',
dataType: 'json',
beforeSend: function () {
$("#modal-book").modal("show");
},
success: function (data) {
$("#modal-book .modal-content").html(data.html_form);
}
});
};
var saveForm = function () {
var form = $(this);
$.ajax({
url: form.attr("action"),
data: form.serialize(),
type: form.attr("method"),
dataType: 'json',
success: function (data) {
if (data.form_is_valid) {
$("#book-table tbody").html(data.html_book_list);
$("#modal-book").modal("hide");
}
else {
$("#modal-book .modal-content").html(data.html_form);
}
}
});
return false;
};
/* Binding */
// Create book
$(".js-create-book").click(loadForm);
$("#modal-book").on("submit", ".js-book-create-form", saveForm);
// Update book
$("#book-table").on("click", ".js-update-book", loadForm);
$("#modal-book").on("submit", ".js-book-update-form", saveForm);
// Delete book
$("#book-table").on("click", ".js-delete-book", loadForm);
$("#modal-book").on("submit", ".js-book-delete-form", saveForm);
});
And when I add a new organization I get the following error:
django.db.utils.IntegrityError: UNIQUE constraint failed: core_organization.name
How do I fix this?
I believe your javascript file contains duplicate ajax calls.
There are 3 calls to create your modal:
$(function () {
$(".js-create-book").click(function () {
at the top of your js file. Then the same function in the middle of your js file. And
var loadForm = function ()
which your binding to the click event at the bottom of your script.
In addition there are two functions handling the submission of the form data:
$("#modal-book").on("submit", ".js-book-create-form", function ()
in the top part and
var saveForm = function ()
in the bottom part.
The duplicate regarding the submission of the form can cause the unique constraint error because you are submitting the same data twice. The duplication of the loading of the modal probably does not cause any noticable errors, but is unnecessary load.
The bottom part of your javascript file, i.e. the part beginning with
$(function () {
/* Functions */
should be sufficient.
I think you are having this issue, because of the unique=True constraint on your name field
name = models.CharField(max_length=255, unique=True)
This means that the name is going to be unique for all users, and you will keep getting UNIQUE constraint failed error everytime you add the same name for different users.
To solve this, I suggest using unique_together meta option.
All you have to do, is removing the unique constraint from name field, and adding Meta class with the unique_toghether option to include both the user_id and name fields.
class Organization(models.Model):
name = models.CharField(max_length=255)
user = models.ForeignKey(User, on_delete=models.CASCADE)
address = models.CharField(max_length=1000, default=None)
is_billed = models.BooleanField(default=False)
def __str__(self):
return f'{self.name} Organization'
class Meta:
unique_together = ['name', 'user_id']
Then, python manage.py makemigrations, python manage.py migrate.
The UNIQUE constraint going to remain, but it is going to be for all Organization names related for one user.
If USER1 have organization ORG1, and tried to add another ORG1, it is going to fail, but if USER2 added ORG1 it is going to work successfully.
Try updating the instance rather than form object, Create separate endpoint/logic for updating instance and an separate endpoint/logic to create objects using form
views.py
def save_organization_form(request, form, template_name):
data = dict()
if request.method == 'POST':
if form.is_valid():
stock = form.instance
stock.user = request.user
stock.something = request.something
stock.save()
data['form_is_valid'] = True
organizations = Organization.objects.all()
data['html_book_list'] = render_to_string('core/includes/partial_organization_list.html', {
'organizations': organizations
})
else:
data['form_is_valid'] = False
context = {'form': form}
data['html_form'] = render_to_string(template_name, context, request=request)
return JsonResponse(data)
#login_required(login_url="/accounts/login/")
def organization_create(request):
if request.method == 'POST':
form = OrganizationForm(request.POST)
else:
form = OrganizationForm()
return save_organization_form(request, form, 'core/includes/partial_organization_create.html')