Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
check if exist on postgres array django
i have this zone like east west north south and i have added states in all 4 zone.every states stored in array type like this ids: {cd26ddeb-04cb-4d9a-8c7f-51d5d389f475,bc44618d-3a21-475b-8d74-c0542abb173b,18695611-256e-4506-a087-596f8914551d} what i'm trying to do is whenever i have any new state it should check on all zone if it exist then do nothing otherwise add this. Issue is i'm passing new states that need to add with previous added states. then i'm checking with all zone states if not exist then add this to new_state list and pass to data but this part not working: if state not in all_state: #its not filtering states returning all new_state.append(state) @api_view(['POST']) @login_required_message def zoneEdit(request): data = decode_data(request.data.copy()) new_state = [] try: try: zone_queryset = Zone.objects.get(uid=data['uid']) all_state = Zone.objects.values_list('state',flat=True) print(all_state, "all_state") data["created_by"] = request.user.uid for state in data['state']: if state not in all_state: #its not filtering states returning all new_state.append(state) print(new_state, "to be added") zone_serializer_obj = ZoneSerializer(zone_queryset, data=new_state) if zone_serializer_obj.is_valid(): try: city_save = zone_serializer_obj.save() return CustomeResponse(request=request, comment=ZONE_NAME_UPDATE, data=json.dumps(zone_serializer_obj.data, cls=UUIDEncoder), status=status.HTTP_200_OK, message=ZONE_NAME_UPDATE) except Exception as e: return CustomeResponse(request=request, log_data=json.dumps(str(e), cls=UUIDEncoder), message=SOMETHING_WENT_WRONG+" mv54 "+str(e), data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) else: return CustomeResponse(request=request, comment=FIELDS_NOT_VALID, data=json.dumps(zone_serializer_obj.errors, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) else: return CustomeResponse(request=request, comment=FIELDS_NOT_VALID, data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) except City.DoesNotExist: return CustomeResponse(request=request, … -
Django template progress bar upload to AWS s3
I have a form where the user can upload multiple files and I am using jquery ajax to submit the files and other fields in the form. when uploading large files.. the site looks unresponsive so I wanted to add a progress bar. so inside the xhr parameter, I wrote... xhr: function () { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener('progress', function (e){ if (e.lengthComputable) { console.log('Bytes Loaded: '+e.loaded) console.log('Total Size: '+e.total) console.log('Percentage Uploaded: '+(e.loaded/e.total)) } }); return xhr; } but this does not work properly because almost instantly the percentage uploaded shows 1 i.e. 100% while the actual file takes its own time to upload and after that, the success message is shown. What am I doing wrong? -
AWS Lightsail 'Exception occurred processing WSGI script'
I followed the amazon tutorial EXACTLY for deploying a Django app on lightsail: Deploy Django-based application onto Amazon Lightsail. But when I visit my IP address (http://52.41.70.195/) I get Internal server error. When I check the apache error logs I see these errors: Failed to parse Python script file '/opt/bitnami/projects/Django-E -Commerce/perfectcushion/wsgi.py'. Exception occurred processing WSGI script '/opt/bitnami/projects/Django-E-Commerce/perfectcushion/wsgi.py'. My wsgi.py file looks like the one amazon provides: import os import sys sys.path.append('/opt/bitnami/projects/Django-E-Commerce’) os.environ.setdefault("PYTHON_EGG_CACHE", "/opt/bitnami/projects/Django-E-Commerce/egg_cache") os.environ.setdefault("DJANGO_SETTINGS_MODULE", “Django-E-Commerce.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Any suggestions? -
Cannot publish Django Rest API on heroku
I'm trying to publish my Django rest framework application to Heroku. I'm following all the procedures accordingly to publish from Github repository but don't know where is my mistake. In Heroku deploy tab it says deployed successfully but while i go to visit the page it show the following error. My folder structure is as follows where my API is in api folder and the project is in config folder: I've specified the file name in Heroku procfile as follows (adding asgi file since my project is using asgi instade of wsgi for Django channels): web: gunicorn config.asgi --log-file - When I check the error from the terminal it cannot find module config but also show build success. The error is as follows: 2021-01-14T07:10:10.612461+00:00 heroku[web.1]: State changed from crashed to starting 2021-01-14T07:10:25.885018+00:00 heroku[web.1]: Starting process with command `gunicorn config.asgi --log-file -` 2021-01-14T07:10:30.278347+00:00 app[web.1]: [2021-01-14 07:10:30 +0000] [4] [INFO] Starting gunicorn 20.0.4 2021-01-14T07:10:30.279496+00:00 app[web.1]: [2021-01-14 07:10:30 +0000] [4] [INFO] Listening at: http://0.0.0.0:36267 (4) 2021-01-14T07:10:30.279664+00:00 app[web.1]: [2021-01-14 07:10:30 +0000] [4] [INFO] Using worker: sync 2021-01-14T07:10:30.296521+00:00 app[web.1]: [2021-01-14 07:10:30 +0000] [9] [INFO] Booting worker with pid: 9 2021-01-14T07:10:30.305338+00:00 heroku[web.1]: State changed from starting to up 2021-01-14T07:10:30.310836+00:00 app[web.1]: [2021-01-14 07:10:30 +0000] [9] [ERROR] Exception … -
How do I add Pagination to a table (Django)
I am trying to add pagination to one of the tables for my project, but I can't find any good resources to refer to, all of the docs use some kind of URL query, but I don't want to do that, since it is on the user page. Background --- I am making a mock website for trading for a project and I need the user to be able to see their trade history, and as you can imagine, after any more than 10, the page starts to look very long, so I am trying to find a way to make the table have pages, but I just can't figure it out. Aim -- To add pages to a bootstrap table. The table should be able to go back and forth using buttons. My "solution" - after going through stuff for about an hour, I found this but I don't know if it is good/safe. Code : VIEW - def userPage(request): user = request.user user_info = user.info trades = user_info.trade_set.all().order_by('-time_bought_at') ###I want this queryset to be paginated total_trades = trades.count() balance = round(user_info.balance) context = { "user" : user, "user_info" : user_info, "trades" : trades, "total_trades" : total_trades, "balance" : … -
python django database information to html template
i am trying to fetch information from a psql database and i would like to export it to a html template, however i get a list, not an object or dict, so i can not call the properties of the information in the tempalte def myview(request): conn = psycopg2.connect(user="bogarr",password="Testing321",host="localhost",port="5432",database="LoginDatabase") try: cursor = conn.cursor() cursor.execute("select * from blog_post") rows = cursor.fetchall() finally: conn.close() context = { 'rows': rows } for row in rows: print("kecske: ", row[1]) return render(request,"blog/mytemplate.html", context) -
Django: Passing 'name' to Client.post()
I want to pass 'name' variable to request.POST.get() from Client in test in Django to be further processed by post function in view. Something like that(product is ChoiceField in form): response = c.post('/ordersys/orders/create/', {'product':product, 'amount':3}, name="Add") I want that if to be True when posting from Client: if request.POST.get("Add"): self.add_to_order(product, amount) In form, submit like that works: <input type="submit" name="Add" value="Add item to order"> -
Chart.js not working after Django deployment on Heroku
My Django site was working fine at localhost:8000 but when I uploaded to Heroku, the charts no longer show up. Is there any typical reason why this would be? The errors I received in the console were Uncaught Error: Chart.js - Moment.js could not be found! You must include it before Chart.js to use the time scale. Download at https://momentjs.com and The page at 'https://...com/' was loaded over HTTPS, but requested an insecure script 'http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js'. This request has been blocked; the content must be served over HTTPS. -
how do i debug or add a relation
The above exception (relation "blog_blog" does not exist LINE 1: INSERT INTO "blog_blog" ("title", "pub_date", "body", "image... ^ ) was the direct cause of the following exception: /usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py, line 47, in inner response = get_response(request) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/core/handlers/base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/contrib/admin/options.py, line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/utils/decorators.py, line 130, in _wrapped_view response = view_func(request, *args, **kwargs) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/views/decorators/cache.py, line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/contrib/admin/sites.py, line 233, in inner return view(request, *args, **kwargs) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/contrib/admin/options.py, line 1653, in add_view return self.changeform_view(request, None, form_url, extra_context) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/utils/decorators.py, line 43, in _wrapper return bound_method(*args, **kwargs) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/utils/decorators.py, line 130, in _wrapped_view response = view_func(request, *args, **kwargs) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/contrib/admin/options.py, line 1534, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/contrib/admin/options.py, line 1580, in _changeform_view self.save_model(request, new_object, form, not add) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/contrib/admin/options.py, line 1093, in save_model obj.save() … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/db/models/base.py, line 753, in save self.save_base(using=using, force_insert=force_insert, … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/db/models/base.py, line 790, in save_base … -
success url does not work in my class based DeleteView
My success_url for my class based delete view does not work for some reason. in views.py # allows a user to delete a project class DeletePost(DeleteView): template_name = 'user_posts/post_delete.html' model = Post # return to the all posts list success_url = reverse_lazy('posts_list') # make sure the user is looking at its own post def dispatch(self, request, *args, **kwargs): obj = self.get_object() if not obj.user == self.request.user: raise Http404("You are not allowed to Delete this Post") return super(DeletePost, self).dispatch(request, *args, **kwargs) in urls.py: path('list/', PostsListView.as_view(), name="posts_list"), path('create-post/', CreatePostView.as_view(), name="post_create"), path('update-post/<int:pk>', UpdatePost.as_view(), name="post_update" ), path('delete-post/<int:pk>', DeletePost.as_view(), name="post_delete") in the HTML file: {% extends 'base.html' %} {% block content %} <form action="." method="POST" style="width:80%;"> {% csrf_token %} <h3>Do You want to delete this post: "{{ object.title }}"</h3> <input class="btn btn-primary" type="submit" value="Confirm"/> <a href="{% url 'posts_list' %}">Cancel</a> </form> {% endblock content %} whenever I click ok to delete a specific project, it doesn't return to the list of posts for: image of the error on the webpage -
TypeError at /api/register/ 'module' object is not callable
I am trying to register users using django rest framework but this is the error i am getting, Please help Identify the issue TypeError at /api/register/ 'module' object is not callable Request Method: POST Request URL: http://127.0.0.1:8000/api/register/ Django Version: 3.1.5 Exception Type: TypeError Exception Value: 'module' object is not callable Exception Location: C:\Users\ben\PycharmProjects\buddyroo\lib\site-packages\rest_framework\generics.py, line 110, in get_serializer Python Executable: C:\Users\ben\PycharmProjects\buddyroo\Scripts\python.exe Python Version: 3.8.5 below is RegisterSerializer from django.contrib.auth.password_validation import validate_password from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.validators import UniqueValidator class RegisterSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) password = serializers.CharField(write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) class Meta: model = User fields = ('username', 'password', 'password2', 'email', 'first_name', 'last_name') extra_kwargs = { 'first_name': {'required': True}, 'last_name': {'required': True} } def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError({"password": "Password fields didn't match."}) return attrs def create(self, validated_data): user = User.objects.create( username=validated_data['username'], email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name'] ) user.set_password(validated_data['password']) user.save() return user and RegisterView.py from django.contrib.auth.models import User from rest_framework import generics from rest_framework.permissions import IsAuthenticated, AllowAny # <-- Here from rest_framework.response import Response from rest_framework.views import APIView from api import UsersSerializer, RegisterSerializer class RegisterView(generics.CreateAPIView): queryset = User.objects.all() serializer_class = RegisterSerializer permission_classes = (AllowAny,) -
how to write serializer and view for this type output data format and save in database drf,mysql
{ "user_name": "admin", "raw_data_column": [ "UPC Code", "Label or Sublabel", "Server Wise" ] } -
password_reset does not pick from_email
I have my email setup for entire django project and it works fine. When it comes to reset password in the following url: http://127.0.0.1:8000/rest-auth/password_reset/ and after submitting the email, it throws: SMTPDataError at /rest-auth/password_reset/ (550, b'The from address does not match a verified Sender Identity. Mail cannot be sent until this error is resolved. when I digged into the issue I noticed that this view doesn't catch from_email at all: If I manually enter the email here, everything works fine. I am wondering what is gone wrong that email is not read! -
Django IOT project
I am working in a Django project building a web application with a few features one of them is showing data from sensor connected to ESP8266 on a page on the project how can I POST these data showing on arduino to the project to use them in an app? (project includes creating users with API token if it's important) -
Django form does'nt render even if the code seems alright
I am beginner to Django. I have just started learning basic forms and here is the code which does'nt work. The method specified for the form in form_page.html is POST, so accordingly in views.py it must render me form_page.html but instead it prints thanks which means it does'nt recognize the method as post and run the else code snippet.Can you help me fix it!! Views.py from django.shortcuts import render from django.http import HttpResponse from .forms import formname def index(request): return render(request,'index.html') def form_name_view(request): if request.method == 'POST': form=formname(request.POST) if form.is_valid: print('NAME:',form.cleaned_data['name']) print('email:',form.cleaned_data['email']) print('text:',form.cleaned_data['text']) return render(request,'form_page.html',{'form':form}) else: form=formname() return HttpResponse('thanks') form_page.html <!doctype html> <html lang='en'> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <title> Basic forms </title> <head> <body> <h1>Fill out the form</h1> <div class="container"> <form method="POST"> {{form.as_p}} {% csrf_token %} <btn type="submit" class="btn btn-primary ">Submit</btn> </form> </div> </body> </html> forms.py from django import forms from django.core import validators class formname(forms.Form): name=forms.CharField() email=forms.EmailField() text=forms.CharField(widget=forms.Textarea) urls.py from django.contrib import admin from django.urls import path from basicformsapp import views from django.conf.urls import url urlpatterns = [ url(r'^$',views.index,name='index'), path('admin/', admin.site.urls), url(r'^formpage/',views.form_name_view,name='form_name_view') ] -
How can I bundle my JSON API data into one dictionary?
I'm trying to package my API data into one GET request simply using standard libraries python. class GetData(APIView): def get(self, request, *args, **kwargs): urls = [url_1, url_2, url_3, url_4 ] data_bundle = [] for x in urls: response = requests.get(x, headers={'Content-Type': 'application/json'}).json() data_bundle.append(response) return Response(data_bundle, status=status.HTTP_200_OK) The return response has to be JSON data, I'm trying to get it to work but it seems like the response data seems to be overiding eachother? How can I properly create a JSON dictionary of dictionaries. I've tried switching data_bundle to an empty dictionary instead of a list. However that just caused an error saying: ValueError: dictionary update sequence element #0 has length 8; 2 is required Is there a simple way to accomplish this that I'm missing? Thank you for the help. -
Django. How to design model so not to have vertical repetition for common name and family name?
In the below model there are fields like name and family name that will be repeated. For example Jhon or Jack would be common name which are bound to repeat themselves. Is there any better way to avoid this or this is ok by normalization standards of data models designs? class PropertyOwner(models.Model): name = models.CharField(max_length=200) family_name = models.CharField(max_length=200) contact_number = models.PositiveIntegerField() email = models.EmailField() def __str__(self): return self.name Is the fact that some names and family names will repeat themselves be a problem or better way to do this? -
'NoneType' object has no attribute 'id' in Django
I get the 'NoneType' object has no attribute 'id' error when opening a URL which view is this one: @login_required def order_checkout_view(request): product_id = request.session.get("product_id") or None if product_id == None: return redirect("/") product = None try: product = Product.objects.get(id=product_id) except: return redirect("/") user = request.user order_id = request.session.get("order_id") order_obj = None new_creation = False try: order_obj = Order.objects.get(id=order_id) except: order_id = None if order_id == None: new_creation = True order_obj = Order.objects.create(product=product, user=user) if order_obj != None and new_creation == False: if order_obj.product.id != product.id: order_obj = Order.objects.create(product=product, user=user) request.session['order_id'] = order_obj.id form = OrderForm(request.POST or None, product=product, instance=order_obj) if form.is_valid(): order_obj.shipping_address = form.cleaned_data.get("shipping_address") order_obj.billing_address = form.cleaned_data.get("billing_address") order_obj.mark_paid(save=False) order_obj.save() del request.session['order_id'] return redirect("/success") return render(request, 'orders/checkout.html', {"form": form, "object": order_obj}) The exception location is in this line if order_obj.product.id != product.id: There's an existing product in the database, however does this mean in this case the Product is 'None'? What could be the problem here? -
Flatpickr datetime field showing the wrong date in Edit form
I am working on an EDIT form to amend a specific record from a PGSQL table. The widget works well to select and save date, but when the EDIT page loads, the Start date of the record is incorrect. Below i call the actual date as it is saved in PG and the same exercise using the FlatPicker widget <label>Start Date</label> <div> {{ restricted_name_obj.Restriction_Start_Date }} <input type="hidden" name="Restriction_Start_Date" required="" id="Restriction_Start_Date" fp_config="{&quot;value&quot;: &quot;{{ restricted_name_obj.Restriction_Start_Date }}&quot;, &quot;id&quot;: &quot;fp_14&quot;, &quot;picker_type&quot;: &quot;DATETIME&quot;, &quot;linked_to&quot;: &quot;fp_13&quot;, &quot;options&quot;: {&quot;value&quot;: &quot;{{ restricted_name_obj.Restriction_Start_Date }}&quot;,&quot;mode&quot;: &quot;single&quot;, &quot;dateFormat&quot;: &quot;Y-m-d H:i:S&quot;, &quot;altInput&quot;: true, &quot;enableTime&quot;: true}}" class="flatpickr-input" value="{{ restricted_name_obj.Restriction_End_Date }}"> </div> But for some reason, the year is correct (always but day, month and hours/minutes are incorrect. I suspect there might be a formating to do while passing data to the field, but how ? Here is how it looks : -
wy in DB table is not creating and showing this errors invalid foreignKey in Django
wy in DB table is not creating and showing this errors invalid foreignKey .IntegrityError: The row in table 'myecomapp_toplist' with primary key '2' has an invalid foreign key: myecomapp_toplist.subcategory_id contains a value '1' that does not have a corresponding value in myecomapp_subcategory.id. models.py class TopList(models.Model): image = models.ImageField(upload_to='ProductImg') title = models.TextField(max_length=500) discountpercentage = models.IntegerField(blank=True,null=True) discountPrice = models.IntegerField(blank=True,null=True) brandName = models.TextField(max_length = 100 , default='',null=True,blank=True) desc = models.TextField(max_length=5000 ,null=True,blank=True) finalprice = models.IntegerField(blank=True,null=True) category = models.ForeignKey(ProductCategory , on_delete=models.CASCADE , default=1) subcategory = models.ForeignKey(subcategory , on_delete=models.CASCADE , default=1) class ProductCategory(models.Model): name = models.CharField(max_length=20) @staticmethod def get_all_categories(): return ProductCategory.objects.all() def __str__(self): representtion of this model object return self.name class subcategory(models.Model): name = models.CharField(max_length=20) MainCategory = models.ForeignKey(ProductCategory , on_delete=models.PROTECT) def __str__(self): return self.name admin.py @admin.register(subcategory) class SubcategoryAdmin(admin.ModelAdmin): list_display = ['name'] @admin.register(FirstSliderData) class FirstsliderModelAdmin(admin.ModelAdmin): list_display=['id','image','title' ,'category'] @admin.register(TopList) class TodoListModelAdmin(admin.ModelAdmin): list_display=['id','image','title' ,'category'] -
Django: values_list(flat=True) but for multiple fields
I have a model, TestModel As far as I know, if I were to implement TestModel.objects.values_list('FieldA', flat=True) This results in [A,B,C,(...)] (a list) And doing this TestModel.objects.values_list('FieldA','FieldB') results in [(A,1),(B,2),(C,3),(...)] (a list of querysets) But is it possible to get a similar result to Flat=True but for multiple fields? So, if I were to use something like testQS = TestModel.objects.values_list('FieldA','FieldB') and call testQS['FieldA'], this will return [A,B,C,(...)] Likewise, calling testQS['FieldB'] will return [1,2,3,(...)] Basically, I want to get all the data from a certain field in a values_list with multiple fields without resorting to for loop or creating values_list multiple times for each field. -
Cannot see my object models in Django admin view
I'm a relative Noobie at Django and have an issue with the admin interface. I am not able to see any of my custom object models, but I can see only the 'Groups' (under Authentication & Authorization), and 'Users' objects (under my 'CrushIt' app) (based on 'abstractuser') I used the startproject script to create my project (wedgeit) and app (CrushIt), and have gone through all the tips in the Django admin documentation, to try to troubleshoot the issue (see below). I also went through all the queries from other users I could find, but I'm still stuck. P.S. I can see my models from the shell and can create instances also, but they don't appear in the admin interface. Any hints would be appreciated. First time posting here so apologies if I've done something very stupid :D > Generated by 'django-admin startproject' using Django 3.0.8. Project settings file settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'CrushIt.apps.CrushItConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'wedgeit.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] apps.py … -
python-logstash and python-logstash-async not working with django
I tried two libraries to send some logs from our Django backend to our logging server: python-logstash python-logstash-async Here are the things I also tried/verified: Verify the Ec2 security group is accepting on port tcp/5000 (logstash) Monitor traffic from local machine and logging server to verify any network traffic. Using nc I was able to verify test logs being send and receive to our logging server. Re-create a bare minimum django project to see if there is an issue from versioning I'm sending logs after running the manage.py runserver class AppConfig(AppConfig): name = 'app' def ready(self): logger.info('info local django logging ') logger.error('debug local django logging ') logger.debug('debug local django logging ') print('logging init') This are the similar links that I've already checked: python-logstash not working? How to use python-logstash on Django settings.py (python-logstash-async) LOGGING = { 'formatters': { 'logstash': { '()': 'logstash_async.formatter.DjangoLogstashFormatter', 'message_type': 'python-logstash', 'fqdn': False, # Fully qualified domain name. Default value: false. 'extra_prefix': 'dev', # 'extra': { 'environment': 'local' } }, }, 'handlers': { 'logstash': { 'level': 'DEBUG', 'class': 'logstash_async.handler.AsynchronousLogstashHandler', 'transport': 'logstash_async.transport.TcpTransport', 'host': 'my.remote.host', 'port': 5000, 'ssl_enable': False, 'ssl_verify': False, 'database_path': 'memory', }, }, 'loggers': { 'django.request': { 'handlers': ['logstash'], 'level': 'DEBUG', 'propagate': True, }, }, } Logstash … -
Change file name upload image in Django
Im having a trouble on how can I rename my image file to prevent duplication of filename. Currently I have a list of photos which can upload the filename to the database and it will automatically create folder and save those selected photos to my media folder. All I want is every image filename must be unique. It would be great if anybody could figure out where I am doing something wrong. thank you so much in advance views.py @login_required(login_url='log_permission') def scanned_docs_add(request): if request.method == 'POST': gallery = folder_info.objects.create( title = request.POST.get('title'), date_upload = datetime.date.today() ) for file in request.FILES.getlist('photos[]'): #imagefile-------- oas = gallery_photos.objects.create( gallery_info_id = gallery.id, photos = file, ) return JsonResponse({'data': 'success'}) models.py class folder_info(models.Model): title = models.CharField(max_length=50,blank=True, null=True) date_upload = models.DateField(null=True, blank=True) class Meta: db_table = "folder_info" class gallery_photos(models.Model): gallery_info_id = models.IntegerField() photos = models.FileField(upload_to='Photos/', unique=True) class Meta: managed = False db_table = 'gallery_photos' html <form id="uploadevent" > {% csrf_token %} <input type="file" multiple data-bind="fileInput: multiFileData, customFileInput: { }" accept="image/*" name="photos[]" required=""> <button type="submit" class="btn btn-outline-primary">Save changes</button> </form> Script <script type="text/javascript"> $('#uploadevent').on('submit', function(e){ $.ajax({ data : new FormData(this), url : "{% url 'scanned_docs_add' %}", type : 'POST', cache : false, contentType : false, processData : false }) … -
Django error 'WSGIRequest' object has no attribute 'request'
i made function of delete a student, it works but messages.info(self.request, student.name + ' blah blah blah ', extra_tags='danger') in views.py makes an error, error is 'WSGIRequest' object has no attribute 'request' Thank you guys and Happy new year ! my views.py class StudentUpdate(UpdateView): model = Student template_name = 'student/list_edit.html' context_object_name = 'student' form_class = AddStudent def form_valid(self, form): student = form.save(commit=False) student.save() return super().form_valid(form) . . . . . def delete_student(self, pk, school_year): student = get_object_or_404(Student, school_year=school_year, pk=pk) messages.info(self.request, student.name + ' blah blah blah ', extra_tags='danger') student.delete() return reverse('student_detail', kwargs={'pk':pk,'school_year':school_year}) my html function deleteconfirm(){ $('.delete-message').dialog({ dialogClass:"confirm-modal", modal: true, buttons: { "delete": function() { $(location).attr("href"," {% url 'delete_student' student.school_year student.pk %} "); }, "cancel": function() { $(this).dialog('close'); }, }, . . . . my urls.py urlpatterns = [ . . . . . path('student/<school_year>/<pk>/delete/', views.StudentUpdate.delete_student, name='delete_student'), ]