Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to insert the data into model users group
I have created a custom User model in Django app users_and_auth to use the default authentication of the Django. models.py class Users(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255, blank=False, null=False) last_name = models.CharField(max_length=255, blank=False, null=False) profile_picture = models.ImageField(upload_to='profile_pictures/', max_length=None, null=True, blank=True) is_active = models.BooleanField(default=True) objects = managers.UserManager() USERNAME_FIELD = 'email' I want to categorize registered users in two different user groups say x and y. So, I added two new records in Group model of auth app i.e auth_group which was created when I run the first migration of the app. Then I run the migration of app users_and_auth which created 3 new models users_and_auth_users, users_and_auth_users_groups and users_and_auth_users_user_permissions. Now, these are the tables of database - As, shown in screenshot there is table in database called users_and_auth_users_groups which categorize users in groups listed in table auth_group. The table is described as below - I want to push the user_id and group_id in this database table from an APIView. What I don't understand is which exact app or model I will have to import so that I could use model.object.create(). -
Django - Ajax not sending data correctly
In my project, I set up an AJAX call, which grabs what a user entered inside an input, sends it to the server, and once returned back to AJAX, it should be displayed inside a div. However no text is displayed in the div as expected. Here is my HTML (signup.html): <form id="signup_form" action="{% url 'signup' %}"> {% for field in form %} {{ field }} <br> {% endfor %} <button class="signup-btn btn btn-primary">Sign up</button> </form> <div id="testbox"></div> JS: var delayTimer; $('#signup_form').keyup(function() { clearTimeout(delayTimer); delayTimer = setTimeout(function () { // Username input in my form(created by Django forms) var usernameVal = $("#username_signup").val(); $.ajax({ url: '/users/ajax/signup', data: { 'usernameVal': usernameVal, }, dataType: 'json', success: function(data) { $('#testbox').text(data['usernameVal']); console.log(data['usernameVal']); } }); }, 1000); }); views.py: // Function to handle AJAX request def ajax_signup(request): form = SignupForm(request.GET) if form.is_valid(): print("It works") return JsonResponse({'usernameVal': form.cleaned_data.get("usernameVal")}) else: print(form.errors) return JsonResponse({'hello': 'not working'}) // View that renders the form(template is the html provided above) def signup(request): context ={} form = SignupForm() context['form'] = form return render(request, 'signup.html', context) The Message "It works" is displayed to the console, therefore the form is valid, however when performing print(form.cleaned_data.get("usernameVal")), I get returned None to the console. This means the … -
Filter Only Custom Permission for the model(Django)
I know i can filter list of the permissions for a specific modal using below orm Permission.objects.filter(content_type__app_label=app_name, content_type__model=model_name) but actually i want to filter custom model permissions and default modal permissions for the specific modal separately. for example default_permissions = some_orm custom_permissions = some_orm Here custom permissions means, permission defined by user inside Meta class of any model. -
Django InlineFormSet DeprecationWarning on can_delete = False
I'm trying to remove the Delete checkbox from the inlines. Let's say I have two models with one to one relation: models.py class Users(model.Models): .... class Extra_Fields(models.Models): user = models.OneToOneField(Users, on_delete=models.CASCADE) other_fields = .... I want a form to update both of the related object at once: class CustomInlines(InlineFormSet): model = Extra_Fields fields = ['custom_fields'] can_delete = False class CopywriterProfile(UpdateWithInlinesView): # boring stuff inlines = [CustomInlines] As you can say I'm using UpdateWithInlinesView. When I try to load the form I get the following error: DeprecationWarning at /profile/ Setting `CopywriterInline.can_delete` at the class level is now deprecated. Set `CopywriterInline.factory_kwargs` instead. I suggest to use factory_kwargs to set can_delete = False, but I didn't find any documentation. Someone can help me? -
Failed to add a object in a app in the admin panel of Django
I am just a beginner in Django Web Development.Following a tutorial I tried to add a object on a app by admin in Django. This is a screenshot before adding object. After clicking Save button I got the error. OperationalError at /admin/products/product/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8000/admin/products/product/add/ Django Version: 2.1 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: C:\Users\royal\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\db\backends\sqlite3\base.py in execute, line 296 Python Executable: C:\Users\royal\AppData\Local\Programs\Python\Python38-32\python.exe Python Version: 3.8.2 Python Path: ['C:\\Users\\royal\\PycharmProjects\\PyShop', 'C:\\Users\\royal\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\royal\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\royal\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\royal\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Users\\royal\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages', 'C:\\Users\\royal\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\win32', 'C:\\Users\\royal\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\win32\\lib', 'C:\\Users\\royal\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\Pythonwin'] Server time: Tue, 24 Mar 2020 15:59:31 +0000 I'm completely new in this sector.Help me to get rid off this error. -
Python: Filter objects by Concat() and order by the same concatenation
In my Python/Django API project I need to get a quesryset from a model filtered by a concatenated combination of two fields and order by the same concatenation. However I only know to filter by one field like shown below. Requirement: TimeTable has two fields "date" and "time". I need to list data where the combination of both these fields are greater than current date time. Code: current_time = datetime.now() timetable = TimeTable.objects.filter(user=user_id, date__gte=current_time.date()).order_by(Concat('date','time')) How can I accomplish this? -
How to create a fillable and savable pop-up form in Django project?
How do I trigger a fillable pop-up when the user clicks on an image, on a Django web app that the winds up sorting the following result ? There many features that come after that as shown in here, that can wind up like that, and resulting on this final result, but so far I couldn't find a solution to that first step (my sole focus) on other websites. Is this something that can be done with HTML, CSS, and JS only, or do I have to use python to then save the data to the SQLite database ? If someone can suggest or hint at the steps that I need to follow to get this done I would really appreciate it. -
Why am I getting 'The requested URL / was not found on this server.' when deploying my django app?
I'm developing a django website and am currently working on deploying. I'm following this tutorial. And im in the last stage of the tutorial (1:08:00 in the video). After he finished configuration th django-project.conf file he saves and everything is working, but me on the other hand, i get an: Not Found The requested URL / was not found on this server. Apache/2.4.34 (Ubuntu) Server at **********.*** Port 80 This is my projects .conf file: <VirtualHost *:80> ServerName _ Redirect 404 / Alias /static /home/user/project/static <Directory /home/user/project/static> Require all granted </Directory> <Directory /home/user/project/project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/user/project/project/wsgi.py WSGIDaemonProcess project_app python-path=/home/user/project python-home=/home/user/project/venv WSGIProcessGroup project_app </VirtualHost> What could I be doing wrong? Thanks in advance! -
problem with get_object_or_404() in my django views,py
i cant find what is the problem with my django code , when i post sth it returns -->No User matches the given query. this is my token model in db : class token(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) token = models.CharField(max_length = 48) def __str__(self): return "{}".format(self.user) and this is my views.py function: @csrf_exempt def home(request): if request.method == 'POST': token = request.POST['token'] current_user = get_object_or_404(User, token__token=token) return HttpResponse(current_user) else: return render(request, 'add.html') -
Cannot populate database table during Heroku deployment?
I have a django app that runs perfectly well on my local server. Unfortunately, when I deploy it onto Heroku, the behaviour doesn't work as expected. I can see that it's a database related issue as my dropdowns which are supposed to load a list of values from my database are empty in production. I have checked on Heroku in the 'Ressources' section of my application and there is a database; it also contains all my project tables (django default tables + my main table). All the django default tables are properly populated (I compared them with my local postgres tables and it matched). Unfortunately, my main table is empty on Heroku, whereas it is populated as expected locally. I'm not sure to understand what has gone wrong, especially considering that the table itself has been recognized, yet it is empty. I've applied the command heroku run python manage.py migrate but it didn't fix the issue. My guess is that my database settings are correct for local deployment but not for Heroku deployment. Nevertheless, I'm not sure at all. I've tried replacing my db settings by the user/host/password/name provided by Heroku but it didn't work. Any guidance will be much … -
Cannot use AWS SES to send email by Django application sit in AWS EC2
I have a Django application which sit in AWS EC2, i want to connect to AWS SES to send Email, so i followed this tutorial: https://kholinlabs.com/the-easiest-way-to-send-emails-with-django First , i created an EC2 instance in ap-southeast-1a avalibility zone, which the inbound and outbound rules are as following: inbound rule: HTTP TCP 80 0.0.0.0/0 All traffic All All 0.0.0.0/0 All traffic All All ::/0 SSH TCP 22 0.0.0.0/0 SMTPS TCP 465 0.0.0.0/0 SMTPS TCP 465 ::/0 HTTPS TCP 443 0.0.0.0/0 outbound rule: All traffic All All 0.0.0.0/0 All traffic All All ::/0 then i created Django application inside the server: django-admin startproject mysite python3 manage.py makemigrations python3 manage.py migrate add the following lines in setting file: EMAIL_BACKEND = 'django_ses.SESBackend' AWS_ACCESS_KEY_ID = 'secret' AWS_SECRET_ACCESS_KEY = 'secret' AWS_SES_REGION_NAME = 'ap-southeast-2' AWS_SES_REGION_ENDPOINT = 'email-smtp.ap-southeast-2.amazonaws.com' then i created an SES instance in ap-southeast-2 avalibility zone. inside EC2 server, i follow the tutorial and type commands: python3 manage.py shell from django.core.mail import send_mail send_mail( 'Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'] ) but it stuck for very long time (around 10 mins) and then show timeout message. is there any step i missed? other info: for telnet: telnet email-smtp.ap-southeast-2.amazonaws.com 465 Trying 3.24.207.252... Connected to email-smtp.ap-southeast-2.amazonaws.com. Escape … -
Django Reverse Not Found when reversing a url in main app
I can not get my head around why this simple reverse() call for one of my Django-Views is not working. The error occurs in some of my tests: Reverse code snippet: # myapp/tests.py response = self.client.get(reverse('index', args=([element1],))) URL registry: # myapp/urls.py urlpatterns = [ path('', views.index, 'index'), path('configuration/', include('configuration.urls')), path('admin/', admin.site.urls), ] view: #myapp/views.py def index(request): elements_list = DB_ELEMENTS.objects.all() return render(request, "startpage.html", {'elements': elements_list}) The error I keep getting is Reverse for 'index' not found. 'index' is not a valid view function or pattern name. Any help appreciated. -
Integrate CoreUi React Template and python (Flask or Django)
I'm very new to CoreUi and I'm trying to connect CoreUi (Frontend) and Python (Backend) but everything I tried didnt work.. Does anyone of you know a good video or documentation which could help me ? I integrated React and Python (Flask) before in another project a couple of month before where I used this instruction from youtube: https://www.youtube.com/watch?v=YW8VG_U-m48&t=179s . I tried to integrate CoreUi and Flask the exact same way but it didnt work. I dont care if I use Django or Flask, I only want the connection to work... I also deleted the code where I tried to connect the frontend with the backend so I cant give you any code snippets or my webpack.config file. Hopefully anyone can give some instructions to simply connect the coreUi Template to python. I downloaded the coreUi template from GitHub (https://github.com/coreui/coreui-free-react-admin-template) -
Multiple databases using routers
I created an application with three apps account,Product and Post, i want to connect each app to different database but it is just not happening.Please tell me what i am doing wrong.This is the first time i am trying to use multiple databases. setting.py DATABASE_ROUTERS = ['account.router.AccountRouter', 'Post.router.PostRouter','Product.router.ProductRouter'] DATABASES = { 'default': {}, 'auth_db': { 'NAME': 'a_user', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'postgres', 'PASSWORD': '1234', 'HOST':'localhost' }, 'account_db': { 'NAME': 'account', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'postgres', 'PASSWORD': '1234', 'HOST':'localhost' }, 'post_db': { 'NAME': 'post', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'postgres', 'PASSWORD': '1234', 'HOST':'localhost' }, 'product_db': { 'NAME': 'product', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'postgres', 'PASSWORD': '1234', 'HOST':'localhost' } } Product/router.py class ProductRouter: """ A router to control all database operations on models in the auth and contenttypes applications. """ route_app_labels = {'Product',} def db_for_read(self, model): """ Attempts to read auth and contenttypes models go to product_db. """ if model._meta.app_label in self.route_app_labels: return 'product_db' return None def db_for_write(self, model): """ Attempts to write auth and contenttypes models go to product_db. """ if model._meta.app_label in self.route_app_labels: return 'product_db' return None def allow_relation(self, obj1, obj2): """ Allow relations if a model in the auth or contenttypes apps is involved. """ if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): … -
Unable to submit a form with Django (Using UserCreationForm & ModelForm)
I've been trying to create a method to upload a profile picture for a user at the time of registration. In order to do so, I created a custom ModelForm with a file field and displayed this along with a UserCreationForm. However, it throws this error ValueError at /signup The UserProfile could not be created because the data didn't validate. Files :- models.py from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) img=models.FileField(upload_to="profile/") def __str__(self): return self.user.username forms.py from django import forms from . models import UserProfile from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm # Create your models here. class ImgForm(forms.ModelForm): class Meta: model=UserProfile fields=['img'] urls.py from django.urls import path from . import views urlpatterns = [ path('', views.signin, name="signin"), path('signup', views.signup, name="signup"), path('logout', views.logout, name="logout") ] views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib import auth from django.http import HttpResponse from .forms import ImgForm from django.contrib.auth.forms import UserCreationForm # Create your views here. def signup(request): if request.method == 'POST': form=UserCreationForm(request.POST) imgform=ImgForm(request.POST, request.FILES) if form.is_valid() and imgform.is_valid(): #looks good user = form.save() img=imgform.save() img.user=user return redirect('/') else: html = "<html><body><script>alert('Invalid form')</script></body></html>" return HttpResponse(html) else: form=UserCreationForm() imgform=ImgForm() context={ 'form':form, 'imgform':imgform } return render(request, … -
Application error while deploying django webapp on Heroku
I tried a lot to solve this error but unable to solve it. I have searched a lot on every platform. Get Application Error: An error occurred in the application and your page could not be served. Please try again in a few moments. If you are the application owner, check your logs for details. Heroku logs: 2020-03-24T14:33:58.867536+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 393, in stop 2020-03-24T14:33:58.867537+00:00 app[web.1]: time.sleep(0.1) 2020-03-24T14:33:58.867537+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 242, in handle_chld 2020-03-24T14:33:58.867537+00:00 app[web.1]: self.reap_workers() 2020-03-24T14:33:58.867538+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 525, in reap_workers 2020-03-24T14:33:58.867538+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2020-03-24T14:33:58.867539+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> 2020-03-24T14:33:58.969807+00:00 heroku[web.1]: State changed from starting to crashed 2020-03-24T14:33:58.952866+00:00 heroku[web.1]: Process exited with status 1 2020-03-24T14:34:13.000000+00:00 app[api]: Build started by user anil8826467317@gmail.com 2020-03-24T14:35:19.446665+00:00 heroku[web.1]: State changed from crashed to starting 2020-03-24T14:35:19.179491+00:00 app[api]: Deploy 939b3c20 by user anil8826467317@gmail.com 2020-03-24T14:35:19.179491+00:00 app[api]: Release v10 created by user anil8826467317@gmail.com 2020-03-24T14:35:25.763617+00:00 heroku[web.1]: Starting process with command `gunicorn naac_portal.wsgi` 2020-03-24T14:35:28.545775+00:00 app[web.1]: [2020-03-24 14:35:28 +0000] [4] [INFO] Starting gunicorn 20.0.4 2020-03-24T14:35:28.546436+00:00 app[web.1]: [2020-03-24 14:35:28 +0000] [4] [INFO] Listening at: http://0.0.0.0:29141 (4) 2020-03-24T14:35:28.546595+00:00 app[web.1]: [2020-03-24 14:35:28 +0000] [4] [INFO] Using worker: sync 2020-03-24T14:35:28.551237+00:00 app[web.1]: [2020-03-24 14:35:28 +0000] [10] [INFO] Booting worker with pid: 10 2020-03-24T14:35:28.603149+00:00 app[web.1]: [2020-03-24 … -
How to LIMIT number of different choices in my model that user can save? - Python Django
I have model UserDraft. Inside that model I have pick_id with different choices represented in numbers when u go into Django Admin. I want each choice to be limited to max 5 times for each user to be picked. For example in this code I want to have user1, 1, hero1, user1, 1, hero2, etc....Also i would love to restrict that you cant pick same hero twice. models.py from django.db import models from users.models import User from heroes.models import Hero from django.core.exceptions import ValidationError class UserDrafts(models.Model): FIRST = "1" SECOND = '2' THIRD = '3' PICK_ID = [ (FIRST, 1), (SECOND, 2), (THIRD, 3), ] user_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_id") pick_id = models.CharField(max_length=20, choices=PICK_ID) hero_id = models.ForeignKey(Hero, on_delete=models.CASCADE) def save(self, *args, **kwargs): if self.__class__.objects.filter(user_id=self.user_id).count() >= 5: raise ValidationError('Maximum five picks are allowed per user') return super().save(*args, **kwargs) def __str__(self): return self.user_id.username class Meta: verbose_name = "UserDraft" verbose_name_plural = "UserDrafts" This save method that I used only limits user to pick more then 5 times. But I also want to be able to restrict choices for each choice to be picked 5 times per 1 user...So maximum number of picks will be 15. 5 pick_id`s will be 1(FIRST), 5 will be … -
Django REST framework: How to use multiple PKs in URL with class based views/serializer
I have two models (examples): class Container(models.Model): name = models.CharField(max_length=100) class ObjInContainer(models.Model): Container = models.ForeignKey(Container, on_delete=models.CASCADE) A Container can have N number of ObjInContainer. I'm trying to write a REST API to do two things: First: See all ObjInContainer from a single Container: # urls.py url(r'^container/(?P<container_id>\d+)/objects_in_container/$', ContainerObjectsListAPIView.as_view(), name='container_objects_list'), # views.py class ContainerObjectsListAPIView(ListAPIView): queryset = ObjInContainer.objects.all() queryset = queryset.prefetch_related('container') serializer_class = ContainerObjectsListAPIView # serializer.py class ContainerObjectsListAPIView(ModelSerializer): container = SerializerMethodField() class Meta: model = ObjInContainer fields = [ 'id', 'container', ] def get_container(self, obj): return str(obj.container.name) But this lists all ObjInContainer from ALL Container. How do I tell REST Framework that the Container it needs to get the ObjInContainer from is the one in the URL from <container_id> ? I suppose in views.py where I declare queryset = ObjInContainer.objects.all(), should really be queryset = ObjInContainer.objects.filter(container_id=container_id), but how do I access the <container_id> part of the URL in the view class? Any my second issue is how to detail a single ObjInContainer, by using two different IDs in the URL? # urls.py url(r'^container/(?P<container_id>\d+)/objects_in_container/(?P<obj_in_container_id>\d+)/$', ContainerObjDetailAPIView.as_view(), name='container_object_detail'), # views.py class ContainerObjDetailAPIView(RetrieveAPIView): queryset = ObjInContainer.objects.all() serializer_class = ContainerObjDetailSerializer # serializer.py class ContainerObjDetailSerializer(ModelSerializer): container = SerializerMethodField() class Meta: model = ObjInContainer fields = [ 'id', 'container', ] … -
Accessing HTTP content from an HTTPS server || HTTP request blocked
My Django application currently runs on HTTPS in the server. Recently i added a new functionality for which it has access another link to get JSON object which is HTTP link. Its working fine in the localhost but when I deploy it in the server, it is showing the following error. Site was loaded over HTTPS, but requested an insecure resource http link. This request has been blocked; the content must be served over HTTPS. Can someone please suggest a workaround to bypass this so that the new functionality runs smooth. -
MultiValueDictKeyError at /login/ "uname,
im working on an ecommmerce site with python mysql and django.During login i'm getting MultiValueDictKeyError at /login/ can someone review this ... This is my login page error occurs on the name "uname": <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <center> <form action="/login/" method="POST"> {% csrf_token %} <input type="text" name="uname" placeholder="username"><br><br> <input type="text" name="pass" placeholder="password"><br><br> <input type="submit" value="Login"> </form> </center> </body> </html> This is my views.py using POST method: from django.shortcuts import render, redirect, HttpResponse from django.http import HttpResponse from . models import * def home(request): return render(request,'index.html') def fn_login(request): v_username = request.POST['uname'] v_password = request.POST['pass'] try: login_obj = Login.objects.get(username=v_username,password=v_password) if login_obj.password == v_password: return render(request,'index.html') return HttpResponse('incorrect password') except Exception as e: print(e) return HttpResponse('invalid username') This is myapp urls.py: from django.contrib import admin from django.urls import path # importing views from views..py from .import views urlpatterns = [ path('index/',views.home), path('login/',views.fn_login,), ] -
Pulling data from MongoDB existing databas with Django(Djongo)
So i am working on a proyect with mongodb and django(djongo) and i have to use an already existing database(MongoDB compass) and i cant find the way to pull or import the information from MongoDB, already try with: python manage.py inspectdb > models.py and python manage.py inspectdb and when create the models.py is not with the database instead it pulls the default MongoDb, already try the Documentation of django and nothing works. Anyone got some info about it? PD: my app is totally empty and already configured the settings.py as the documentation on Django instruct. Thanks in advance. -
Attribute error 'QueryDict' object has no attribute '_meta'
I'm trying to send a post request from PostMan into my Django view and I'm getting this error. "AttributeError: 'QueryDict' object has no attribute '_meta'" From what I've gathered it has something to do with the form.save() as seen in traceba I've searched all over to find a solution or even a better way to achieve an image post from a external web client to a Django server. All help is very much appreciated. Traceback Capture.PNG form is valid Internal Server Error: /getimg/ Traceback (most recent call last): File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\decorators.py", line 50, in handler return func(*args, **kwargs) File "C:\Users\Gedit\Desktop\django\indivproj\getimg\api\views.py", line 21, in getimg form.save() File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\serializers.py", line 207, in save self.instance = self.update(self.instance, validated_data) File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\serializers.py", … -
How to manually edit the usercreationforms dropdown menu in html?
I have used usercreationform in forms.py to create form in html page. It will automatically create field by using {{form. field}} that is fine, but I want to do manual dropdown list in html from forms.py that is I want to edit dropdown form field in html page. forms.py class SignupForm(UserCreationForm): username = forms.CharField(label="Roll No", help_text="Enter Valid RollNo") name = forms.CharField(label="Candidate Name", max_length=150) dob = forms.DateField(label="Date") email = forms.EmailField(max_length=100, help_text='Required') department = forms.CharField(label="Department", widget=forms.Select(choices=CHOICES)) edc = forms.ChoiceField(label="EDC", widget=forms.Select(choices=COURSE)) class Meta: model = User fields = ("username","name", "dob", "email","department",'password1','password2') signup.html is my html page {% block content %} <form method="post"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-6"> {{ form.username | as_crispy_field }} </div> <div class="form-group col-md-6"> {{ form.name|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.dob | as_crispy_field }} </div> <div class="form-group col-md-4 mb-0"> {{ form.email | as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.department | as_crispy_field }} </div> <div class="form-group col-md-4 mb-0"> **<p><label >EDC:</label> <select> {% for choices in form.edc %} <option value="{{choices}}">""</option> <option value="{{choices}}">{{choices}}</option> <option value="{{choices}}">{{choices}}</option> <option value="{{c}}">{{choices}}</option> {% endfor %} </select> </p>** </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.password1 | as_crispy_field }} </div> <div class="form-group col-md-4 mb-0"> … -
Error while updating multiple objects using django rest_framework serializers
I am making API for an order which can have multiple foods. I am able to create it successfully but when I try to update with food id, I am getting an error like NoneType object has no attribute 'get', please help me out with a solution. Here is my code models.py class Order(models.Model): order_no = models.PositiveIntegerField(blank=True,null=True) class VegFood(models.Model): name = models.CharField(max_length=25,blank=True,null=True) price = models.CharField(max_length=25,blank=True,null=True) order = models.ForeignKey(Order,on_delete=models.CASCADE,blank=True,null=True,related_name="order") serializers.py class VegFoodSerializer(serializers.ModelSerializer): class Meta: model = VegFood fields = ['name','price'] class OrderSerializer(serializers.ModelSerializer): """ for multiple add items importinf serializers in Order """ veg_foods = VegFoodSerializer(many=True,required=False) nonveg_foods = NonVegFoodSerializer(many=True,required=False) starters = StarterSerializer(many=True,required=False) deserts = DesertSerializer(many=True,required=False) class Meta: model = Order fields = ['order_no','veg_foods','nonveg_foods','starters','deserts'] def create(self, validated_data): veg_food_validated_data = validated_data.pop('veg_foods',None) if veg_food_validated_data: for veg_food in veg_food_validated_data: veg_food_obj = VegFood.objects.create(order=orders,**veg_food) return orders def update(self, instance, validated_data): instance.order_no = validated_data.pop('order_no', instance.order_no) veg_food_validated_data = validated_data.pop('veg_foods',None) if veg_food_validated_data: for veg_food in veg_food_validated_data: veg_food_id = veg_food.get('veg_food_id') print(veg_food_id) veg_foods, created = VegFood.objects.get_or_create(order_id=instance.id,id=veg_food_id) veg_foods.name = veg_food_id.get('name',None) veg_foods.price = veg_food_id.get('price',None) veg_foods.save() instance.save() return instance My JSON body is : { "order_no":1, "veg_foods":[ { "veg_food_id":1, "name":curry1, "price":150 }, { "veg_food_id":2, "name":curry2, "price":120 }, { "name":curry2, "price":120 } ] } So object1 & object2 I am passing id so it will update 1st … -
Django, Cant import Module from an App into project urls.py
Hi so i am trying to import a module from app my (views.py) into the project urls.py. It is not letting me import from my app though. I tried butting '''from project.AppFolder import views''' but it says no module found names that. I put a init.py in my project folder to try that and that still didnt work. the folder layout is -ProjectFolder ---ProjectFolder -----urls.py ---AppFolder -----views.py