Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse Foriegn Key in Django Serializers
Suppose class Post(models.Model): content = ... image = ... timestamp = ... class PostLike(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,...) post = models.ForiegnKey(Post,...) timestamp = ... and class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ("content","image","timestamp","liked") Here liked could be true or false. It will be true if user (request.user) is in PostLike. How do i create that liked field? -
Get all appointments on the same day, same time, same seat - django
I have two models: seat model: class Seat(models.Model): name = models.CharField(max_length=255) slug = models.SlugField() short_description = models.TextField(blank=True, null=True) created_at = models.DateField(auto_now_add=True) appointments model: class Appointment(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) seat = models.ForeignKey(Seat, on_delete=models.SET_NULL, null=True) start_appointment = models.DateTimeField(default=timezone.now, blank=True) end_appointment = models.DateTimeField(default=timezone.now, blank=True) name = models.CharField(max_length=255) I would like to get all appointments performed on the same date, same time and same seat. Lets illustrate, 28 Nov Time | Seat 1 | Seat 2 | 3:00 | Jim, John | Alex, Bean | So far i can get appointments on same date and for specific seat but i cannot figure out how can i get same time, i.e today = datetime.datetime.now() appointments_per_day = Appointment.objects.filter(start_appointment__day=today.day).filter(seat__name='Seat1').values() Any ideas? -
Sending email is not working for a django app on Digital Ocean
I am facing problem sending email on production with Digital ocean. This is my settings: MAILER_EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'Mypassword' DEFAULT_FROM_EMAIL = 'noreply<no_reply@domain.com>' All is working fine on development mode and on terminal as well When I tape ( to test) : from django.core.mail import send_mail send_mail('test email', 'hello world', 'sender@gmail.com', ['reciever@gmail.com']) I got : 550 5.4.1 All recipient addresses rejected : Access denied. AS(201806271) Please note that I authorise less secure apps on gmail account. Does any one has an idea ? Regards -
Django : One to many relationship
I have a question regarding objects modelling. Let's say we have a one to many relationship where an object A instance could have 0 to many linked objects B whereas object B could be linked to one and only one object A (note here object B cannot be created without being linked to an object B). So far I have added a foreign key to object B model, when adding that object I should select an Object A , so far so good. My question now is do I have to also add the object B to object A model on database level? Or should I just do it on API level by creating nested APIs? So that getting object B would be this way : get : http://localhost/api/objectA/objectB I hope I was clear explaining my question but to summarize I am not sure if adding a foreign key to represent a : 0.n---->1.1 is enough. It has been a long time for me that I did not design a database am I using a very old methodology? Thanks -
Can't figure out the for loop logic
I am trying to write a code where the user submits a wiki search. If the query is in the given list of entries, the user should be redirected to related entry's page. If the query doesn't match the name of an entry but is a substring of any entry, the user should be taken to a page that lists the related entries. My problem is that I couldn't figure out how to logically implement return statements. The code below works fine: def search(request): sub_list = [] entries = util.list_entries() search = request.GET.get("q") for entry in entries: if search.lower() == entry.lower(): return redirect("entry", title= search) elif search.lower() in entry.lower(): sub_list.append(entry) return render(request, "encyclopedia/search.html",{ "title":search, "sub_list":sub_list }) But when I try to add another condition for the case where the query doesn't match the name of an entry, either it always returns to "Not Found": for entry in entries: if search.lower() == entry.lower(): return redirect("entry", title= search) else: if search.lower() in entry.lower(): sub_list.append(entry) return render(request, "encyclopedia/search.html",{ "title":search, "sub_list":sub_list }) return HttpResponse("Not Found") or returns only the first substring match: for entry in entries: if search.lower() == entry.lower(): return redirect("entry", title= search) else: if search.lower() in entry.lower(): sub_list.append(entry) return render(request, "encyclopedia/search.html",{ "title":search, … -
Django c'ant runserver
my project worked but whene l added static folder withe css and js bootstrap file it crashed first sec third -
Add or Edit if already exists
I'm working on a web application that has a number of forms that allow the user to submit data to the database. The data is linked to a project, and from the project page, I have a drop-down list that allows you to select what information you want to add to the project. At the moment I have two views linked to two dropdown lists. One to add new data and one to update, but ideally, I'd like the button to either take you to the update or add a new page depending on data already being added to the database. So is there a way to have a single button that automatically takes you to the correct view? I imagine i'll need some kind of logic within the view to handle this. But im not sure what this would be? Views.py @login_required def AddFundamentals(request,project_id): project = get_object_or_404(Project, pk=project_id) if request.method == 'POST': form = AddFundamentalsForm(request.POST) if form.is_valid(): form.instance.project = project form.save() return redirect('http://127.0.0.1:8000/') else: form = AddFundamentalsForm() return render(request, 'pages/add_fundamentals.html', {'project': project, "form": form}) @login_required def UpdateFundamentals(request,project_id): project= Project.objects.get(pk=project_id) form = AddFundamentalsForm(request.POST or None, instance=project) if form.is_valid(): form.save() return redirect('dahsboard.html') return render(request, 'pages/update_fundamentals.html', {'project': project, "form": form}) HTML <div … -
create custom domain email and receive email in python
I want to receive an email on this abcd@myemail.com. I want to use python(django) in the backend, for achieve this task which libraries and steps do I have to take. -
Error trying to host my Django project on Heroku
I was creating a Django project trying to upload it to Github. When I was doing git push Heroku main it pushed most of them. Before finishing pushing all of them, this error popped up: ![remote rejected] main -> main (pre-receive hook declined) error: failed to push some refs I followed my steps on this site: https://realpython.com/django-hosting-on-heroku/#make-an-app-release -
matching query does not exist django V3.2.9
I am trying to retrieve the ID from a POST request which throws matching query does not exist when i am certain that specific ID for that customer exists because all it's information is displayed at the template table also using {{customer.id}} in the template gives an (ID) to make sure that it actually exists My views.py from .models import Customer,FilterMaintenance def index(request): if request.method == "POST": filtermaintenance_id = FilterMaintenance.objects.get(pk=request.POST.get('{{customer.id}}', False)) x = filtermaintenance_id.filter_last_due_date f = FilterMaintenance.objects.all() return render(request,'maintenance/index.html',{ "customers_maintenance":f, "test":x }) my models.py class Filter(models.Model): filter_brand= models.CharField(max_length=64) filter_interval = models.IntegerField() def __str__(self): return f"{self.id} , {self.filter_brand}" class Customer(models.Model): first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=64) phone_number = models.IntegerField(blank=True) home_address = models.CharField(max_length=64,blank=True) email = models.EmailField(blank=True) notes = models.TextField(blank=True) def __str__(self): return f"{self.id}, {self.first_name}, {self.last_name}" class FilterMaintenance(models.Model): customer_info = models.ForeignKey(Customer,related_name="customer_set",on_delete = models.CASCADE) customer_filter = models.ForeignKey(Filter,related_name="filter_set",on_delete = models.CASCADE) filter_last_due_date = models.DateField() def __str__(self): return f"{self.id}, {self.customer_info}, {self.customer_filter},{self.filter_last_due_date} " my index.html {% extends "maintenance/layout.html" %} {% block body %} <div class="maintenance-container"> <h1>Section for customers ...</h1> <table class="maintenance-table"><thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Phone number</th> <th>Home address</th> <th>Filter brand</th> <th>Last filter change</th> <th>Next filter due date</th> <th>Filter done</th> </tr> </thead> <tbody> {% for customer in customers_maintenance %} <tr> <td>{{customer.customer_info.first_name}}</td> <td>{{customer.customer_info.last_name}}</td> <td>{{customer.customer_info.phone_number }}</td> <td>{{customer.customer_info.home_address}}</td> <td>{{customer.customer_filter.filter_brand}}</td> <td>{{customer.filter_last_due_date}}</td> … -
get current logged in user info in Django
i try to get logged in user info inside a form class in Django. class PayForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PayForm, self).__init__(*args, **kwargs) self.fields['username_id'].initial = ? #current_logged_in_user_id() -
Using Ajax call for sending sort criteria from template to a Django view
I wish to send a sort criteria from a Django template to the associated view and update the template without reloading the page. Understand that an Ajax call is the way to go, but how would I implement this? store.html {% extends 'ecomsite/main.html' %} {% load static %} {% block content %} <select class="form-control" id="sort"> <option value="default" selected="selected">Default</option> <option value="price-low">Price(lowest first)</option> <option value="product-name">Product Name</option> </select> <br> <div class="row"> {% for product in products %} <div class="col-lg-4"> <img class="thumbail" src="{{product.imageURL}}"> <div class="box-element-product"> <h6><strong>{{product.name}}</strong></h6> <hr> <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-primary add-btn update-cart">Add to Cart</button> <a href="{% url 'detail' product.id %}" class="btn btn-outline-info">View</a> <h5 style="display: inline-block; float: right"><strong>€{{product.price|floatformat:2}}</strong></h5> </div> <br> </div> {% endfor %} </div> {% endblock %} views.py def store(request): data = cartData(request) cartItems = data['cartItems'] products = Product.objects.all() context = {'products':products, 'cartItems':cartItems} return render(request, 'ecomsite/store.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path('',views.store,name='store'), path('cart/',views.cart,name='cart'), path('checkout/',views.checkout,name='checkout'), path('update_item/',views.updateItem,name='update_item'), path('process_order/',views.processOrder,name='process_order'), path('getting_started/',views.HowtoView.as_view(),name='howto'), path('myorders/',views.order_list,name='list'), path('signup/',views.Signup.as_view(),name='signup'), path('thankyou/',views.thank_you,name='thank_you'), path('products/<int:id>/',views.product_detail,name='detail') ] -
Django: How to ensure a parent class only has one child instance
This a theoretical question which I want to reapply to my own study. However, say I have three models: class Person(models.Model) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class Teacher(Person) teacher_id = models.IntegerField() class Student(Person) student_id = models.IntegerField() What database/model restrictions can I put in place to ensure that an instance from both children cannot be created with the same Person id. Note: Obviously I could put a small check when saving but was hoping for something more "Pythonic" -
How to send script's return value to view using html href
I'm using django I want to send what I clicked as a parameter to my view getneworder. So I made a script which tells me what I clicked. It succeed but, I coudn't find a way to send the get_mall()'s return value to view using onclick. I kept googling but coudn't find an answer. How do I send the return value of get_mall() to view using onclick? thank you <li class="nav-item"><a class="nav-link" onclick="change_mall('esm');" href="{% url mallboard:esm' %}">ESM</a> var mall = "null" function change_mall(new_mall) { {#alert('change_mall to :'+new_mall)#} mall = new_mall } function get_mall() { {#alert(mall)#} return mall } @login_required(login_url='common:login') def getneworder(request, mall_name): if (mall_name =="coupang"): print("couapng") return HttpResponse("coupang") elif (mall_name=="interpark"): print("interpark") return HttpResponse("interpark") else: print("err") return HttpResponse("err") -
avoid sending same field with same value in body in django rest framework
I am trying to create objects in bulk but during the creation I have to send the same data of class = 2 in every objects which I think will make the code inefficient as well as the app. How to send that particular field just once? For eg: class AttendanceView(viewsets.ModelViewSet): queryset = Attendance.objects.all().order_by('-created_at') serializer_class = AttendanceSerializer def create(self, request, *args, **kwargs): data = request.data serializer_class = self.get_serializer_class() serializer = serializer_class(data=data,many=True) if serializer.is_valid(): serializer.save() return Response({ "message": "Data posted successfully.", "data":serializer.data, return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) My serializer: class AttendanceListSerializer(serializers.ListSerializer): def create(self, validated_data): attendance = Attendance.objects.bulk_create([Attendance(**datas) for datas in validated_data]) return attendance class AttendanceSerializer(serializers.ModelSerializer): class Meta: model = Attendance fields ='__all__' list_serializer_class = AttendanceListSerializer The data are sent like this from frontend: [ { "class":2, "student":16, "status":"a" }, { "class":2, "student":15, "status":"p" }, { "class":2, "student":17, "status":"p" } ] Here we can see that class 2 is repeated all the times which is inefficient. Can we send this just once and not repeatedly? Also there might be other fields that might be repeated as well. I know we can send it into url but sending id while creating in the url endpoint doesnt look nice and there might be several other fields which … -
How to use django PWA on android
I created a django PWA but I do not know how to get in on the phone. When I created the PWA with my laptop following instructions here https://www.geeksforgeeks.org/make-pwa-of-a-django-project/, it just converted my laptop dev tools look to be a phone but I cannot find on the internet how to actually jam the app on the phone. I tried heroku also but could not get the database to populate with loaddata. -
Dajango FK constraint complaint, but object is there. What do I miss?
I am at my first Django app, please bear with me... It's based on some legacy scripts with an existing PostgreSQL database. Hence, the naming of some of the tables doesn't follow the Django naming schema. Currently I am in the middle of remodeling my data to follow sane data modeling principles. The migration doing one of the steps gives me an foreign key exception I do not understand: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 242, in _commit return self.connection.commit() psycopg2.errors.ForeignKeyViolation: insert or update on table "design_shopify_category" violates foreign key constraint "design_shopify_categ_shopifycollection_id_9f310876_fk_designs_s" DETAIL: Key (shopifycollection_id)=([<ShopifyCollection: ShopifyCollection object (gid://shopify/Collection/263596736569)>]) is not present in table "designs_shopifycollection". The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.9/runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "/usr/local/lib/python3.9/runpy.py", line 87, in _run_code exec(code, run_globals) File "/root/.vscode-server/extensions/ms-python.python-2021.11.1422169775/pythonFiles/lib/python/debugpy/__main__.py", line 45, in <module> cli.main() File "/root/.vscode-server/extensions/ms-python.python-2021.11.1422169775/pythonFiles/lib/python/debugpy/../debugpy/server/cli.py", line 444, in main run() File "/root/.vscode-server/extensions/ms-python.python-2021.11.1422169775/pythonFiles/lib/python/debugpy/../debugpy/server/cli.py", line 285, in run_file runpy.run_path(target_as_str, run_name=compat.force_str("__main__")) File "/usr/local/lib/python3.9/runpy.py", line 268, in run_path return _run_module_code(code, init_globals, run_name, File "/usr/local/lib/python3.9/runpy.py", line 97, in _run_module_code _run_code(code, mod_globals, init_globals, File "/usr/local/lib/python3.9/runpy.py", line 87, in _run_code exec(code, run_globals) File "/workspace/src/otaya_tool/manage.py", line 23, in <module> main() File "/workspace/src/otaya_tool/manage.py", line 19, … -
User verification for desktop application
I've developed a python desktop application using Kivy with intent to sell it for a monthly fee like a subscription. I'm planning to develop a simple website(probably using Django) where user can create an account, pay for the subscription/cancel it... . Once the user downloads the app he will have to login by entering his username and password he used to create an account on that website to verify if he has paid for the subscription or not. However I don't know what's the best way to do this verification process. I was thinking some API that will be integrated in the website and it will just query the database to check if user paid for the subscription. But I don't know if its possible with Django and Python. I know there are probably other ways to handling this problem that's why I'm asking the more experienced. Thanks for any suggestions :) -
Unsupported config option for services: 'account-database'
I am trying to create image and container with docker-compose up --build -d and this docker-compose.yml : services: account: build: context: . dockerfile: Dockerfile.dev env_file: - ./envs/development.env volumes: - ./:/app ports: - 8000:8000 command: gunicorn account.wsgi:application --reload --bind 0.0.0.0:8000 account-database: image: postgres:alpine env_file: - ./envs/development.db.env networks: default: name: mizban and docker-compose-production.yml : services: account: build: context: . env_file: - ./envs/development.env ports: - 8000:8000 volumes: # - ./:/app - /store/account/media:/app/media - /store/account/static:/app/static command: gunicorn account.wsgi:application --reload --bind 0.0.0.0:8000 account-database: image: postgres:alpine env_file: - ./envs/development.db.env volumes: account-media: account-static: networks: default: name: mizban but i got this error : ERROR: The Compose file './docker-compose.yml' is invalid because: Unsupported config option for services: 'account-database' Unsupported config option for networks: 'default' i have googled and it seems the problem is about indentation but i cant find out where the issue is -
Cannot get NGINX auth_request working with UWSGI + Django REST backend
I have a working NGINX > UWSGI > Django REST application where large-file uploads are sent to NGINX directly. After the upload has finished, Django gets notified that the upload is complete, and further update its database. As soon as I add an auth_request sub-request to the NGINX config, however, I'm getting upstream 502 errors. I have tried many different things based on info I found (in SO but also in other places). None of the examples that I saw specifically used UWSGI. Most of the auth_request examples simply refer to some auth-server that is connected but no further details. Below you can find some of the config file I'm using. The nginx.conf works without issues without the 'auth_request /auth' statement. Eveything is running in Docker containers on the yoda_default network. My Django backend container is called yoda_web and running on port 8001, so that's what you see in the nginx.conf (uwsgi_pass yoda_web:8001). NGINX itself is running on port 8002. At the bottom, there's the pytest script I used to test everything. Without the 'auth_request' statement in nginx.conf it works fine (see output below) yoda_nginx | 172.31.0.1 - - [28/Nov/2021:08:59:17 +0000] "POST /tokens HTTP/1.1" 200 52 "-" "python-requests/2.7.0 CPython/3.9.9 Darwin/20.6.0" … -
not able to run python manage.py migrate while I have some environment variables in the settings file
Am using 2 separate files for settings in my Django project one for production and the other for debugging,, here is how they look : base.py """ Django settings for arkb_eh project. For more information on this file, see https://docs.djangoproject.com/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ['secret_key'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [os.environ['allowed_host']] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', # <-- Here 'location_field.apps.DefaultConfig', 'colorfield', 'auth_system', 'stations', 'lines', 'trips', 'chat', ] 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 = 'arkb_eh.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], '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', ], }, }, ] WSGI_APPLICATION = 'arkb_eh.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['database_name'], 'USER': os.environ['database_user'], 'PASSWORD': os.environ['database_pass'], 'HOST': 'localhost', 'PORT': '3306', } } REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', # <-- And here ], } # Password validation … -
add subitems for the suit menu subitems(3 level tree) in django-suit
Is it Possible to structure a 3 level tree with django-suit menu? If yes how can I do this or if there is another way to customize in the menu. what i need is something like that: Main Menu| |- SubItem1 |- SubItem2 |- SubItem2-1 |- SubItem2-2 |- SubItem3 -
How to handle recipe ingredients in database
Hi I'm new to programming and I am building a recipe website to learn, what I am struggling with though is how to handle recipe ingredients? I would like to do the following: Have global recipe ingredients i.e. common ingredients, chicken, beef etc. Allow users to create their own ingredients (for that user only) i.e. big tomato Attach ingredients to a recipe regardless of if they are global or user created Allow users to add ingredients to their pantry and how much of the ingredient they have in stock What I think the models would like is below, but I'm not sure if this is correct or the best method, any advice appreciated. recipe/models.py User = settings.AUTH_USER_MODEL class Recipe(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) recipeName = models.CharField(max_length=220) # grilled chicken pasta userRecipeIngredients = models.ManyToManyField(UserCreatedIngredient, blank=True, Null=True, through='IngredientToRecipe') globalRecipeIngredients = models.ManyToManyField(GlobalIngredient, blank=True, Null=True, through='IngredientToRecipe') class UserCreatedIngredient(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=220) # grilled chicken class GlobalIngredient(models.Model): name = models.CharField(max_length=220) # chicken class IngredientToRecipe(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) userIngredient = models.ForeignKey(UserCreatedIngredient, on_delete=models.SET_NULL) globalIngredient = models.ForeignKey(GlobalIngredient, on_delete=models.SET_NULL) quantity = models.CharField(max_length=50, blank=True, null=True) # 400 unit = models.CharField(max_length=50, blank=True, null=True) # pounds, lbs, oz ,grams, etc instructions = models.TextField(blank=True, null=True) # chopped, diced … -
Django channels chat async app not working on heroku but working fine in local environment and encounter no error in log files of heroku
I'm new to channels and I tried every possible solution to make it work but my chat app is not working on heroku, but is working fine in local environment. My other blog and story apps are working fine in local as well as on heroku, I'm facing this issue with just chat app. Here's the settings.py file ASGI_APPLICATION = 'core.routing.application' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer", # "CONFIG": { # "hosts": [('127.0.0.1', 6379)] # } } } routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatRoomConsumer.as_asgi()), ] asgi.py import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE','core.settings') application = get_asgi_application() consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] username = text_data_json['username'] await self.channel_layer.group_send( self.room_group_name, { 'type': 'chatroom_message', 'message': message, 'username': username, } ) async def chatroom_message(self, event): message = event['message'] username = event['username'] await self.send(text_data=json.dumps({ 'message': message, 'username': username, })) pass and my Procfile web: gunicorn core.wsgi:application --log-file - --log-level debug web: daphne core.asgi:application … -
django rest framework dosent even show the option to upload image. I do have imageField in models
django rest framework dosent even show the option to upload image. I do have imageField in models. I also get GET http://127.0.0.1:8000/api/person-create/ 405 (Method Not Allowed) in console when i go to the api url to create new item. TLDR I am trying to upload images using django rest framework i can do it from admin but not with DRF or frontend any help is appreciated Thanks. view.py @api_view(['POST']) def create_person(request): serializer = PersonSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) serializer.py class PersonSerializer(serializers.ModelSerializer): image = serializers.ImageField(max_length=None, allow_empty_file=False, allow_null=True, required=True) class Meta(): model = Person fields = 'name', 'about', 'created_at', 'email', 'image' urls.py urlpatterns = [ path('', views.apiOverview, name='apiOverview'), path('persons/', views.all_persons, name='all_persons'), path('person/<str:pk>', views.person, name='person'), path('person-create/', views.create_person, name='create'), path('person-update/<str:pk>', views.update_person, name='update_person'), path('person-delete/<str:pk>', views.delete_person, name='delete_person'), ] models.py class Person(models.Model): name = models.CharField(max_length=50) about = models.CharField(max_length=10000) created_at = models.DateTimeField(auto_now_add=True) email = models.EmailField(unique=True) image = models.ImageField(blank=True, null=True, upload_to='media/', default='default.png') Heres the frontend part create.js const Create = () => { let history = useHistory(); let [person, setPerson] = useState({ name:"", about:"", email:"", image:"", }) let createPerson = async (e) => { e.preventDefault() fetch(`/api/person-create/`, { method: "POST", headers: { "content-type": 'application/json' }, body: JSON.stringify(person) }) .then(setPerson({ name:"", about:"", email:"", image:"", })) } let handleChange = (e) …