Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
kombu.exceptions.EncodeError: Object of type ShiftBooking is not JSON serializable in Django 3.0
I have updated my project from Django 1.8 tom Django 3.0 Here when sending an confirmation email through celery i am getting this error Django = 3.0 Python = 3.7 celery = 5.1.2 Here is my views.py class JobShiftCreateView(CreateView): template_name = 'contract_worker/job_shift_form.django.html' form_class = JobShiftForm context_object_name = "job_shift" model = ShiftBooking def get_context_data(self, **kwargs): .... .... def get_form_kwargs(self): .... .... def form_valid(self, form): addtional_days = form.cleaned_data['addtional_days'] booked_with = form.cleaned_data['booked_with'] or None date = form.cleaned_data['date'] location = form.cleaned_data['location'] week_start = date - datetime.timedelta(days=(date.weekday())) x = datetime.datetime.strftime(week_start, '%d-%m-%Y') week_start = datetime.datetime.strptime( x, '%d-%m-%Y').strftime('%d-%m-%Y') self.object = form.save(commit=False) for i in range(0, int(addtional_days) + 1): self.object.pk = None if i == 0: days = 0 else: days = 1 date = date + datetime.timedelta(days=days) self.object.client = self.request.user.client self.object.created_by = self.request.user self.object.booked_with = booked_with self.object.date = date self.object.save() messages.success(self.request, 'Shift created successfully.') send_shift_mail_for_booking.delay(self.object, self.request.user) Here is my tasks.py @celery_app.task(bind=True) def send_shift_mail_for_booking(self, object, user): template_src = 'contract_worker/shift_confirmation_mail.html' template = get_template(template_src) from_email = settings.DEFAULT_FROM_EMAIL if user.client.email_validated_status == 'Validated': from_email = user.client.replay_to_email context = { 'user': user, 'client': user.client, 'object': object } context = Context(context) html = template.render(context) subject = 'Shift offer from ' + ' ' + str(user) + ' ' message = get_template('contract_worker/shift_confirmation_mail.html').render(Context(context)) email = EmailMessage(subject, … -
django forms for widget
I am working on a manual form for creating a post for a forums, I cannot get the categories to work, for the different forums. My forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ["title", "content", "categories", "tags"] def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['categories'].widget.attrs['readonly'] = True Here is my views.py def posts(request, slug): category = get_object_or_404(Category, slug=slug) posts = Post.objects.filter(approved=True, categories=category) context = { 'posts': posts, 'forum': category, 'title': 'Posts' } return render(request, 'forums/posts.html', context) @login_required def create_post(request): context = {} form = PostForm(request.POST or None) if request.method == "POST": if form.is_valid(): print("\n\n form is valid") author = Author.objects.get(user=request.user) new_post = form.save(commit=False) new_post.user = author new_post.save() form.save_m2m() return redirect('forums') context.update({ 'form': form, 'title': 'Create New Post' }) return render(request, 'forums/create_post.html', context) And last my html for creating a post <form method="POST" action="." enctype="multipart/form-data"> {% csrf_token %} <div class="mb-4"> <label for="{{ form.categories.id_for_label }}" class="form-label">{{ form.categories.label }}:</label> <input class="input is-medium" name="{{ form.categories.html_name }}" type="text" class="form-control" id="{{ form.categories.id_for_label }}" value="{{ request.forum }}"readonly> </div> </form> If I use the django build inn form, it all works, but I wanted to use own form so that it look a bit better and can be placed around. So if anyone know a … -
I want to compress an image in view before saving, but the file size stays the same
I have a functional update view that I am trying to compress uploaded images before saving them. However, when I try to compress the image, nothing happens and instead just saves the image with the exact same size. I think I might be saving it wrong, but I am unsure of how to save it correctly. Please let me know. Thank you! import io from PIL import Image def get_compressed_image(file): image = Image.open(file) with io.BytesIO() as output: image.save(output, format=image.format, quality=20, optimize=True) contents = output.getvalue() return contents def updated_form_view(request) ... if initial_form.is_valid(): initial_form.clean() updated_form = initial_form.save(commit=False) updated_form.username = request.user.username # compressing image here updated_form.form_image.file.image = get_compressed_image(updated_form.form_image) updated_form.save()``` -
Django Filtering - Field 'testcaseidstring' expected a number but got 'tc123'
I am trying to apply a filter on a Django model based on a column name That column is a Foreign Key Code - Inside models.py - testcaseidstring = models.ForeignKey('Testcaseidstructure', models.DO_NOTHING, db_column='testCaseIdString') Inside views.py - sessid_qs=History.objects.using("otherdb").filter(testcaseidstring="tc123") This gives me the following ERROR - Field 'testcaseidstring' expected a number but got 'tc123' How am I supposed to filter on this column? -
Build Django Query Dynamically based on kendo UI filter
I'm trying to query a database based on user filter. i received following input from kendo UI grid. { "filter":{ "filters":[ { "logic":"or", "filters":[ { "field":"aging", "operator":"eq", "value":24 }, { "field":"aging", "operator":"eq", "value":13 } ] }, { "logic":"or", "filters":[ { "field":"follow_up_name", "operator":"eq", "value":"Call Insurance Provider" } ] }, { "logic":"or", "filters":[ { "field":"patient_name", "operator":"eq", "value":"kartik" } ] }, { "logic":"and", "filters":[ { "field":"created_date", "operator":"eq", "value":"2022-01-09T18:30:00.000Z" }, { "field":"created_date", "operator":"gte", "value":"2022-01-04T18:30:00.000Z" } ] }, { "logic":"or", "filters":[ { "field":"follow_up_status", "operator":"eq", "value":"Open" } ] }, { "logic":"or", "filters":[ { "field":"role_name", "operator":"eq", "value":"Pharmacist" } ] }, { "logic":"or", "filters":[ { "field":"last_response", "operator":"eq", "value":"To-Patient" } ] } ], "logic":"and" }, "skip":0, "take":10 } Based on above data i need both 'and' & 'or' condition to build query dynamically. and pass it to database. also filter can contain multiple list. also want to make these class common which can take only UI arguments build query and return. please provide a solution for these. -
django - add l<a> tag - render_to_string
in my view.py: subject = "Thank you for your payment!" template = render_to_string('cart/email_template2.html', {'name': request.user.first_name, 'transaction_id' : transaction_id, 'total':total, 'items': items}) to = request.user.email res = send_mail(subject , template , settings.EMAIL_HOST_USER, [to], fail_silently=True) in my email_template2.html: Dear {{name}}, Thank you for making your payment towards: Your Transaction ID is {{transaction_id}} Total Amount Paid is {{total}} AED It’s been a pleasure doing business with you and below you will see the links to download your purchased items. {% for i in items %} <a href="l{{ i }}"></a> {% endfor %} Best wishes, here is the email i receive (output): Email received from the app "i" are the links for the items to be downloaded but they are presented as text not links. How to add a link? I tried to add tag but in the email it stays that way. Thanks... -
Is there a way to render a React component *UI* into Django without calling APIs?
I've been working on my Django App for a couple of months now and decided to use React as my front-end, which I know is bad habit for development and makes everything a lot more complicated. I run npm build for my front-end app with Django, but when I launch the Django Project, it shows me the Django Rest Apis. When I wanted it to show me my UI, I built in React. Everything in my Django settings should be correct from tutorials and documentations, so I believe that isn't the issue. I've tried calling the my API's but I believe that isn't the issue either. I am trying to keep everything as simple as possible, so if I'm missing stuff in my code I apologize, I just want to understand the very basics of React without having a lot of side code. Here is my App.js import React from 'react'; import './App.css'; import Form from './Form'; class App extends React.Component { render(){ return( <Form /> ) } } export default App; index.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') ); -
Data is saving as [object Object] in database
form.html <form data-bind="submit: save" enctype="multipart/form-data" > {% csrf_token %} <table border="1"> <tr> <td>Title: <input type="text" name="title" id="title" data-bind="value: $data.title"></td> <br> </tr> <tr> <td>Description: <textarea name="description" id="description" data-bind="value: $data.description">Description</textarea></td> <br> </tr> <tr> <td>Image: <input type="file" name="image" id="image" ></td> <br> </tr> <tr> <td><button type="button" id="submit" data-bind="click: save">Submit</button></td> </tr> </table> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script> <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); </script> <script> var ViewModel = function () { var self = this; self.save = function () { var formdata = new FormData(); formdata.append('image', $('#image').get(0).files[0]); formdata.append('title', ko.observable("")); formdata.append('description', ko.observable("")); console.log(formdata) $.ajax({ type: 'POST', url: "{% url 'productsadd' %}", data: formdata, headers: {'X-CSRFToken': csrftoken}, processData: false, contentType: false, success: function (){ alert('The post has been created!') window.location = '{% url "productslist" %}'; }, error: function () { alert("fail"); } }); }; }; ko.applyBindings(new ViewModel()) </script> views.py class ProductsCreate(CreateView): model = … -
How to connect React native with django rest api
I build a simple django rest api now i need to fetch data from it in frontend using React Native. I can make a request to the api but the data is not coming from there. I search about it a lot but didn't find any help Thanks in advance... -
Django-treebeard with Django rest framework
class Category(MP_Node): name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=50, unique=True, null=True) node_order_by = ['name'] def save(self, *args, **kwargs): if not self.slug: slug = self.name self.slug = slugify(slug) super(Category, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('brands', args=[self.slug]) def __str__(self): return self.name class CategorySerializer(ModelSerializer): class Meta: model = Category fields = '__all__' read_only_fields = ['slug'] class CategoryCreateSerializer(ModelSerializer): parent_id = SerializerMethodField(allow_null=True, method_name='parent_id', read_only=True) def get_parent_id(self, data): if 'parent_id' in data: return data['parent_id'] else: return None class Meta: model = Category fields = ('name', 'parent_id') read_only_fields = ['parent_id'] def create(self, validated_data, *args, **kwargs): value = self.initial_data.dict() parent_id = self.get_parent_id(value) if parent_id is None: data = Category.add_root(**validated_data) value = Category.objects.get(id=data.id) data_serializer = CategoryCreateSerializer(value) return Response(data_serializer.data, status=status.HTTP_201_CREATED) else: if Category.objects.filter(id=parent_id).exists(): date = Category.objects.get(id=parent_id) value = date.add_child(**validated_data) return Response(value.name) class CategoryModelViewSet(ModelViewSet): queryset = Category.objects.all() lookup_field = 'slug' def get_serializer_class(self): if self.action == 'create': return CategoryCreateSerializer else: return CategorySerializer 'CategoryCreateSerializer' object has no attribute 'parent_id' what should i return in Response ? E:\nth\django_tree_drf\venv\lib\site-packages\rest_framework\fields.py, line 1885, in to_representation -
How to restore integers from my json.dumps file (for display in my javascript chart) when using Django
In my Django application, I have a very basic Pie Chart model with the name column as a CharField and the stats column as an IntegerField. I also have some javascript code on my html page that displays a pie chart -- but I'm only able to get it working if I hardcode the values as an array. I was hoping to instead display the data from my model/ DB as {{ values|safe }} in pie chart form, pulling the values from json dumps of my DB data. Here's what I've tried, as seen in my views.py file: def metrics(request): pietitle = serializers.serialize('json', PieChart.objects.all(),fields=('title')) piestats = serializers.serialize('json', PieChart.objects.all(),fields=('stats')) piedata=[[pietitle, piestats]] json_data = json.dumps(piedata) data_json= json.loads(json_data) return render(request, "metrics.html", {"values": data_json}) On my HTML page, the message I'm getting is simply "No Data", and I'm fairly certain that's because when I serialize the stats field, it's converted to a string and is unable to be interpreted as integers. Would anyone kindly be able to assist? Thanks so much, in advance. -
Django implementation go bcrypt. GenerateFromPassword and bcrypt.Com pareHashAndPassword function
Django implementation go bcrypt. GenerateFromPassword and bcrypt.Com pareHashAndPassword function,whether Django bcrypt can be implemented? -
Django permission denied to delete comment
i have a problem with my blog comment delete. It works properly when the user is superuser, but keep getting "django.core.exceptions.PermissionDenied [07/Jan/2022 01:47:09] "GET /blog/comentario/eliminar/6/ HTTP/1.1" 403 135" when the user is comment autor but no superuser. here is my code: Model. class BlogComentario(models.Model): post = models.ForeignKey(BlogPost,on_delete=models.CASCADE,related_name="comentarios") nombre = models.ForeignKey(Usuario,on_delete=models.CASCADE) email = models.EmailField(max_length=100) contenido = models.TextField(max_length=500) publicado = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) class Meta: ordering = ('-publicado',) db_table= "blog_comentario" def __str__(self): return f"comentado por {self.nombre}" view class ComentarioEliminar(UserPassesTestMixin,DeleteView): template_name = 'Blog/Comentarios/comentario_eliminar.html' model = BlogComentario def get_success_url(self, **kwargs): return reverse('blog:blog_inicio') def test_func(self): obj = self.get_object() return obj.nombre == self.request.user or self.request.user.is_superuser -
django-Ajax Getting same button value for autogenerated Button's
Iam having a webpage which contains Multiple Buttons Generated using django.Using ajax,When I click a button the value send to server is of first button only.The button value is set according to value passed through context from django.Heres's the Code: <form method="POST" id='form'> {% csrf_token %} <div class="shadow p-3 mb-5 bg-body rounded" style="height: fit-content;"> <h5 class="card">Choose A Day!</h5> <p class="card-text">Booking Can be made for Next 15 Days.</p> <div class="btn-group" role="group" aria-label="Basic example"> <div class="row row-cols-3 row-cols-md-5 g-4"> {% for d,y in dates.items %} <div class="col"> <div class="card"> <button id='dt' name="date" type="submit" value={{d}} class="btn btn-success card-body shadow" style="font-size: 15px; width: fit-content;"> <div style=" margin-top: -15px; width: 100%; margin-bottom: 5px;"> <p style="font-weight: bolder;" class="card-text">{{y}}</p> </div> <div> <p class="card-text">{{d}}</p> </div> </button> </div> </div> {% endfor %} </div> </div> </div> </form> Ajax Code: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script> $('#form').on('submit', function(e){ e.preventDefault(); $.ajax({ type : "POST", url: "", data: { date : $('#dt').val(), csrfmiddlewaretoken:'{{ csrf_token }}', }, success: function(data){ /* response message */ }, failure: function() { } }); }); </script> When i try to print the request.POST on views.py it shows same value of every button. Thanks In Advance -
React .map function not working after Django backend GET with axios
I am trying to make a simple React frontend while using Django Rest Framework as a backend. When I make the call to Django and then try to use the .map function to display the data, I get an "Uncaught (in promise) TypeError: this.state.users.map is not a function". I am a React noob so it is definitely something I am doing. import React from 'react'; import axios from 'axios'; class App extends React.Component { state = { users: [] } componentDidMount() { axios.get('http://127.0.0.1:8000/api/users/') .then(res => { const users = res.data; this.setState({ users }); }) } render() { return ( <ul> { this.state.users.map(user => <li>{user.username}</li>)} </ul> ) } } export default App; -
Likes, Dislikes & Views using Django Rest Framework
I'm working on a News Model where I want to perform the likes, dislikes & no of views functionality using the Django Rest Framework(ModelViewset). I have created a model for it Models.py class Post(models.Model): NEWS_TYPE = (('Images','Images'),('Multi-Images','Multi-Images'),('Image-Text','Image-Text'), ('Audio-Video','Audio-Video'),('Audio-Video-Text','Audio-Video-Text'),('Audio','Audio'), ('Audio-Text','Audio-Text')) POST_STATUS = (('Pending','Pending'),('Verified','Verified'),('Un-Verified','Un-Verified'), ('Published','Published'),('Mint','Mint')) category = models.ForeignKey(Category, on_delete=models.CASCADE) post_type = models.CharField(max_length=100, verbose_name='Post Type', choices=NEWS_TYPE) title = models.TextField(verbose_name='News Title') content = models.TextField(verbose_name='News Content') hash_tags = models.CharField(max_length=255, verbose_name='Hash Tags') source = models.CharField(max_length=255, verbose_name='News Source') author = models.ForeignKey(User, related_name='Post', on_delete=models.CASCADE) views = models.ManyToManyField(User,related_name='Views') likes = models.ManyToManyField(User, related_name='Likes') dislikes = models.ManyToManyField(User, related_name='Dislikes') status = models.CharField(max_length=20, verbose_name='Status', choices=POST_STATUS) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return (self.post_type)+ '-' +self.title serializers.py class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' views.py class PostAPI(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer I have tried a lot of ways,but i'm not able to like, dislikes or view the post by multiple users. When a post is liked or disliked by one user & try to like or dislike by another user, it says Like with this post already exist Is there anything that I have left out. Please help it would be a great support. Thanks alot. -
How do I remove the ticks or inner circles of my polar area chart Chart.js
I have written the code for my chart in Jquery and I am using the chart to display data on my Django Web Page, I want to remove the inner circles which I think are called ticks along with the small numbers that are displayed with them. I have tried to use the ticks:{ display: false, } and scale:{ display: false, } but have had no luck with either I am not sure how to do it. Code for Chart: new Chart("chart_{{ i.pk }}_{{ t.pk }}", { type: "polarArea", data: { labels: labels_{{ t.pk }}, datasets: [{ fill: true, pointRadius: 1, {# borderColor: backgroundColors_{{ t.pk }} ,#} backgroundColor: backgroundColors_{{ t.pk }} , data: totals_{{ i.pk }}_{{ t.pk }}_arr, }] }, options: { responsive: false, maintainAspectRatio: true, plugins: { legend: { display: false, }, scale: { ticks: { display: false, }, gridLines: { display: false, lineWidth: 7, tickMarkLength: 30// Adjusts the height for the tick marks area }, }, title: { display: false, text: 'Chart.js Polar Area Chart' } } } }); {% endfor %} {% endfor %} {% endblock %} -
How to fix urls patterns testing views in django?
testviews.py class StudentsDetailsViewTest(TestCase): def test_query_search(self): query_set=StudentDetails.objects.raw('SELECT * FROM collegedetails.college_studentdetails LIMIT 3;') url=(reverse('api/Student_Details', args=(query_set))) response=self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) output: django.urls.exceptions.NoReverseMatch: Reverse for 'Student_Details' with arguments '(<StudentDetails: Demon>, <StudentDetails: Stefen>, <StudentDetails: james>)' not found. 1 pattern(s) tried: ['api/students\Z'] Ran 1 test in 0.248s FAILED (errors=1) Destroying test database for alias 'default'... I'm trying to testing my query_set views and to figure out testing passing or not, that showing not found pattern i don't get that error means, is there any error near line url? can anyone suggest me what went missing in code? -
Many to one and many to many relationship between same models in django
I am working on a project in django. There are two models similar to users and courses where any user can create multiples course and other users can join any of the courses. So this leads to two relation between the models(users and courses), one to many for creater of a course and many to many for users who join the course. Django gives error on defining two relations on the same models. Currently I have defined foreignkey field in courses table for reference to creater(user) and a third model with foreign key of both the user and courses to keep track of users who join the courses. I just want to know is there a better known way to do this in django. -
Image is not saving in database django
form.html <form> {% csrf_token %} <table> <tr> <td> <label for="name">NAME: </label> <input type="text" data-bind="value: $data.name" name="name" class="form-control" id="name" placeholder="name of product"> </td> </tr> <tr> <td> <label for="price">PRICE </label> <input type="text" name="price" data-bind="value:$data.price" class="form-control" id="price" placeholder="price"> </td> </tr> <tr> <td> <label for="description">DESCRIPTION: </label> <textarea cols="10" rows="5" name="description" data-bind="value:$data.description" class="form-control" id="description" placeholder="product description"></textarea> </td> </tr> <tr> <td> <label for="image">IMAGE: </label> <input type="file" class="form-control-file" id="image" name="image" required> </td> </tr> <tr><td><button type="button" id="submit" data-bind="click : save" class="btn btn-success">Submit</button></td></tr> </table> </form></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script> <!-- <script type="application/javascript" src="static/js/knockout-file-bind.js"></script> --> <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); </script> <script> // $(document).on('click', '#submit', function(e) { var ViewModel = function () { var self = this; self.name = ko.observable(""); self.price = ko.observable(""); self.description = ko.observable(""); self.image = $(document).on('click', "#submit", function(e) { formdata = new FormData(); $('#image').get(0).files[0]; formdata.append('image', image); }); // self.image =$('#image').get(0).files[0]; // formdata = new FormData(); // formdata.append("image", image); // console.log(formdata.get("image")); var PerData = { name: … -
Passing an ID parameter to the Django Channel connect handler for single channel layers
I am setting up a Single Channel websocket layer as documented here https://channels.readthedocs.io/en/stable/topics/channel_layers.html#single-channels But the problem is I need to pass a meta data parameter into the connect method from client-wide websocket initilization because otherwise there is no way to reference it outside of the Consumer. E.g. imagine I want to use a SESSION_ID as the channel name lookup key. Only the client knows the SESSION_ID. I want to be able to do something like: client.js (pass the session id to the websocket connection somehow) monitorWS = new WebSocket('ws://localhost:9000/ws/api/monitor/?SESSION_ID=762123') consumer.py (save the session id with the auto-generated channel name) class ChatConsumer(WebsocketConsumer): def connect(self): # Make a database row with our channel name Session.objects.create(channel_name=self.channel_name, id=[SESSION_ID]) How can I pass that ID parameter so that my code outside the Consumer can pick up the single channel name so that I can do something like this: elsewhere.py from channels.layers import get_channel_layer channel_layer = get_channel_layer() session=Session.objects.get(id=762123) # get the session object in the example await channel_layer.send(session.channel_name, { "type": "chat.message", "text": "Hello there!", }) -
is it possible to prevent/bar more than one person from accessing a page with Django?
Is it possible to prevent/bar more than one person from accessing a page with Django? For example: I have an editing screen for a product, and if someone is accessing that page, for that product, I don't want anyone but can enter that url, to be clearer, let's say I'm editing a product called "smartphone " and his route is http://localhost:8000/product/edit/smartphone, when someone tries to edit this product, he cannot enter the page. That's my question. I don't know if it was very clear, but I ask that whoever knows can help me. -
htmx and django: display feedback on successful/failed request
So I'm trying to display a feedback message saying "added" or "failed" when a form is submitted with HTMX to my Django backend. Basically what I have right now is a form that performs an hx-post, and the reply is a div containing the updated information, which is swapped with the current contents of the div. <div id="list"> <!-- The stuff in here is loaded through another template, which is the result of a successful myApp:add operation. --> </div> <form hx-post="{% url 'myApp:add' eid=e.id %}" hx-swap="outerHTML" hx-target="#list"> <!-- Some stuff in here --> </form> <div id="result"> <!-- Here I should print a message saying correct or incorrect depending on the HTMX result (if the entry was added or there was any kind of error, even connection errors) --> </div> The thing is, in case of an error in the form or in the request itself, the list will remain the same, but I would like for it to print something like "error" in the result div. In case the new entry is added correctly I would like to print a "success" message in the result div. I'm also using Alpine.js, if that's any help. -
What is the best way to collect a log of C++ Application, Running in k8s + django Server?
I've tried searching through Google, but I'm confused which one is the best way. There are ways to use stdout and stderr, but I would like to use a more convenient framework. Is there any tip or standardized way you can give me? -
is that possible to add mutiple images save in one column in mysql using dajngo framework
iam a beginner in the field. i currently doing a ecommerce website which sells samrtphone. 1 .I want to add mulitple product images. In order to add the images do i need more columns for every image. How to add mutiple ram and price for product. Samrtphone have mutiple ram according to ram price varies.user can choose ram of the product. How to add this in to my project using mysql. Do ineed more columns for every ram.