Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin looks different when I use incognito mode, and I want it always to look like the one in incognito
UI in incognito mode: https://drive.google.com/file/d/10d874FS4JjaB_lJ0aJK29BVcP-dWfu0P/view?usp=sharing UI in normal mode: https://drive.google.com/file/d/1z7iYb6Lx755S1jqTJvW3r47ml-JY8NJV/view?usp=sharing -
Django translation with variable not working
If I do the following works: django.utils.translation.gettext("hola mundo %(variable)s") % { "variable": "test" } Result: 'Une test' But if I do the following it doesn't work: class SiteText(models.Model): HOLA1 = django.utils.translation.gettext_noop("hola mundo %(variable)s") % { "variable": "test" } HOLA2 = django.utils.translation.gettext_lazy("hola mundo %(variable)s") % { "variable": "test" } HOLA3 = django.utils.translation.gettext("hola mundo %(variable)s") % { "variable": "test" } HOLA4 = django.utils.translation.ugettext_lazy("hola mundo %(variable)s") % { "variable": "test" } SiteText.HOLA1 SiteText.HOLA2 SiteText.HOLA3 SiteText.HOLA4 Results: hola mundo test Without variables YES it works, but with variables NO. Why doesn't it work? -
Trying to send emails using Django OSError: [Errno 101] Network is unreachable
I was trying to send email from gmail account to another using django as show in images below settings.py file https://i.stack.imgur.com/4GXMx.png then i get this error when i use the send_mail() OSError: [Errno 101] Network is unreachable https://i.stack.imgur.com/5kISS.png -
How to Deploy a Django Web Application on the compagnie server (Windows Server)
I have just finished the first phase of a Django project (CRM) and willing to deply it in the server we have at the compagnie's level (A Windows server). the objective is to make the application accessible for my co-workers once the are connected to the server. Can you guide me how to do that or recommend some useful tutorials? -
ManyToMany relation queryset result when using prefetch_related
I have the following models shown below. class Document(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,null=True,blank=True) name = models.CharField(max_length=255,null=True, blank=True) url = models.TextField(null=True, blank=True) objection_no = models.CharField(max_length=255,null=True, blank=True) file = models.FileField(upload_to='objections/',storage=RawMediaCloudinaryStorage()) size = models.CharField(max_length=255,null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now_add=True) class Property(models.Model): """Represents property class model""" serial_no = models.CharField(unique=True,max_length=255,blank=True,null=True) map_no = models.CharField(max_length=255,blank=True,null=True) lr_no = models.CharField(max_length=255,blank=True,null=True) locality = models.CharField(max_length=255,blank=True,null=True) class PropertyObjection(models.Model): """Represents property objection class. This has properties that have been objected""" objector_name = models.CharField(max_length=255,null=True, blank=True) objection_no = models.CharField(max_length=255,null=True, blank=True) properties = models.ManyToManyField(Property,blank=True) documents = models.ManyToManyField(Property,blank=True) ratable_owner = models.BooleanField(null=True,blank=True) ratable_relation = models.CharField(max_length=50,null=True, blank=True) serializer.py class CustomPropertyObjectionSerializer(serializers.Serializer): objection_no = serializers.CharField() properties__serial_no = serializers.CharField() properties__id = serializers.IntegerField() properties__map_no = serializers.CharField() properties__lr_no = serializers.CharField() ratable_owner = serializers.BooleanField() ratable_relation = serializers.CharField() documents = DocumentSerializer(many=True) class Meta: model = PropertyObjection fields = [ 'properties__serial_no', 'properties__id', 'properties__map_no', 'properties__lr_no', 'properties__locality', 'documents' ] I have the following implementation below and would like to refactor it to return also the documents as a list of objects so that the are serialized into a JSON list. When I make a request I get the following error: TypeError at api/all_objections/'int' object is not iterable. The documents field is returning documents an integer from the queryset result but the field documents in the PropertyObjection model … -
Django ImageField Creating New Folder by ID on upload?
I'm Currently developing creating app with a ManyToMany ImageField Relantionship . I want to have the ImageField save all images to a specific folder based on the ID of the Relantionship. I want to have something like this. class PostImages(models.Model): image = models.ImageField(upload_to='Post_Images/post/' + post.id) class Post(models.Model): images = models.ManyToManyField(JobImages) How do I access the post.id to do this ? Would this affect Database optimization in any way when I deploy ? I intend for this app to have a few thousand users and was gonna use AWS for the images. I mostly want to do this for organization purposes right now cause its on my local machine but also see no reason to change it when I deploy. -
pass some variable of a row in Vue.js as parameters to vue.js method and send out using axios
I have a web app, used Django as backend, Vue.js for the frontend. In the cell, that's a button for every row, which is supposed to get the detail info of the row after click. So I want to pass some variable of a row in Vue.js as parameters to Vue.js method. But I failed to do that, when I tried to click the button, it always submitted the form, but I have added type="button" already. <tbody> <tr v-for="(row, index) in filteredRows" :key="`isbn-${index}`"> <td name="`title_${index}`" v-html="highlightMatches(row.title)">{{ row.title }}</td> <td v-html="highlightMatches(row.author)">{{ row.author }}</td> <td><button type="button" v-on:click="greet( $event, {{ row.title }})">Greet</button></td> <td name="`discipline_code_course_code_${index}`" bgcolor= "white"><div contenteditable></div></td> </tr> </tbody> <script> const app = new Vue({ el: '#app', data:() => ({ filter: '', rows: book_rows }), methods: { greet: function (event, title) { alert(title); #undefined when debug this.$http.post( '/check_code/', { title: title } ); } }, </script> How could I pass some variable of a row in Vue.js as parameters to Vue.js method and send out using axios? -
python command only gives "Python"
enter image description here i got a terminal problem using python. ex) when typing "python --version" and tapping Enter, my terminal only gives "Python" all the other command starting with "python" gives "Python", without executing the command i think it's not that complicated problem, but i don't know what keyword has to be searched. -
update datetime field in model form only shows plain text instead datepicker Django
I'm trying to update my DateTimeField field , but it only shows a plain text of numbers instead of the date picker class MyModel(models.Model): date= models.DateTimeField(default=timezone.now) #others forms.py class UpdateMyModelForm(forms.ModelForm): date= forms.DateTimeField(required=True,input_formats=['%Y-%m-%dT%H:%M','%Y-%m-%dT%H:M%Z'],widget=forms.DateTimeInput(attrs={'type':'datetime'})) class Meta: model = MyModel fields = ['date','others] when i use forms.DateTimeField it doesnt show the previous date which i've selected before! and when i remove forms.DateTimeField it only show a plain text type=text i also tried to use class DateInput(forms.DateInput): input_type = 'date' but it shows only show Y-m-d : year-month-day i have to display hour and minute as well ? is there something else i have to change please -
Page not found (404) likes button
I have a button in my template but it returned None to me. What's my problem HTML code <form action="{% url 'blog:like_post' post.id post.slug %}"> {% csrf_token %} <button type='submit',name = 'post_id', value = "{{post.id}}" class="btn btn_primary btn_sm">Like</button> {{ total_likes }} Likes </form> views.py @login_required def like(request, id, slug): pk = request.POST.get('post_id') print(pk) post = get_object_or_404(Post, id = pk) post.likes.add(request.user) return HttpResponseRedirect(reverse('blog:detail'),kwargs={'id': id, 'slug':slug}) @login_required def DetailPost(request, id, slug): post = Post.objects.get(id=id, slug=slug) total_likes = post.total_likes() context = { 'post' : post, 'total_likes' : total_likes, } return render(request, 'blog/PostDetail.html', context) urls.py urlpatterns = [ re_path(r'detail/(?P<id>[0-9]+)/(?P<slug>[-\w]+)/', DetailPost, name='detail'), re_path(r'like/(?P<id>[0-9]+)/(?P<slug>[-\w]+)/', like, name='like_post') ] I print pk in my terminal and it's show None for value of pk -
Django order by multiple related datetimefields - how to ignore null values
I have one model (Model1) that has multiple related to fields to another model (Model2). What I would like to do is to sort Model1 based on the datetimefields in the related fields to Model2. The issue is that the realted_x fields can be None. class Model1: related_1 = models.ForeignKey(Model2, null=True, default=None, ...) related_2 = models.ForeignKey(Model2, null=True, default=None, ...) related_3 = models.ForeignKey(Model2, null=True, default=None, ...) class Model2: .... planned_publication_datetime = models.DatetimeField(null=True, default=None, ...) I tried the following queries but the ordering is not correct due to None values in the related_x fields. Model1.objects.all().annotate( latest_publication_dt = Greatest( 'related_1__planned_publication_datetime', 'related_2__planned_publication_datetime', 'related_3__planned_publication_datetime', ) ).order_by('latest_publication_dt') The result is ordered in blocks. The first block is only the objects where related_1 is not None, the second one, where related_1 and related_2 is not None and so on. Within the blocks the ordering is correct. What I am trying to achieve is to order Model1 by the latest planned_publication_datetime of the related fields without having the "ordered blocks". -
django heroku programming error: syntax error when migrating
I'm currently pushing my django app to heroku. It successfully deployed. but when i tried to migrate using "heroku run python3 manage.py migrate --app ******", it turned an error, programming error: syntax error. here's the log/error message. Running migrations: Applying core.0001_initial...Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.SyntaxError: syntax error at or near "100000000000" LINE 1: ...Y KEY, "title" varchar(200) NULL, "story" varchar(1000000000... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/operations/models.py", line 92, in database_forwards schema_editor.create_model(model) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 345, … -
TypeError: argument must be int of float
I am getting TypeError: argument must be int of float in django template when running the server Django 2.2.23 python 3.5.2 Here is what my models, views, template looks like models.py class Items(models.Model): DRAFT = 1 APPROVED = 2 SENT = 3 STATUS = ( (DRAFT, '1'), (APPROVED, '2'), (SENT, '3'), ) client = models.ForeignKey("core.Client", null=True, blank=True,on_delete=models.CASCADE) invoice_number = models.IntegerField(blank=True, null=True) class ItemsAdded(models.Model): item_invoice = models.ForeignKey(Items,on_delete=models.CASCADE) class ProductionBill(models.Model): invoice_item = models.ForeignKey(ItemsAdded,on_delete=models.CASCADE) class Sales(models.Model): ''' Records the movements of objects in sale ''' invoice_item = models.ForeignKey(ItemsAdded, related_name='invoice_item', blank=True, null=True,on_delete=models.CASCADE) bom_item = models.OneToOneField(ProductionBill, blank=True, null=True,on_delete=models.CASCADE) status = models.CharField(max_length=20, choices=SALES_STATUS_CHOICES, default='in_stock') This is my views.py class DispatchList(View): def get(self, request): client = request.user.client sales_order = Items.objects.filter(client=client, deleted=False) sales_movements = Sales.objects.filter(status='in_stock') boms = ProductionBill.objects.filter(original_item=True,salesmovement__in=sales_movements) dispatched_items = ItemsAdded.objects.filter(productionbillofmaterials__in=boms,item_invoice__in=sales_order).order_by('-item_invoice__invoice_number') data = { 'sales_order': sales_order, 'dispatched_items': dispatched_items, 'status_options': SALES_STATUS_CHOICES, } return render(request, 'stock/transfersout/dispatch_list_detail.django.html', data) Here is my template template/dispatchlist.html {% if dispatched_items %} <div class="row"> <div class="span11"> <table class="table table-striped"> <thead> <tr> <th class="essential persist">{% trans "Sales Order" %}</th> <th class="essential persist">{% trans "Item Name" %}</th> </tr> </thead> <tbody> {% for item in dispatched_items %} <tr> <td> {{ item.item_invoice.invoice_number }} </a> </td> <td> {{ item.item.item_name }} </a> </td> </tr> {% endfor %} </tbody> </table> </div> <!--/span10--> </div> … -
integrate skrill in django project
I want to integrate Skrill in my Django project. The thing is that, I am new to PaymentGetWays and in general and I don't have enough knowledge to do it, and there is a django-skrill package which i think it doesn't support python3. Can anyone suggest a guide which is beginner friendly or at least easy to understand, so that I could integrate it? -
How can display products coming from ajax search result in django?
Problem The search feature is working and the values are retrieved from the Django views search function but now I'm not getting how to display those values in my Django project. Can anyone here can help me through this. The code is attached below. JS $('#searchsubmit').on('click', function(e){ e.preventDefault(); q = $('#search').val(); console.log(q); updateContentBySearch(q); }); function updateContentBySearch(q) { var data = {}; data['search_by'] = q // data["csrfmiddlewaretoken"] = $('#searchform [name="csrfmiddlewaretoken"]').val(); $.ajax({ url: "{% url 'main:Search' %}", data: { 'search_by': q }, success: function (data) { // do your thing } }); } VIEW def search(request): q = request.GET.get('search_by') print(q) product = Products.objects.all() cart_product_form = CartAddProductForm() transaction = transactions.objects.filter(productID__name__icontains=q,status='Enable').order_by('productID') print(transaction) return HttpResponseRedirect(reverse('main:home'),{'products':product, 'transaction': transaction , 'cart_product_form':cart_product_form}) # return redirect(request, 'main/home.html',{'products':product, 'transaction': transaction , 'cart_product_form':cart_product_form}) HTML FORM form class="d-flex col-md-6" id="searchform"> <div class="input-group mb-3" style="text-align:center"> <input name="q" type="text" class="form-control" placeholder="Search" id="search"> <button class="btn btn-primary shadow px-5 py-2" type="submit" id="searchsubmit">Search</button> </div> </form> HTML PRODUCT DISPLAY {% regroup transaction by productID as ProductList %} {% for productID in ProductList %} <div class="col-sm-3 productID" > <div class="product"> <a href="{% url 'main:product-detail' productID.grouper.id %}" class="img-prod"><img class="img-fluid" src={{productID.grouper.product_image.url}} alt="" height="200px"> <span class="status id_discount">%</span> <div class="overlay"></div> </a> <div class="text py-3 pb-4 px-3 text-center"> <h3><a href="#">{{productID.grouper}}</a></h3> <div class="d-flex text-center"> <div … -
How to change a model after creating a ModelViewset?
I am creating an API with django rest framework. But I have a problem every time I want to modify a model when I have already created an associated ModelViewset. For example, I have this model: class Machine(models.Model): name = models.CharField(_('Name'), max_length=150, unique=True) provider = models.CharField(_("provider"),max_length=150) build_date = models.DateField(_('build date')) category = models.ForeignKey("machine.CategoryMachine", related_name="machine_category", verbose_name=_('category'), on_delete=models.CASCADE ) site = models.ForeignKey( "client.Site", verbose_name=_("site"), related_name="machine_site", on_delete=models.CASCADE ) class Meta: verbose_name = _("Machine") verbose_name_plural = _("Machines") def __str__(self): return self.name def get_absolute_url(self): return reverse("Fridge_detail", kwargs={"pk": self.pk}) And this viewset: class MachineViewSet(viewsets.ModelViewSet): """ A simple ViewSet for listing or retrieving machine. """ permission_classes = [permissions.IsAuthenticated] serializer_class = MachineSerializer queryset = cache.get_or_set( 'machine_machines_list', Machine.objects.all(), 60*60*24*7 ) @swagger_auto_schema(responses={200: MachineSerializer}) def list(self, request): serializer_context = { 'request': request, } queryset = cache.get_or_set( 'machine_machines_list', Machine.objects.all(), 60*60*24*7 ) serializer = MachineSerializer(queryset, many=True, context=serializer_context) return Response(serializer.data) @swagger_auto_schema(responses={404: 'data not found', 200: MachineSerializer}) def retrieve(self, request, pk=None): serializer_context = { 'request': request, } queryset = Machine.objects.all() machine = get_object_or_404(queryset, pk=pk) serializer = MachineSerializer(machine, context=serializer_context) return Response(serializer.data) If I want to add a field to my model, like for example a description. When I run the command python manage.py makemigrations I get the error : django.db.utils.ProgrammingError: column machine_machine.description does not exist I … -
django signals can't passing sender id
I am trying to create an notification system which will be notify author if any new comment posted in his Blog post. I am trying to pass sender id through Django signals but I am getting this error: NOT NULL constraint failed: notifications_notifications.sender_id here is my code: notifications models.py class Notifications(models.Model): blog = models.ForeignKey('blog.Blog',on_delete=models.CASCADE) NOTIFICATION_TYPES = ((1,'Like'),(2,'Comment'), (3,'Follow')) sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_from_user") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_to_user") notification_type = models.IntegerField(choices=NOTIFICATION_TYPES) comment models.py class BlogComment(models.Model): blog = models.ForeignKey(Blog,on_delete=models.CASCADE,null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_comment',blank=True,null=True) def user_comment(sender, instance, *args, **kwargs): comment= instance blog = comment.blog sender = comment.user notify = Notifications(blog=blog, sender=sender, user=blog.author, notification_type=2) notify.save() post_save.connect(BlogComment.user_comment, sender=BlogComment) if I use pass author id sender = comment.blog.author as a sender then it worked. But I need to pass commenter id as comment will be sent from user not author. -
'how to solve QuerySet' object has no attribute '_meta'
iam,new to django iam getting QuerySet object has no attribute _meta error while login. [[1]: https://i.stack.imgur.com/0zuJu.png][1] [[1]: https://i.stack.imgur.com/AQtOQ.png][1] [[1]: https://i.stack.imgur.com/5OfJs.png[\]\[1\]][1] [[1]: https://i.stack.imgur.com/YnfTb.png] -
Heroku with django session (status 500)
I get status=500 when working with session. I call the following from Ajax to update session. def update_session(request): request.session['test']= request.GET.get('test') return JsonResponse({"success": True}) It works fine when running on local machine, but when deployed to Heroku it say 'Server Error (500)' Thank you. -
exporting the data to an excel sheet after being filtered on the admin panel?
so, after i filter information, is there a way I can export that filtered list as an excel sheet? I would prefer to have a button that you can click in the admin page to just export all the info as an excel sheet that is visible currently in the panel. If this is too confusing please ask more question, I would be happy to help you help me! my list filters : list_filter = ('Class','Age',) -
Unable to verify webhooks from PayPal in Python
I am trying to verify webhooks for subscriptions in paypal using django python. I am receiving the webhooks but when i send them to get verified i get this error: {'name': 'VALIDATION_ERROR', 'message': 'Invalid request - see details', 'debug_id': 'ccc873865982', 'details': [{'field': '/', 'location': 'body', 'issue': 'MALFORMED_REQUEST_JSON'}], 'links': []}. I have checked what the status code is for the response which gives a 400 response. By looking at the API Docs i see that invalid request + 400 response is either a validation error (which is to do with the Json format, so most likely a syntax error) or an authorization error (which says i need to change the scope). I think it is the validation error because the error points to the body. Here is the relevant code: header_params = { "Accept": "application/json", "Accept-Language": "en_US", } param = { "grant_type": "client_credentials", } cid = settings.PAYPAL_CLIENT_ID secret = settings.PAYPAL_CLIENT_SECRET token_i = requests.post('https://api-m.sandbox.paypal.com/v1/oauth2/token', auth=(cid, secret), headers=header_params, data=param).json() token = token_i["access_token"] bearer_token = "Bearer x".replace('x', token) headers = { "Content-Type": "application/json", "Authorization": bearer_token, } print(request.body) webhook_event = request.body.decode("utf-8") data = { "transmission_id": request.headers["PAYPAL-TRANSMISSION-ID"], "transmission_time": request.headers["PAYPAL-TRANSMISSION-TIME"], "cert_url": request.headers["PAYPAL-CERT-URL"], "auth_algo": request.headers["PAYPAL-AUTH-ALGO"], "transmission_sig": request.headers["PAYPAL-TRANSMISSION-SIG"], "webhook_id": "3AJ143072C221060T", "webhook_event": webhook_event, } print(json.dumps(data)) response = requests.post('https://api-m.sandbox.paypal.com/v1/notifications/verify-webhook-signature', headers=headers, json=json.dumps(data)).json() … -
Button to be able to display list of recipients from a specified group in Opencart
I'm trying to allow my 'Check' button to be able to display the list of customers based on the checkbox that I clicked, and display the list of customers in a table. I did all I could and researched for awhile but unable to understand on how to do so. If anyone is able to help me with this, it would be much appreciated! enter image description here -
Why it shows Unknown command: 'collectstatic', when I try to collect-static while deploying on Digital Ocean
I am trying to deploy my Django project on Digital Ocean. I created my droplet and spaces on Digital Ocean and created a static folder to store my static files. I pulled my code from my github-repo. then I installed all requirements and tried to collect static files with command python3 manage.py collectstatic but it shows Unknown command: 'collectstatic' Type 'manage.py help' for usage. what should I do here? I checked my manage.py helper but it has no command as collectstatic check, compilemessages, createcachetable, dbshell, diffsettings, dumpdata, flush, inspectdb, loaddata, makemessages, makemigrations, migrate, runserver, sendtestemail, shell, showmigrations, sqlflush, sqlmigrate, sqlsequencereset, squashmigrations, startapp, startproject, test, testserver, these are the commands in manage.py helper. And my settings.py is the following import os from pathlib import Path from decouple import config # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = config('DEBUG', default=False, cast=bool) SECRET_KEY = config("SECRET_KEY") ALLOWED_HOSTS = ["134.209.153.105",] ROOT_URLCONF = f'{config("PROJECT_NAME")}.urls' WSGI_APPLICATION = f'{config("PROJECT_NAME")}.wsgi.application' ASGI_APPLICATION = f'{config("PROJECT_NAME")}.routing.application' # =================================================================== # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'crispy_forms', 'accounts', 'adminn', 'student', 'union', 'chat', 'channels', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] AUTH_USER_MODEL = 'accounts.User' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': … -
how can i search products using ajax in django?
I'm trying to search the products using ajax in my Django project but can't get any value from the views function. can anyone help me out with this issue. The code is attached below. JS function initSearchForm(){ $('#searchsubmit').on('click', function(e){ e.preventDefault(); q = $('#search').val(); updateContentBySearch(q); }); } function updateContentBySearch(q) { var data = {}; data['search_by'] = q // data["csrfmiddlewaretoken"] = $('#searchform [name="csrfmiddlewaretoken"]').val(); $.ajax({ url: '/search-products/', data: { 'search_by': q }, dataType: 'json', success: function (data) { // do your thing } }); } HTML FORM <form class="d-flex col-md-6" id="searchform"> <div class="input-group mb-3" style="text-align:center"> <input name="q" type="text" class="form-control" placeholder="Search" id="search"> <button class="btn btn-primary shadow px-5 py-2" type="submit" id="button-addon2 searchsubmit">Search</button> </div> </form> VIEW def search(request): q = request.GET.get('search_by') print(q) product = Products.objects.all() cart_product_form = CartAddProductForm() transaction = transactions.objects.filter(productID__name__icontains=q,status='Enable').order_by('productID') print(transaction) # return HttpResponseRedirect(reverse('main/home.html'),{'products':product, 'transaction': transaction , 'cart_product_form':cart_product_form}) return redirect(request, 'main/home.html',{'products':product, 'transaction': transaction , 'cart_product_form':cart_product_form}) URL path('',views.search,name='Search'), -
What is the purpose of level in logger and handler in django setting?
I am in confusion about django logger. I can not identify difference and purpose of "level" in logger and handler. I have configured a logger- "loggers": { "django": { "handlers": ["fileerror","filewarning","fileinfo"], "level": "DEBUG", "propagate": True }, }, "handlers": { "fileerror": { "level": "ERROR", "class": "logging.FileHandler", "filename": "C:/Users/samrat/Desktop/Development/uttaran/uttaran new/org_manager/static/logs/uttaran-error.log", "formatter": "app", }, "filewarning": { "level": "WARNING", "class": "logging.FileHandler", "filename": "C:/Users/samrat/Desktop/Development/uttaran/uttaran new/org_manager/static/logs/uttaran-warning.log", "formatter": "app", }, "fileinfo": { "level": "INFO", "class": "logging.FileHandler", "filename": "C:/Users/samrat/Desktop/Development/uttaran/uttaran new/org_manager/static/logs/uttaran-info.log", "formatter": "app", }, }, I want to know the difference of level in loggers and handlers. Regards, Samrat