Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to set choices in a form to a Select widget
I am wondering if someone could help to figure out how to set initial choices to a CharField which has Select widget applied on a form level without overwriting the Meta class data(such as verbose_name coming from model level)? My form looks like that: from django.forms.widgets import Select class AssessmentFormModelForm): def __init__(self, *args, **kwargs): super(AssessmentForm, self).__init__(*args, **kwargs) # Intial choices set here (DOESN'T work) self.fields['test_taker_report_uid'].choices = [('', 'Placeholder')] class Meta: model = Assessment fields = ( 'test_taker_report_uid', ) widgets = { 'test_taker_report_uid': Select2, } I in fact know that I can make it work by removing widgets from Meta and adding it as a: class AssessmentFormModelForm): test_taker_report_uid = ChoiceField( widget=Select, choices=[('', 'Placeholder')] ) def __init__(self, *args, **kwargs): but it is annoying cause it overwrites verbose_name which i have specified on a model level, which i want to keep intact. -
django-paypal showing page not found when trying to checkout
I was able to install django-paypal and also created a sandox account, but the problem is when i try to checkout the process-payment display no page found. I think this have to do with the view.py or maybe the Order. How do i make this work properly? Model.py: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) billing_address = models.ForeignKey('BillingAddress', on_delete=models.SET_NULL, blank=True, null=True) def __str__(self): return self.user.username def get_total(self): total = 0 for order_item in self.items.all(): total += order_item.get_final_price() return total Views.py: def process_payment(request): order_id = request.session.get('order_id') order = get_object_or_404(Order, id=order_id) host = request.get_host() paypal_dict = { 'business': settings.PAYPAL_RECEIVER_EMAIL, 'amount': '%.2f' % order.get_total().quantize( Decimal('.01')), 'item_name': 'Order {}'.format(order.id), 'invoice': str(order.id), 'currency_code': 'USD', 'notify_url': 'http://{}{}'.format(host, reverse('paypal-ipn')), 'return_url': 'http://{}{}'.format(host, reverse('shop:payment-done')), 'cancel_return': 'http://{}{}'.format(host, reverse('shop:payment-cancelled')), } form = PayPalPaymentsForm(initial=paypal_dict) context = { 'form': form, 'order': order } return render(request, 'process_payment.html', context) -
Django anonymous session issue
I have this anonymous session middleware: from __future__ import unicode_literals from importlib import import_module from django.conf import settings class AnonymousSessionMiddleware(): """This middleware is used for anonymous testing, creates an anonymous session. """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = None if not response: response = self.get_response(request) if hasattr(self, 'process_request'): self.process_request(request) return response def process_request(self, request): if not request.user.is_authenticated and not request.session.session_key: engine = import_module(settings.SESSION_ENGINE) request.session = engine.SessionStore() request.session.create() And in my View I want to get the session_key (session_key = request.session.session_key) but it always be None. I think the problem is in my middleware because the def process_request(self, request) method runs after the View. What would be the best solution to launch this method first to create a new session before the View function gets called? -
How to change two models using a single foreign key?
So I have a model Part which contains ConnectedTo, which is a models.ForeignKey('self'). This is supposed to function in the same way the naming suggests. If a part is connected to another part, it is listed. My problem comes when dealing with the first object created, and linking objects to parts not yet created. If I have a Part A, then it is connected to nothing because no other objects exist yet. Even though I know it is connected to B which doesn't exist yet. I can create B and refer it to the other part when I create it, but this does nothing to change the ConnectedTo value in A. I could easily write something to change both whenever something is added, but this system is designed to become quite large scale and I feel like I need a more automatic solution before it gets out of hand. -
save some information from form that is images and some other information
this is views.py each = seller(state=state,city=city,full_address=full_address,pro_img=out,username=userName, bedroom_no=bedroom_no,kitchen_img=kithen_img,swimming_img=swimming_img,phone=phone ,email=email,price=price,floor=floor,squre=squre,gerden_img=garden_img) but a problem is occur "getattr(): attribute name must be string" now what i do -
How Do I open different views based on url in django
I'm just starting to use django so bear with me. I'm currently trying to open different template based on the url I got , for example path("<int:pk>",views.OptionView.as_view(),name = 'eachoption') What I want to do is to open a different view based on the value of the pk I got , I've searched for a while but still got no luck, can anyone help me ? :/ -
Python - Multiple user types implementation in Dajngo 2.2
I'm working on a project using Python(3.7) and Django(2.2) in which I have to implement four types of users as (1): Personal - Below 18 (2): Personal 18 or Above (3): Coach (4): Parent, each user will share some basic fields like First & Lat name, Email, Gender, Account type but also will have different permissions, dashboards and functions and need to provide different signup forms but one login form. Along with that I also need to use the Email as the username for this project. what is a good and scalable approach? any resource or tutorial links will be appreciated. and how can I utilize django-allauth in this scenario? and here's how I was thinking to implement this: class BaseUser(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) is_personal_above_18 = models.BooleanField(default=False) is_personal_below_18 = models.BooleanField(default=False) is_parent = models.BooleanField(default=False) USERNAME_FIELD = 'email' def __str__(self): return self.email + '/s account' class PersonalAccountAbove18(BaseUser): user = models.OneToOneField(BaseUser, on_delete=models.CASCADE, primary_key=True) customer_id = models.BigIntegerField(default=generate_cid()) class PersonalAccountBelow18(BaseUser): user = models.OneToOneField(BaseUser, on_delete=models.CASCADE, primary_key=True) customer_id = models.BigIntegerField(blank=False) class ParentAccount(BaseUser): user = models.OneToOneField(BaseUser, on_delete=models.CASCADE, primary_key=True) customer_id = models.BigIntegerField(default=generate_cid()) The reason to use customer_id in each model is because later we need to connect different accounts, for example if someone wants to create an as … -
How to deploy static files in Django before hosting it anywhere?
I have a Django application which needs to be deployed. Currently, I am not using Heroku or a Linux server to deploy it. However, I am trying to follow along with the Django checklist and ensure whether if it's ready to be deployed. I had done the following in my settings.py module: Set DEBUG = False Allowed_Hosts = ['*'] STATIC_ROOT = os.path.join(BASE_DIR,"staticfiles") This is my settings.py module: """ DJANGO PROJECT """ 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.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'SECRET KEY STORED IN ENVIRON VARIABLE' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'main.apps.MainConfig', #placing the Django app here. 'crispy_forms', 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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 = 'main.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'main.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { … -
implementing notification on a django rest api
While building my API, I didn't think about the logic behind notifications. Please, How do I solve a problem like this on a potentially big project? let us assume I have the code below: model.py class Showcase(models.Model): title = models.CharField(max_length=50) description = models.TextField(null=True) skill_type = models.ForeignKey(Skill, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name="Showcases") content = models.TextField(null=True) created_on = models.DateTimeField(auto_now=True) updated_on = models.DateTimeField(auto_now_add=True) voters = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="upvotes") slug = models.SlugField(max_length=255, unique=True) serializer.py class ShowcaseSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField(read_only=True) created_on = serializers.SerializerMethodField(read_only=True) likes_count = serializers.SerializerMethodField(read_only=True) user_has_voted = serializers.SerializerMethodField(read_only=True) slug = serializers.SlugField(read_only=True) comment_count = serializers.SerializerMethodField(read_only=True) class Meta: model = Showcase exclude = ['voters', 'updated_on'] def get_created_on(self, instance): return instance.created_on.strftime("%d %B %Y") def get_likes_count(self, instance): return instance.voters.count() def get_user_has_voted(self, instance): request = self.context.get("request") return instance.voters.filter(pk=request.user.pk).exists() def get_comment_count(self, instance): return instance.comments.count() view.py # SHOWCASE APIView class showcaseCreateViewSet(generics.ListCreateAPIView): ''' Create showcases view. user must be logged in to do this ''' queryset = Showcase.objects.all() serializer_class = ShowcaseSerializer permission_classes = [IsAuthenticatedOrReadOnly] def perform_create(self, serializer): serializer.save(user=self.request.user) class ShowcaseLikeAPIView(APIView): ''' Can like(post) and unlike(delete) the showcases, must be authenticated to do this ''' serializer_class = ShowcaseDetaiedSerializer permission_classes = [IsAuthenticated] def delete(self, request, slug): showcase = get_object_or_404(Showcase, slug=slug) user = self.request.user showcase.voters.remove(user) showcase.save() serializer_context = {"request": request} serializer = self.serializer_class(showcase, context=serializer_context) return … -
In Django rest framework: GDAL_ERROR 1: b'PROJ: proj_as_wkt: Cannot find proj.db '
I am using the versions for my project: Django==2.2.7 djangorestframework==3.10.3 mysqlclient==1.4.5 In my database I work with geometric types, and for this I have configured the library: GDAL-3.0.2-cp38-cp38-win32 To run this library, I have to include these variables in the django properties file: GEOS_LIBRARY_PATH GDAL_LIBRARY_PATH Now on my models, I do the following import: from django.contrib.gis.db import models For types like: coordinates = models.GeometryField (db_column = 'Coordinates', blank = True, null = True) It seems that the queries work correctly, but when creating a new element, I get the following error: GDAL_ERROR 1: b'PROJ: proj_as_wkt: Cannot find proj.db ' But after this error, the object is persisted correctly in the database. I would like to know how to solve this error. I have not found information on the network, I have only tried to declare a new variable in the DJANGO properties file: PROJ_LIB = 'APP / backend / env / Lib / site-packages / osgeo / data / proj / proj.db' But the error still appears, and you may have problems in the production environment in an OpenSuse image Why can't you find proj.db? How do I solve it? -
How to use query value from [[def get_queryset(self)]] and use in all classes
search.html file <div class="content-section"> <h1 class="mb-3">{{ user.username }}</h1> <form method="GET" action="{% url 'doctor:search' %}"> <input name ="q" value="{{request.GET.q}}" placeholder="search.."> <button class="btn btn-success" type="submit"> Search </button> </form> </div> VIEWS.py How can i use [[query = self.request.GET.get('q')_]] once and use it's result in other class? Currently i'm using search.html repeatedly to get query value for all other classes. Where value of query is same for all the classes. class SearchResultsView(ListView): model = User template_name = 'all_users/doctor/search.html' def get_queryset(self): query = self.request.GET.get('q') object_list = User.objects.filter(Q(username__icontains=query)) return object_list class PostCreateView(LoginRequiredMixin, CreateView): template_name = 'all_users/doctor/post_form.html' model = Post fields = ['title', 'content', 'comment'] def form_valid(self, form): query = self.request.GET.get('q') form.instance.author = self.request.user form.instance.patient = User.objects.get(username=query) return super().form_valid(form) -
Best way to change relation of django group and user model?
The default django User and Group model has ManyToMany relationship but I want to change it OneToOne Relation.Is it possible ?What might be the right way to do this? models.py class Group(models.Model): name = models.CharField(max_length=255) permissions = models.ManyToManyField(Permission) user = models.OneToOneField(User,on_delete=models.CASCADE) -
Can't use Javascript in Django
I tried to use java script in django, by following all the instructions and making the necessary changes in the settings.py file as well as using {% load static %} in my .html file. The CSS loads perfectly, but the .js file in the static/js folder does not. {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'css/calcu.css' %}"> </head> <form id="calci_form" method="get" action="operation"> <select name="vehicle" id="veh" onChange="hideShow(this.value)"> <option id="ve1" value="none" name="Select" selected="selected"></option> <option id="ve2" value="2">17 </option> <option id="ve3" value="3">18 </option> <option id="ve4" value="4">19 </option> <option id="ve5" value="5">20</option> <option id="ve6" value="6"> 21 </option> </select> <select name="power" id="pwr" onchange="showHide()"> <option id="pw1" value="none" name="Select" selected="selected"></option> <option id="pw2" value="A">A</option> <option id="pw3" value="B">B </option> <option id="pw4" value="C"> C</option> <option id="pw5" value="D">D</option> <option id="pw6" value="E"> E</option> </select> <label class="l1">X</label><input type="text" name="num1" class="tb1" value="{{fvalue}}"> <label class="l2">Y</label><input type="text" name="num2" class="tb2" value="{{svalue}}"> <label class="l3">Z</label><input type="text" id="txt" class="tb3" name="user_input" value={{result}}> <input type="submit" name="sym" class="btn1" value="Calculate"> <!-- <input type="submit" name="mul" class="btn2" value="Calculate"> --> </form> </html> <script src="{% static 'js/script.js' %}"> </script> This is my html file. my js file looks like this function showHide(){ alert(YOO) var x = document.getElementById("veh").options.length var v = document.getElementById("veh") var val = document.getElementById("pwr").value if(v.value == "none"){ return 0 } for(i = 0; … -
Hello, i need a help , i have got error when i install mysqlclient to ubuntu 18.04, my steps of install in down
My Steps 1)python3 -m venv env 2)source env/bin/activate 3)sudo apt-get install python3.7-dev or python3.8 never mind i tried 4)sudo apt-get install libmysqlclient-dev 5)pip install django mysqlclient error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Command "/home/dastan/projects/crud_add_book/env/bin/python3 -u -c "import setuptools, tokenize;file='/tmp/pip-build-a6zmf3am/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-eaynvhxp-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/dastan/projects/crud_add_book/env/include/site/python3.6/mysqlclient" failed with error code 1 in /tmp/pip-build-a6zmf3am/mysqlclient/ -
Ping from server (Ubuntu,Nginx,Gunicorn,Django)
I'm developing an app for local use and it needs to communicate with PLC and other devices in local network. Before sending data to PLC I need to know whether it is present in the network, so i tried to use ping. It all worked fine, while developing the app on Windows. Now when the app is on server I'm getting: "[Errno 1] Operation not permitted, /usr/lib/python3.6/socket.py in init, line 144", when trying to use pythonping library from my Django app. Is there some way to change permissions for the app, to make it ping. Or maybe there is some other way to check if some device is present? -
Gunicorn not starting throwing gunicorn.service: Failed with result 'exit-code'. error
I'm trying a deploy simple Django application on DigitalOcean by following this link I follow every work step by step and successfully run that project via Python manage.py runserver were it's not throwing any error but when I try to implement it with gunicorn its throw following error gunicorn.service: Failed with result 'exit-code'. Here is my following configuration sudo nano /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target sudo nano /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/myprojectdir ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application [Install] WantedBy=multi-user.target sudo systemctl status gunicorn.socket ● gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled) Active: active (listening) since Tue 2019-11-26 07:39:39 UTC; 12min ago Listen: /run/gunicorn.sock (Stream) CGroup: /system.slice/gunicorn.socket Nov 26 07:39:39 POS systemd[1]: Listening on gunicorn socket. When I try to start gunicorn it's throwing this error sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Tue 2019-11-26 07:39:43 UTC; 13min ago Process: 718 ExecStart=/home/pos/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock pos.wsgi:application (code=exited, status=1/FAILURE) Main PID: 718 (code=exited, status=1/FAILURE) Nov 26 07:39:43 POS gunicorn[718]: Arbiter(self).run() Nov 26 07:39:43 POS gunicorn[718]: File … -
User creation form in Django
I am taking online Djago class and have no one to ask for help. I would appreciate to get any help and tips. I am learning creating forms (login/singup). So far i did in models.py from django.db import models from django.contrib import auth class User(auth.models.User,auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) In forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm class UserCreateForm(UserCreationForm): class Meta: fields = ('username','email','password1','password2') model = get_user_model() def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = 'Display Name' self.fields['email'].label = 'Email Address' I want to add addtional firelds as surname , however when i add 'surname' in class meta in fields (forms.py) i get error, however the online training says i can easily add additional fields. Could you please tell what i am doing wrong and how i can add this field? -
Log into Chrome Extension without OAuth2
I'm wondering if it's possible to set up secure login authentication in a Chrome extension without OAuth2. I'm considering setting it up as follows: On opening the extension, send a POST to server which returns the CSRF token JavaScript inserts the token into the usual login form (as in Django template) [steps 1 and 2 replace the usual Django template rendering] User provides username and password and submits the form Success/Fail JSON response is returned and handled appropriately CSRF token is stored as a cookie (or in browser storage that Chrome extensions use) to enable automated login until it expires Would be great to hear possible problems/corrections to this approach as well as pointers to relevant resources! -
how to sum data according to date, year and some other category in django
I am new in django and i am stuck in this situation. I am adding student points according to category. Now I am want to show point according to category and month wise.I have attached following image as my expected result. I have tried annotate function but i am not able to solve this problem. Expect Result Models from django.db import models from datetime import datetime # Create your models here. class Teacher(models.Model): full_name=models.CharField(max_length=50) username=models.CharField(max_length=50) password=models.CharField(max_length=50) def __str__(self): return self.full_name class Student(models.Model): classes_name=( ('nur','Nursery'), ('lkg','LKG'), ('ukg','LKG'), ('1','1'), ('2','2'), ('3','3'), ('4','4'), ('5','5'), ('6','6'), ('7','7'), ('8','8'), ('9','9'), ('10','10'), ) full_name=models.CharField(max_length=100) roll_no=models.CharField(max_length=20) class_name=models.CharField(max_length=20,choices=classes_name) def __str__(self): return self.full_name+' '+self.class_name class PointCategory(models.Model): category_name=models.CharField(max_length=100) def __str__(self): return self.category_name class StudentPoint(models.Model): stu_id=models.IntegerField(null=True) teacher_id=models.IntegerField(null=True) point_cat=models.IntegerField(null=True) points=models.IntegerField(null=True) add_date=models.CharField(max_length=50,null=True) assign_date=models.DateTimeField(default=datetime.now) View Code for report def report(request,stu_id): decoded_hand = json.loads(request.session['teacherData']) teach_id=decoded_hand[0]['pk'] month_year=StudentPoint.objects.filter(stu_id=stu_id,teacher_id=teach_id).annotate(month=TruncMonth('assign_date'),year=TruncMonth('assign_date')).values('month','year').annotate(total_points=Sum('points')) all_category=PointCategory.objects.all() return render(request,'teacher/report.html',{ 'month_year':month_year, 'categories':all_category, 'stu_id':stu_id, }) -
Set Index Name in Django with db_index=True
Can I set my own index name when setting index using db_index=True in Django models? -
Adding pagination on searched data in django using ajax call
I am trying to do pagination on the searched data but when clicked on the pagination option like on clicking second page i am not able to recieve the value of q and it throws error. -
How do you install Django & PIP?
I am having a nightmare tonight, I want to start learning some Django but I am running into quite a few problems while installing it. I am following these tutorials - https://www.youtube.com/watch?v=UmljXZIypDc / https://www.youtube.com/watch?v=MEcWRk9w0t0 I installed Python 3.7.2 and confirmed the installation by typing 'python --version' into Terminal/Command Prompt. I typed 'pip --version' into CMD and got this message in return "'pip' is not recognized as an internal or external command, operable program or batch file." this is where I am stuck, I cannot continue any longer without completing this step, could anyone tell me where I am going wrong? Thank you -
Console log of AJAX data is my html code?
I am trying to transfer data through an ajax request. I want to transfer the contents of the input field. But output of console.log("ok" + data) is "ok" + all my html code, although output of console.log("ok" + formData) is that value i need. respectively, in the Django view variable q = None <input id="search" name="q" type="text" class="form-control" placeholder="Поиск"> <input name='submit_s' id='search_btn' type='button' value='poisk' /> jQuery(document).ready(function($){ $("#search_btn").click(function () { var formData = $('#search').val(); $.ajax({ type: "GET", url: "search/", data: { q: formData, }, processData: false, dataType: "text", cache: false, success: function (data) { if (data != ''){ console.log("ok" + data); } else { console.log("no"); } }, failure: function(data){ console.log("FAIL"); console.log(data); }, }); }); }); -
Django circularDependencyError
from django.db import migrations import xlrd def load_gm_options(apps, schema_editor): GMOptions = apps.get_model('sendmails','GMOptions') gm_filename = "../GMOptions.xlsx" gm_workbook = xlrd.open_workbook(gm_filename) for row in range(1,gm_workbook.sheet_by_index(0).nrows): GMOptions.objects.create(GMOptionText = gm_workbook.sheet_by_index(0).cell_value(row,0),GMOptionTextTranslation = gm_workbook.sheet_by_index(0).cell_value(row,1)) class Migration(migrations.Migration): dependencies = [ ('sendmails','0001_initial'), ] operations = [ migrations.RunPython(load_gm_options), # migrations.RunPython(load_item_list) ] I'm trying to pre-populate my models with some data but when I run python manage.py migrate. I got an error saying circularDependencyError, I tried removing the ('sendmails','0001_initial') but I will get an error saying no installed app with label. Below are all the tracebacks Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\migrate.py", line 87, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\loader.py", line 275, in build_graph self.graph.ensure_not_cyclic() File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\graph.py", line 274, in ensure_not_cyclic raise CircularDependencyError(", ".join("%s.%s" % n for n in cycle)) django.db.migrations.exceptions.CircularDependencyError: sendmails.0001_initial -
Django request method always return GET
@csrf_exempt def get_request(request): return JsonResponse({"method":request.method}) Postman POST result { "method": "GET" } I try to detect request method, but no matter what request I used, It always return GET anyone know where is the problem?