Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django use request.META['HTTP_ORIGIN'] in django sites framework
So I have a task where I have to use django.sites framework in order to filter some objects in ApiViews depending on the client (there are different front-end clients hosted on different domains) which called the api. so www.frontend1.com and www.frontend2.com are calling www.myapi.com The problem is that both of the clients are calling the api and now I have to "divide" it depending on the request.META['HTTP_ORIGIN']. I've red about django.sites framework (I was asked to use it) but this framework should be useful if the site is hosted on different hosts with the samo codebase. But if the host is the same it renders the django.sites framework useless in my case. Or maybe I am wrong. I have to divide the api by site but instead ot HTTP_HOST I should relay on HTTP_ORIGIN. I've come up with two ideas. Override half of the django.sites framework, but im pretty shure that this will be an overkill Create a my own django.sites framework. Honestly I dont need the whole django sites framework, I will just add permissions in the staff users and filter the querysets depending on their rights and for the api I will just create an object_manager in the … -
using django's request.session with angular
I have a working Django app using session authentication. I am using request.user in my templates and views. I am also using several session variables like requst.session['some_variable']. Currently I am using Django for my backend and as well as for my frontend i.e. html templates, staticfiles etc. Everything's working fine. But I want to shift to angular for my frontend part. I tried using JWT authentication from my angular app. I am getting JWT token from django-restframework, this is my service file import {Injectable} from '@angular/core'; import {HttpClient, HttpHeaders} from '@angular/common/http'; @Injectable() export class UserService { // http options used for making API calls private httpOptions: any; // the actual JWT token public token: string; public sessionid: string; // the token expiration date public token_expires: Date; // the username of the logged in user public username: string; // error messages received from the login attempt public errors: any = []; readonly APIUrl = "http://127.0.0.1:8000"; constructor(private http: HttpClient) { this.httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'}) }; } // Uses http.post() to get an auth token from djangorestframework-jwt endpoint public login(user) { this.http.post(this.APIUrl + '/api-token-auth/', JSON.stringify(user), this.httpOptions).subscribe( data => { this.updateData(data['token']); }, err => { this.errors = err['error']; } ); } … -
Empty QuerySet in django-mysql JSONField
When I am executing ModelName.objects.filter(firstName__contains="MyName") it returns an empty queryset but when I am executing it's SQL equivalent in dbshell it is fetching the rows perfectly. select * from AppName_ModelName where firstName like '%MyName%'; I have constructed the sql query as per the documentation -
AttributeError: '_UnixSelectorEventLoop' object has no attribute '_signal_handlers'
I've been upgrading our Django/Python app to Python 3.9.7 and Django 3.2.7 (from Python 3.5 and Django 1.11.23). Currently if I try to run python manage.py createsuperuser I get the following error Traceback (most recent call last): File "/Users/instabrand/.pyenv/versions/3.9.7/lib/python3.9/asyncio/selector_events.py", line 261, in _add_reader key = self._selector.get_key(fd) File "/Users/instabrand/.pyenv/versions/3.9.7/lib/python3.9/selectors.py", line 193, in get_key raise KeyError("{!r} is not registered".format(fileobj)) from None KeyError: '10 is not registered' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/instabrand/Development/instabrand_platform/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/instabrand/.pyenv/versions/insta9/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/instabrand/.pyenv/versions/insta9/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/instabrand/.pyenv/versions/insta9/lib/python3.9/site-packages/django/core/management/base.py", line 367, in run_from_argv connections.close_all() File "/Users/instabrand/.pyenv/versions/insta9/lib/python3.9/site-packages/django/db/utils.py", line 213, in close_all connection.close() File "/Users/instabrand/.pyenv/versions/insta9/lib/python3.9/site-packages/django/utils/asyncio.py", line 19, in inner event_loop = asyncio.get_event_loop() File "/Users/instabrand/.pyenv/versions/3.9.7/lib/python3.9/asyncio/events.py", line 639, in get_event_loop self.set_event_loop(self.new_event_loop()) File "/Users/instabrand/.pyenv/versions/3.9.7/lib/python3.9/asyncio/events.py", line 659, in new_event_loop return self._loop_factory() File "/Users/instabrand/.pyenv/versions/3.9.7/lib/python3.9/asyncio/unix_events.py", line 54, in __init__ super().__init__(selector) File "/Users/instabrand/.pyenv/versions/3.9.7/lib/python3.9/asyncio/selector_events.py", line 61, in __init__ self._make_self_pipe() File "/Users/instabrand/.pyenv/versions/3.9.7/lib/python3.9/asyncio/selector_events.py", line 112, in _make_self_pipe self._add_reader(self._ssock.fileno(), self._read_from_self) File "/Users/instabrand/.pyenv/versions/3.9.7/lib/python3.9/asyncio/selector_events.py", line 263, in _add_reader self._selector.register(fd, selectors.EVENT_READ, File "/Users/instabrand/.pyenv/versions/3.9.7/lib/python3.9/selectors.py", line 523, in register self._selector.control([kev], 0, 0) TypeError: changelist must be an iterable of select.kevent objects Exception ignored in: <function BaseEventLoop.__del__ at 0x103307310> Traceback (most recent call last): File "/Users/instabrand/.pyenv/versions/3.9.7/lib/python3.9/asyncio/base_events.py", line … -
Celery periodic tasks being processed only if a post and get request is sent to a route containing .delay() and AsyncResult()
I want to run this task for every three minutes and this is what I have tasks.py @shared_task def save_hackathon_to_db(): logger.info('ran') loop = asyncio.get_event_loop() statuses = ['ended', 'open', 'upcoming'] loop.run_until_complete(send_data(statuses)) logger.info('ended') settings.py CELERY_BEAT_SCHEDULE = { "devpost_api_task": { "task": "backend.tasks.save_hackathon_to_db", "schedule": crontab(minute="*/3"), }, } However this doesn't get run every 3 minutes, it only gets run when I send a post request to http://0.0.0.0:8000/hackathon/task followed by a get request to http://0.0.0.0:8000/hackathon/<task_id> This is the code for the functions pertaining to the routes respectively @csrf_exempt def run_task(request): if request.method == 'POST': task = save_hackathon_to_db.delay() return JsonResponse({"task_id": task.id}, status=202) @csrf_exempt def get_status(request, task_id): print(task_id) task_result = AsyncResult(task_id) result = { "task_id": task_id, "task_status": task_result.status, "task_result": task_result.result } return JsonResponse(result, status=200) -
I can't create an object in the python shell because I can't import my app with the line "from products.models import Product"
I'm following a Django tutorial that has us creating an app named products I start the python interpreter in the root folder C:\Users\dancc\dev2\cfeproj using the line python manage.py shell when I run the line from products.models import Product I get the following error message ImportError: cannot import name 'Product' from 'products.models' (C:\Users\dancc\dev2\cfeproj\products\models.py) I read that this was a case of circular import, but I have no idea which file is the cause of it here is every part of files that includes the works with Products models.py #C:\Users\dancc\dev2\cfeproj\products\models.py from django.db import models # Create your models here. class Prodcut(models.Model): title = models.TextField() description = models.TextField() price = models.TextField() summary = models.TextField(default='this is so cool!') settings.py #C:\Users\dancc\dev2\cfeproj\cfehome\settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'products', ] apps.py #C:\Users\dancc\dev2\cfeproj\products\apps.py from django.apps import AppConfig class ProductsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'products' 0002_summery.py #C:\Users\dancc\dev2\cfeproj\products\migrations\0002_summery.py from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0001_initial'), ] operations = [ migrations.AddField( model_name='prodcut', name='summery', field=models.TextField(default='this is so cool!'), ), ] I also read that the structure of my files might also be the issue, but I don't want to mess around with the location without fully understanding it. -
How to protect child app urls using auth in a Django DRF API
This is my scenario: I have a legacy db and an Django api that is using it. Now we are developing another package with Django DRF that will be installed in the 'parent' app. The parent app already have oauth authentication. So in the parent app's settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('oauth2_provider.contrib.rest_framework.OAuth2Authentication',) } Then the routes are protected under this auth system. This is routes.py: urlpatterns = [ path('api/v1/', include('myapp.routes', namespace='api')), # OAuth 2.0 path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')) ] I install my package, that basically is a DRF API with managed=False models, and it will be an API that will work against the legacy DB. (this is done and working ok) pip install -m my_new_child_package After I install the package and add it's urls I would like to have authentication as well. Basically apply same auth of the parent app. So I am going to have this: urlpatterns = [ path('api/v1/', include('myapp.routes', namespace='api')), path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')) # I want to protect routes under api/v2/ as well with existent auth system. path('api/v2/', include('my_new_child_package.urls')), ] Should I configure something in my child app, or can what other alternative do I have? A middleware? -
bigger and smaller between 2 numbers in a row problem
I am trying to make a guessing game , when I run it it is run correctly but when I guess its make it bigger and smaller between 2 numbers in a row2 this is the code: The code is here -
Django JWT - Allow request with no credential if key in body is valid
I have an endpoint that needs an Access Token for authentication. Also in this endpoint, there's a serializer UUID field that is not required. What I would like to do is: In case the UUID field is passed in the body, check if this UUID is valid and registered in the Database. If it's not valid it'll raise a DRF ValidationError. If no UUID field is passed then the request needs to be authenticated with an Access Token. Is there a way to have this kind of seletive auth verification? -
Highlight Repeated Names
I have a webpage that shows a list of students being requested by teachers for tutoring. A student can only be listed requested once in reality but multiple teachers may accidentally request the same student unknowingly. Is there a way to highlight a student's name each time they are requested except for the first request? The highlighting will be used to signify to teachers that these requests are to be ignored. See attached picture for clarity. Screenshot of Webpage -
Long running request causes connection refused with daphne and nginx
I have a Django 3.2.4 application which I am running on Kubernetes, fronted by NGINX, served via ASGI / daphne. I have a long running API call (no longer than 30 seconds) that when running, seems to cause other requests to be refused. In the NGINX logs I see connect() failed (111: Connection refused) while connecting to upstream and in the pods I see the liveness probe fails (because connection refused), and get Killed 8 pending application instances. Can someone tell me what might be happening? -
How to get currently logged-in user in signals.py file?
I'm making a todo app and one of it's functionalities is to send an email to the user that his task was overdue. Part of the views.py file: from .models import Todo from django.utils import timezone from .signals import overdue def index(request): ... overdue_tasks = Todo.objects.filter(time__lte=timezone.now()) if overdue_tasks: overdue.send_robust(sender=Todo) ... return render(request, 'todo/index.html', {'overdue_tasks' : overdue_tasks }) Part of the signals.py file: from django.dispatch import receiver, Signal from .models import Todo from django.core.mail import send_mail overdue = Signal() user_email = request.user.email @receiver(overdue) def my_handler(sender, **kwargs): send_mail('My Task Manager', 'Your task was Overdue !', 'abdullahatif132@gmail.com', 'user_email', fail_silently=False)' It's raising exception: "NameError: name 'request isn't defined." -
Why does my React Dom render method not work?
I'm building a React-Django application, and on my App component, I'm getting an issue on the final line with my render(<App />, appDiv). Please can someone tell me what I'm doing wrong? I have the necessary modules imported, and this worked on my previous project. I am aware that Function-based components are better, but I'm more experienced with Class-based. Error: Code: import React, { Component } from "react"; import { render } from "react-dom"; import HomePage from "./HomePage"; export default class App extends Component { constructor(props) { super(props); } render() { return ( <div className="center"> <HomePage /> </div> ); } } const appDiv = document.getElementById("app"); render(<App />, appDiv); Thanks, DillonB07 -
How to pass parameters in django form
views.py def ATMlogin(request,id): global loginname loginname=='ATM_login' if request.method == 'POST': ATMnumber1=request.POST['ATMnumber'] mobnum1=request.POST['mobnum'] global mobnum global atmnum atmnum=ATMnumber1 mobnum=mobnum1 if Customer_details.objects.filter(ATMnumber=ATMnumber1).exists() and ATMLogin.objects.filter(mobnum=mobnum1).exists() : user_set=Customer_details.objects.all() for user in user_set.iterator(): if (user.ATMnumber==atmnum): id=user.id current_user={id:1} #current_user=Customer_details.objects.get(id=id) return render (request,'dashboard.html',{'current_user':current_user}) form=ATMLoginform() return render (request,'ATM_login.html',{'form':form}) urls.py from django.urls import path from . import views urlpatterns=[ path('',views.login,name='login_option'), path('savings_login',views.savingsloginform,name='Savings_Login'), path('ATM_login',views.ATMloginform,name='ATM_Login'), path('OB_login',views.OBloginform,name='OB_Login'), path('Register_OB',views.registerOB,name='Register_OB'), path('dashboard/<int:id>',views.ATMlogin,name='dashboard'), path('sentsms',views.sendsms,name='sms_sent'), path('VerifiedDashboard',views.verifiedDashboard,name='Dashboard'), path('Logout',views.Logout,name='Logout'), ] **Atmlogin.html** {% csrf_token %} <img src="{% static 'Images/portrait_black_24dp.svg' %}" alt="" class="icon">{{form.ATMnumber}}<br><br> <img src="{% static 'Images/portrait_black_24dp.svg' %}" alt="" class="icon">{{form.mobnum}}<br><br> //--> class="fas fa-sign-in-alt"> Log-in guys help me i haveto finish this project aa soon as possible............................................... -
Retrieve data from Salesforce using Django
I am trying to integrate salesforce Rest API with Django, so for hours I have been trying to figure out the endpoint which it exposes, I have learned to create records but how do I access those records as the URL mentioned in docs is https://yourInstance.salesforce.com/services/data/v52.0/query/?q=SELECT+name+from+Account, what is "yourinstance" here, any help will be appreciated, thanks in advance when i tried to access above URL in thunder client it gave me this error Couldn't resolve the hostname to an IP address, Verify Url: https://trial65.salesforce.com/services/data/v52.0/query/?q=SELECT+name+from+Account -
How to use lock with pymemcache on Django?
I am using pymemcache 3.5.0 with Django 3.2.7. I have a lot of script running on my Django instance and also using the cache to share data between them. I have thoses configration in my Django settings: def json_serializer(key, value): print("Message Type: " + str(type(value))) if type(value) == str: return value, 1 return json.dumps(value), 2 def json_deserializer(key, value, flags): if flags == 1: return value.decode('utf-8') if flags == 2: return json.loads(value.decode('utf-8')) raise Exception("Unknown serialization format") CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '127.0.0.1:11211', 'OPTIONS': { 'no_delay': True, 'ignore_exc': True, 'max_pool_size': 1000, 'use_pooling': True, 'serializer': json_serializer, 'deserializer': json_deserializer, } } } I see in the pymemcache documentation that i can add a lock_generator parameter it is written this as the description: • lock_generator – a callback/type that takes no arguments that will be called to create a lock or semaphore that can protect the pool from concurrent access (for example a eventlet lock or semaphore could be used instead) But no exemple anywhere i have shearched a lot but found nothing on how to implement this. Is there anyone here that know how to implement a lock so not 2 threads can write or read the same key twice ? … -
'method' object is not subscriptable problem in python
in my code I am trying to make a guessing game, i take input from what num do you want to start to what num do you want to stop and that the code which break(that code in a while loop): ''' while True: user = int(randrange[num1 , num2]) ''' -
How to remove the post-fix 's' from the database table name in Django Model, which is automatically added by Djanog
can anyone tell me, how can I get rid of the postfix 's' from the db_table name. Below is the sample model code. When is see this model through the admin portal I see the database table name is 'countrys'. How can I remove this 's' from my db_table name? class Country(models.Model): name = models.CharField(max_length=30) population = models.IntegerField() alpha2Code = models.CharField(max_length=2, primary_key=True) languages = models.CharField(max_length=256) class Meta: db_table = "country" Thanks in advance -
How to Serve Media Files in Django + React
I'm confused about serving media files on django and react. Here is my code: Here is my settings.py : STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api-user/', include('landingpage.urls')), path('', TemplateView.as_view(template_name='index.html')) ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Render it on react : <img src="/img/logo.jpeg" // is it true? /> I put my image on build/img folder. When i open with localhost 3000 it's rendered but when i open with localhost 8000, i get not found error with this image link http://127.0.0.1:8000/img/logo.jpeg My question is : Where to put images? Should i create media folder to store all my image or put it on build/image folder? How to specify the src link to image on in react? Thanks. -
Can't run makemigrations after moving modules
I've got a module named: validators.py located at ./project/app1/validators.py. I have imported it inside one of my Models: # app1/models.py from .validators import validate_something After a while, I decide to move this validators.py to a separated directory utils/ ("package", __init__.py), so I can use its functions in all my apps without referencing the app1: ./project/utils/validators.py. After moving the module, I changed my import at the beginning of the Model: # app1/models.py from utils.validators import validate_something Now that I want to create new migrations using manage.py makemigrations I'm getting this error: File "project/app1/migrations/0001_initial.py", line 5, in <module> import app1.validators ModuleNotFoundError: No module named 'app1.validators' I can remove all migrations and regenerate them but I guess there should be another way to resolve this dependency issue. -
Prevent TypeError: updates[0] is undefined in Vue.js/Django application
I'm developing a Django/Vue.js application. Right after the login form, the Django view redirects to the user/username page, in which the Vue.Js file loads the data from the server. Here is the code: async created(){ await this.getUpdates(); } The detail of the getUpdates() function is reported below; basically, it posts at Django the date that the server needs to do its calculations. async getUpdates(){ await fetch(baseurl + 'getupdates', { method: 'post', headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken': await this.getCsrfToken() }, body: JSON.stringify(this.date) } ); var response = await this.loadUpdates(); this.updates = await response.json() }, async loadUpdates(){ await this.getUser(); var response = await fetch(baseurl + 'loadupdates', { method: 'post', headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken': await this.getCsrfToken() }, body: JSON.stringify(this.date) } ); this.updates = await response.json() } The html snippet that uses these updates are reported below <!--Avvisi--> <h3>Avvisi:</h3> <div class="container" > <div class="row" v-if="updates[0].length"> <div v-for="notice, index in updates[0]" class="col-md-3 col-6 my-1"> <!--Qua metto le carte--> <div class="card"> <div class="card-body"> <h4 class="card-title">[[notice.titolo]]</h4> <p><a v-bind:href="'notices/'+ notice.id" tabindex=0>Vedi dettaglio</a></p> <button class="btn btn-primary" @click="hide(notice)" tabindex=0>Nascondi</button> </div> </div> </div> </div> <div class="row" v-else> Nessun nuovo avviso oggi </div> </div> <br> The problem is that when I firstly log in to the page … -
ValueError when uploading resized django images to google cloud
i have this model which works fine when uploading resized images to the media file on my django project class ItemImage(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True,upload_to='item_img/') created = models.DateTimeField(auto_now_add=True) def save(self): im = Image.open(self.image) im_name = uuid.uuid4() im = im.convert('RGB') output = BytesIO() # Resize/modify the image im = im.resize((700, 700)) # after modifications, save it to the output im.save(output, format='JPEG', quality=90) output.seek(0) # change the imagefield value to be the newley modifed image value self.image = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.image.name, 'image/jpeg', sys.getsizeof(output), None) super(ItemImage, self).save() def __str__(self): return self.item.title when i changed the file storage to google cloud i faced this error when uploading the images ValueError at /ar/dashboard/my_items/edit_item/add_item_image/2/ Size 120495 was specified but the file-like object only had 120373 bytes remaining. note that the images are uploaded successfully when i remove the save method that is added so is there anything that i need to change in that save method when dealing with gcloud? -
for root in settings.STATICFILES_DIRS: TypeError: 'WindowsPath' object is not iterable WHILE MIGRATING in DJANGO(3.2.7)
(env) C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\social>python manage.py migrate Traceback (most recent call last): File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\social\manage.py", line 22, in main() File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\social\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\core\management_init_.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\core\management_init_.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\core\management\commands\migrate.py", line 75, in handle self.check(databases=[database]) File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\contrib\staticfiles\checks.py", line 7, in check_finders for finder in get_finders(): File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\contrib\staticfiles\finders.py", line 281, in get_finders yield get_finder(finder_path) File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\contrib\staticfiles\finders.py", line 294, in get_finder return Finder() File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\contrib\staticfiles\finders.py", line 57, in init for root in settings.STATICFILES_DIRS: TypeError: 'WindowsPath' object is not iterable -
In Django project uploaded img not showing in website
I just want to display profile picture.Img upload successfully but not showing the img.But if i try in admin panel then show me img. Here is my index.html code {% extends 'Login_app/base.html' %} {% block body_block %} {% if user.is_authenticated %} <p>Hi {{ user_basic_info.username }},</p> <p>Your Email {{ user_basic_info.email }}</p> <p><a href="{{user_basic_info.facebook_id }}"> Facebook Profile </a></p> <img src="/media/{{ user_more_info.profile_pic }}" width="200px"> {% else %} <div class="alert alert-primary"></div>You are not logged in!!</div> {% endif %} {% endblock %} Here is my setting.py media setting import os MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # This is a tuple MEDIA_URL = '/media/' Here the ss of website -
Method Not Allowed (POST): /cbvdelete/5/ Method Not Allowed: /cbvdelete/5/
i am not able to run this code viwes.py from django.shortcuts import render, redirect from django.urls import reverse_lazy, reverse from . models import Task from . forms import Taskform from django.views.generic import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import UpdateView,DeleteView class Tasklistview(ListView): model = Task template_name = 'home.html' context_object_name = 'task' class Detailview(DetailView): model=Task template_name = "details.html" context_object_name = 'task' class Updateview(UpdateView): model = Task template_name = "update.html" context_object_name = "task" fields = ('name', 'priority', 'date') def get_success_url(self): return reverse_lazy('todoapp:cbvdetail',kwargs={'pk':self.object.id}) class Deleteview(DetailView): model = Task template_name = 'delete.html' success_url = reverse_lazy('todoapp:home') urls.py from django.urls import path from . import views app_name='todoapp' urlpatterns = [ path('',views.home,name='home'), path('delete/<int:id>/',views.delete,name='delete'), path('edit/<int:id>/',views.update,name='update'), path('cbvhome/',views.Tasklistview.as_view(),name='home'), path('cbvdetail/<int:pk>/',views.Detailview.as_view(),name='cbvdetail'), path('cbvupdate/<int:pk>/',views.Updateview.as_view(),name='edit'), ] when i run this code i am getting a error this page isn't working right now i am not able to run this code gngnitgbnugriujvnnvtvnviuvntnvtvitu