Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
drf-spectacular define request content type as 'application/x-www-form-urlencoded'
In drf-spectacular swagger, post method have 3 content types as below application/json application/x-www-form-urlencoded multipart/form-data Is there anyway to make "application/x-www-form-urlencoded" as default content type for my post method. @extend_schema( description='API authentication using login & password', # OpenApiRequestBody('content': "application/x-www-form-urlencoded") ) In extend_schema function, tried to add content type as form-urlencoded. but no luck. Thanks in advance -
How to fetch data by foreign key in Django serializers?
I'm stuck on fetching data with a related foreign key. I am doing some kind of validation in which the create method would be allowed depending on the requesterid to be POSTed. This is my userTable model: class userTable(models.Model): userid = models.UUIDField(primary_key=True, default = uuid.uuid4, editable=False) username = models.CharField(max_length=50, null=False, unique=True) userroleid = models.ForeignKey(roleTable, on_delete=models.CASCADE) def __str__(self): return self.username Another model is the requestTable class requestTable(models.Model): rid = models.AutoField(primary_key=True) requesterid = models.ForeignKey(userTable, on_delete=models.CASCADE) (...) This is my serializer: class RequestCreateSerializer(serializers.ModelSerializer): parts=PartSerializer(many=True) class Meta: model = requestTable fields = ['rid','requesterid', (...)] def create(self, instance, validated_data): if instance.requesterid.userroleid == 3: #how can i fetch my `requesterid` data? parts_data = validated_data.pop('parts') request = requestTable.objects.create(**validated_data) for part_data in parts_data: partsTable.objects.create(request=request, **part_data) return request raise ValidationError("Sorry! Your role has no permission to create a request.") Also, I'm quite confused if I should do validation in serializers, or views. If I do it in views, it just throws the ValidationError, and it doesn't seem to enter the if condition. For reference, here's my views: class RequestListCreateView(ListCreateAPIView): queryset = requestTable.objects.all() serializer_class = RequestCreateSerializer def create(self, request, *args, **kwargs): if request.data.get('requesterid__userroleid') == '3': write_serializer = RequestCreateSerializer(data=request.data) write_serializer.is_valid(raise_exception=True) self.perform_create(write_serializer) headers = self.get_success_headers(write_serializer.data) return Response({"Request ID": write_serializer.instance.requestid, "Parts ID": [p.partsid … -
400 Bad Request error in response to PUT/POST request
My project is to create a twitter style web application. I'm trying to implement a feature whereby a user can edit the content of their posts. Whenever I click 'save' to edit the post I receive: This is the context of my fetch request: const edit_div = document.createElement('div'); edit_div.innerHTML = `<p id="edit" style="color: blue;">Edit</p>`; edit_div.querySelector('#edit').addEventListener('click', () => { post_div.querySelector('#content').innerHTML = ` <textarea id="edited">${post.content}</textarea> `; edit_div.innerHTML = `<button id="change_post">Create change</button>`; edit_div.querySelector('#change_post').addEventListener('click', () => { const new_content = post_div.querySelector('#edited').value; fetch(`/posts/${post.id}`, { method: 'PUT', body: JSON.stringify({ content: new_content }) }) This is my URL in urls.py file path("posts/<int:post_id>", views.post, name="edit_post"), This is what I've created in views.py @csrf_exempt @login_required def post(request, post_id): edited_post = Post.objects.get(id=post_id) return JsonResponse(edited_post) Using POST instead of PUT gets me the same result. I have tried to clear browser cookies and and clear browser cache but to no avail. I have made very similar fetch calls but none of them had this issue. What have I got wrong? -
Not recognizing the user after I receive a request from React
After I send data in json I want to save the data, all the data is received fine, but it does not recognize the user, even though it is indeed connected according to the tests I did. i am getting this error: ValueError: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x106fd12d0>>": "Vendors.user" must be a "User" instance. but the user is log in. view.py: @csrf_exempt def store_register(request): if request.method == 'POST': form = json.loads(request.body) print(request.user,form) vendor = Vendors.objects.create(user=request.user,store_name=form['storeName'],company_name=form['companyName'],img=form['storeImage'],business_email=form['businessEmail'],pay_pal=form['payPalEmail']) vendor.save() return JsonResponse({'test':'test'}) react: class RegisterBody extends React.Component { constructor (props) { super (props); this.state = { url: '' } } SendInput = () => { const storeName = document.getElementById('storeName').value const companyName = document.getElementById('companyName').value const storeImage = document.getElementById('storeImage').value const businessEmail = document.getElementById('businessEmail').value const payPalEmail = document.getElementById('payPalEmail').value this.setState({storeName:storeName,companyName:companyName,storeImage:storeImage,businessEmail:businessEmail,payPalEmail:payPalEmail}) fetch('/store-register', { method: 'POST', body: JSON.stringify({ 'storeName':storeName, 'companyName':companyName, 'storeImage':storeImage, 'businessEmail':businessEmail, 'payPalEmail':payPalEmail }), headers: { 'Content-type': 'application/json; charset=UTF-8' }, }) } render () { return ( <div> <label>Store Name</label> <input type={"text"} name={"storeName"} id={"storeName"}></input> <br></br> <label>Company Name</label> <input type={"text"} name={"companyName"} id={"companyName"}></input> <br></br> <label>Store Image</label> <input type={"file"} name={"storeImage"} id={"storeImage"}></input> <br></br> <label>Business Email</label> <input type={"email"} name={"businessEmail"} id={"businessEmail"}></input> <br></br> <label>Paypal Email</label> <input type={"email"} name={"payPalEmail"} id={"payPalEmail"}></input> <br></br> <button onClick={() => this.SendInput()}>Register</button> </div> ) } } export default RegisterBody -
How to generate a (html) file from a view in Django
I have a Django-driven website with several applications which are dynamically updated, but not too often, like "About", "Our services", etc. They have a two-level structure of pages, which I want to reflect in the top pop-up menu (see the picture). I could make it as a custom simple_tag called each time from the base.html template. It would generate a menu each time a user opens or reloads a page, but think it is very costly since the app structure is changed seldom (say, once a year). Instead, I want to like to generate an HTML code of the menu each time the app structure is updated. It will be stored as a statical HTML file, so my base.html will include the menu as a ready piece of code. Are there recipes on how to generate an HTML file from the views (CreateView, UpdateView, DeleteView)? -
read csv file from user input in django
ERROR : FileNotFoundError: [Errno 2] No such file or directory: '/media/tableConvert.com_v02pvt.csv' Hello there im trying to read a csv file in django backend where user upload and i dont want to save it to my DB so my best try was this : View : def view_submit_form(request): if request.method == 'POST': text = request.POST.get('smstext') csv_file = request.FILES['csv_file'] file_name = default_storage.save(csv_file.name, csv_file) file_url = default_storage.url(file_name) df = pd.read_csv(r'{}'.format(file_url)) return render(request, 'SubmitForm/form.html',) -
Django site fails with "bytes-like object is required, not 'str'"
I have a django site which I can login fine. However when I click one of the links "Scripts" it fails with the error builtins.TypeError TypeError: a bytes-like object is required, not 'str' . There were no recent changes on this site. Its using python36. The only thing I can think of its not liking the data its pulling from sql server but I cant pin point to it. Also as soon as I get the error, it crashes python manage.py runserver so I have to start it again. File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__ return self.application(environ, start_response) File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 157, in __call__ response = self.get_response(request) File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in get_response response = self._middleware_chain(request) File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 43, in inner response = response_for_exception(request, exc) File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 93, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 139, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/werkzeug_debugger_runserver/management/commands/runserver.py", line 69, in null_technical_500_response six.reraise(exc_type, exc_value, tb) File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/six.py", line 686, in reraise raise value File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/django/utils/deprecation.py", line 140, in __call__ response = self.get_response(request) File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 43, in inner response = response_for_exception(request, exc) File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 93, in response_for_exception response = handle_uncaught_exception(request, … -
Django celery ModuleNotFoundError: No module named 'config'
I am doing a docker django project with celery in which the project's name for main container is main_config. the main_ms\main_config\celery.py looks like import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') includedTasks=[] CeleryApp = Celery ('main_config', broker=settings.CELERY_BROKER_URL, backend=settings.CELERY_RESULT_BACKEND,include=includedTasks) CeleryApp.config_from_object('django.conf:settings', namespace='CELERY') CeleryApp.autodiscover_tasks() in docker-compose this containers is like: main_django_ser: container_name: main_django_container build: context: ./main_ms dockerfile: Dockerfile.main command: sh -c " celery -A main_config.celery worker --loglevel=info && python manage.py runserver 0.0.0.0:8000" by starting docker-compose gave the error below: main_django_container | Usage: celery [OPTIONS] COMMAND [ARGS]... main_django_container | Try 'celery --help' for help. main_django_container | main_django_container | Error: Invalid value for '-A' / '--app': main_django_container | Unable to load celery application. main_django_container | While trying to load the module main_config.celery the following error occurred: main_django_container | Traceback (most recent call last): main_django_container | File "/usr/local/lib/python3.9/site-packages/celery/bin/celery.py", line 57, in convertmain_django_container | return find_app(value) main_django_container | File "/usr/local/lib/python3.9/site-packages/celery/app/utils.py", line 384, in find_app main_django_container | sym = symbol_by_name(app, imp=imp) main_django_container | File "/usr/local/lib/python3.9/site-packages/kombu/utils/imports.py", line 56, in symbol_by_name main_django_container | module = imp(module_name, package=package, **kwargs) main_django_container | File "/usr/local/lib/python3.9/site-packages/celery/utils/imports.py", line 105, in import_from_cwd main_django_container | return imp(module, package=package) main_django_container | File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module main_django_container | return _bootstrap._gcd_import(name[level:], package, level) main_django_container … -
how to add playwright docker image to docker compose?
I am building Django app where I want to run Django and playwright images in 1 container in Docker Desktop (locally). Below you can see my docker-compose.yml file: version: '3.8' services: web: build: ./docker_playwright_test command: python manage.py runserver 0.0.0.0:8000 volumes: - ./docker_playwright_test/:/usr/src/docker_playwright_test/ ports: - 8000:8000 Django is running fine on my localhost but I am not sure how to add Playwright image to docker-compose file? Any help or tip will be appreciated. -
Django migration failed due to lack of memory. Query can't be killed
I deleted a column in a large table from a django migration. Due to lack of memory, the migration failed and the database restarted. (Managed database digital ocean mysql v8) After the database restarts, the drop column query runs again, and every time I kill the query through tableplus (mysql), the query restarts again. Meaning that my database runs out of memory every 15 minutes (I was in the process of deleting unnecessary data to free up memory) and restarts again. How can I kill this query for good? -
Django rest framework : custom object permissions doesn't work
My problem is very simple : I'm trying to create some custom permissions for my django rest API. This is my code (permission.py) : class UserPermissions(permissions.BasePermission): def has_object_permission(self, request, view, obj): return obj == request.user I just want that the users can only get, delete and update their own account. The problem is that I think my code is not read by Django. I have try to always return false (without any condition) and it does nothing. I have also try to print some debug message at the beginning of the file and it's does nothing. (My file permissions.py is at the root of my application) -
ImportError: cannot import name 'ParamSpec' from 'typing_extensions' when using Django websockets with channels and twisted libraries
We did not update any lib or new lib added. During deployment of Django web application, got the following error: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/celery/fixups/django.py", line 118, in django_setup django.setup() File "/usr/local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.7/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/usr/local/lib/python3.7/site-packages/channels/apps.py", line 4, in <module> import daphne.server File "/usr/local/lib/python3.7/site-packages/daphne/server.py", line 5, in <module> from twisted.internet import asyncioreactor # isort:skip File "/usr/local/lib/python3.7/site-packages/twisted/internet/asyncioreactor.py", line 19, in <module> from twisted.internet.posixbase import ( File "/usr/local/lib/python3.7/site-packages/twisted/internet/posixbase.py", line 16, in <module> from twisted.internet import error, tcp, udp File "/usr/local/lib/python3.7/site-packages/twisted/internet/tcp.py", line 99, in <module> from twisted.internet import abstract, address, base, error, fdesc, main File "/usr/local/lib/python3.7/site-packages/twisted/internet/base.py", line 34, in <module> from twisted.internet import abstract, defer, error, fdesc, main, threads File "/usr/local/lib/python3.7/site-packages/twisted/internet/defer.py", line 42, in <module> from typing_extensions import Literal, ParamSpec, Protocol ImportError: cannot import name 'ParamSpec' from 'typing_extensions' … -
Django rest framework send form data
I have to build a form page with multiple image uploads using CRUD functions that I made. On submit the page should not reload so I'm using ajax to make the request. The serializer keeps throwing an error 400 (Bad request). It might be that FormData stringify some values that shouldn't, bud serializer won't let me add an item. Please help, I'm second day on googling different aproaches to do it and none of them worked. views.py @api_view(['GET']) def index(request): imageform = ImageForm() form = CreateShopItemForm() return render(request, 'main/index.html', {"form": form, "imageform": imageform}) @api_view(['POST']) def create_item(request): shop_item = ShopItemSerializer(data=request.data) print(request.data) if shop_item.is_valid(raise_exception=True): shop_item.save() print('success') return Response(shop_item.data) else: print("invalid") return Response(status=status.HTTP_404_NOT_FOUND) models.py class ShopItems(models.Model): item_name = models.CharField(max_length=100, null=False, blank=False) item_price = models.FloatField(null=False) item_author = models.CharField(max_length=100, null=False, blank=False) date = models.DateField(auto_now_add=True, editable=False) class Image(models.Model): shop_item = models.ForeignKey(ShopItems, on_delete=models.CASCADE, related_name="images") image = models.ImageField() serializers.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = ['image',] class ShopItemSerializer(serializers.ModelSerializer): images = ImageSerializer(many=True) def create(self, validated_data): images_data = validated_data.pop("images") shop_item = ShopItems.objects.create(validated_data) for image_data in images_data: Image.objects.create(shop_item=shop_item, song=image_data) return shop_item class Meta: model = ShopItems fields = [ 'item_name', 'item_price', 'item_author', 'date', 'images', ] script.js $("#addItemForm").on("submit", function (e) { e.preventDefault(); let data = new FormData($(this)[0]); $.ajax({ url: … -
How properly use mptt?
There are model: class Employee(MPTTModel): name = models.CharField(max_length=100) position_name = models.CharField(max_length=100) position_lvl = models.IntegerField(null=True) hired_at = models.DateField(auto_now=True) salary = models.DecimalField(max_digits = 9, decimal_places= 2) parent = TreeForeignKey('self', null=True,blank=True, on_delete=models.CASCADE, related_name='subordinate') class MPTTMeta: order_insertion_by = ['position_lvl'] There are the view: def show_employees(request): return render(request, "employees.html",{'employees': Employee.objects.all()}) There are template: {% load mptt_tags %} <ul> {% recursetree employees %} <li> <{{ node.id }}>{{ node.name }} - {{ node.position_name }} ({{ node.position_lvl }}) {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> I want to show employees by their position lvl (boss of the bosses have lvl 0, employee of the boss have 2 and etc.) But when i use this model and template i have not the correct image: <6>Имя манагера - манагер (2) <2>Дон Симон - Старший манагер (1) <1>Влад Савельев - Самый старший (0) <3>Генадий Горин - манагер (2) <4>Вася Пупкин - Старший разраб (1) <5>Виндовс Убунтович - разраб (2) The tempalte goes: Name - postion_name (position_lvl) And i want see all employees with the lvl 2, then their bosses with lbl 1 and the the boss of all bosses with lvl 0. How can i make it the right … -
Remove field from drf-api-tracking for Django Rest Framework
I'm using drf-api-tracking to track requests to an api build with Django Rest Framework. With time, the size of the resulting table is growing too big, and I don't need the information stored in the column that takes up the most space ("response", which contains the full JSON response data). Is there a way to systematically avoid storing this information? In the documentation I found instructions on how to avoid logging at all in certain cases, but not on how to skip individual columns. -
How to pass data (specific fiiled) from views.py to models.py
I have a problem. How can i pass the data (def maybe) from models.py I need this for filter by category in future def get_category(self): return self.category To views.py. This sample it doesn't work class GetDetailTag(DetailView): model = Tag template_name = 'main/catalog.html' context_object_name = 'tag' category = Tag.get_category def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs,) context['pansion_in_tag_list'] = Pansions.objects.filter(tags__slug=self.kwargs['slug']) context['tags_in_category'] = Tag.objects.filter(category__slug = '...INSERT THE DATA FROM MODEL HERE...') return context I was trying to call the 'def'(get_category) in views.py Anyway? How i can to do that? -
How to correctly perform async django task execution
I am trying to make it so that a User is able to click Download on a web page to download about 30 reports from a third party API. Obviously, this takes time. So I am planning on implementing a WebSocket-based webpage that displays the status of that particular download (even if they reload the page) using Celery, Redis and Django Channels and Postgres. If a user wishes to download multiple reports at once, each download will be placed in a Queue. I know how to create tasks and use Django Channels, I’m just wondering if there is a standard way to manage task status in the database, so no matter what happens - the download on the front-end isn’t always saying ‘processing’ forever if it has failed for example. Is there a correct way to store the status of the task in the database? What if the download (task) fails during execution, how does it get stored? Any help would be appreciated. I have created the front-end thus far and prepared for websocket execution. -
404 Error while serving files with django
I want to access logs easily on my app so I created a page for that, I click on a button and it download the log. But I get a 404 error when I try to do that, I've set static files and media files here are my settings STATIC_URL = 'static/' STATICFILES_DIRS = [ "frontend/static", ] MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media') LOG_URL = 'static/logs/' LOG_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static/logs') and here are my urls urlpatterns += static(settings.LOG_URL, document_root = settings.LOG_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) It works when I access /media/path/to/media.file, but not for /static/logs/path/to/logs.txt, it's the same configuration for both urls so I know I miss a point, but how could I fix it? Is it because I used static and not media? Thx a lot -
How Can I use Django Filter Backend url parameters fields for multible models connected via onetomany connection?
I have an master and masterDetail model given in below; class Master(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)s_user') create_date = models.DateTimeField(auto_now_add=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='%(class)s_company') department = models.ForeignKey(Department, on_delete=models.CASCADE, related_name='%(class)s_department') is_active = models.BooleanField(default=True) class MasterDetail(models.Model): master = models.ForeignKey(Master, on_delete=models.CASCADE, related_name='%(class)s_master') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)s_user') recordtypes = models.ForeignKey(RecordTypes, on_delete=models.CASCADE, related_name='%(class)s_recordtypes') create_date = models.DateTimeField(auto_now_add=True) I want to filter data using these two model fields at the same time using Django Filter Backend url parameters. The url has two model field parameters like; http://127.0.0.1:8003/api/master/detail/query/page/list?search=&pages=1&page_size=14&company_code=XXX&recordtypes=general -
Django Model filters method finder
I would like to know if there is any way to do dynamically regroup a model by all available columns. models.py class ProductionPlan(models.Model): status_choices = ( ('READY TO START', 'Ready To Start'), ('IN PROGRESS', 'In Progress'), ('PROGRESS STOPPED', 'Progress Stopped'), ('MAINTENANCE STOPPED', 'Maintenance Stopped'), ('QUALITY STOPPED', 'Quality Stopped'), ) id = models.CharField(max_length=15, primary_key=True) first_start_date = models.DateTimeField(null=True, blank=True, default=None) bills_of_material = models.ForeignKey(BillsOfMaterial, on_delete=models.CASCADE) quantity = models.IntegerField() scheduled_date = models.DateTimeField() real_duration = models.DurationField() expected_duration = models.DurationField(default=None) start_date = models.DateTimeField(default=None, null=True) status = models.CharField(max_length=50, default='Ready To Start', choices=status_choices) now if i want to filter model i would use ProductionPlan.objects.filter(status__icontains = '') Then my question is this method of searching status__icontains or any other (start_date_contains, expected_duration__startswith) how can i get these methods. my end point is something like this: def get_methods_for_filter(model): do something here return ((**start_date_contains**, **expected_duration__startswith**) -
Django Override the Default success_url in contrib.auth.views
I made an app with app_name = 'accounts' in urls.py of the django and created signup/login pages there using the built-in signup function. Now I need to change all the class details of the success_url, for instance from: reverse_lazy('login') to: reverse_lazy('accounts:login') but overwriting the original urls.py is not a good practice. I'm a python beginner and struggling with this problem already for a month.. how can I achieve this? What I attemptd was making subclasses in my views inherent from each of the class in django.contrib.auth.views. I even tried putting try/except method with except 'NoReverseMatch:' but the function itself did not exist. -
Does django-cachalot lib support Django version 4.0?
Currently, the new django.core.cache.backends.redis.RedisCache cache backend provides built-in support for caching with Redis and I used it in my application. I've used the latest version django-cachalot and get this warning: Cache backend 'django.core.cache.backends.redis.RedisCache' is not supported by django-cachalot. It's so weird! Please help me to clear my question. I'm using Python 3.9, and MySQL 5.7. I applied the latest version of django-cachalot into Django app version 4.0.8, but get this warning: Cache backend 'django.core.cache.backends.redis.RedisCache' is not supported by django-cachalot -
How to confirm from user if he wants to leave the page while filling form?
I am creating a form where user can fill data. Based upon the user's input and selected options I'm showing the next data to fill using js which works totally fine. Now what I want is if the user presses the back or exit button accidentally. I want to confirm with the user if he really wants to exit from the current page. -
How to write an image attribute file in django (The 'image' attribute has no file associated with it)
I am building a django blog website and I am trying to upload an image on the website. I can access the photos on the admin page but whenever I try to access it on the page I get an enroll. The trace back says " The 'image' attribute has no file associated with it. This my code for the model class article(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() image = models.ImageField(null=True, blank=True, upload_to='static/media/article') date = models.DateTimeField(default=timezone.now) def __str__ (self): return self.title def get_absolute_url(self): return reverse('article-detail', kwargs= {'pk':self.pk}) This is my views code class ArticleCreateView(LoginRequiredMixin, CreateView): model = article fields= ['title', 'content', 'image'] def ArticleCreateView(request): if request.method == "POST": form = ArticleForm(request.POST, request.FILES) if form.is_valid(): article = form.save(commit=False) article.author = request.user.id article.save() return HttpResponse this is the blog template code {% extends "agri_tourism/base.html" %} {% load crispy_forms_tags %} {% block content %} <section class="flex-container"> <div> {% for article in articles %} <article class="media content-section"> {% load static %} <div class="media-body"> <div style="text-decoration:none; display: inline-block;" class="article-metadata"> <img class="rounded-circle article-img" src="{{user.profile.image.url}}"> <a style="text-decoration:none;" class="mr-2" href="#">{{ article.author }}</a> <small class="article-date">{{ article.date|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="">{{ article.title }}</a></h2> <p class="article-content">{{ article.content }}</p> <img class="image-content" id="image-el" src = … -
Gunicorn ModuleNotFound : No module named 'core' when Deployment Django
I try to deployment my apps. So when i try to run this command gunicorn -c conf/gunicorn_config.py core.wsgi Error : ModuleNotFound : No module named 'core' This is my directory home/uletin --- conf --------- ... --------- gunicorn_config.py --- env --- graduates ------... ------core ------------ ... ------------ settings.py ------------ wsgi.py ------------ ... ------manage.py ------static in gunicorn_config.py like this command = '/home/uletin/env/bin/gunicorn' pythonpath = 'home/uletin/graduates' bind = '165.22.98.56:8000' workers = 3