Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM error: FieldError: Cannot resolve keyword XXX into field
When I typing comds = Purchased.objects.filter(category_id = '1'), it thrown a error like this FieldError: Cannot resolve keyword 'category_id' into field. Choices are: comd_expire, comd_img_type, comd_name, id, player, player_id, purchase_time, status, and my table's fields are: my models is: I don't know why there has no category and category_id -
Is there any function in Django that tests if a field instance of a model is primary key?
In Django, is there a way (function) to test if a model field is primary key (pk)? For instance, my model is: class Gender(models.Model): name = models.CharField(max_length=50, primary_key=True) def __str__(self): return self.name Is there a function to test for name being primary key? -
Custom validation for formset in Django
I can't figure out how to make a custom validation for my formset. I'm trying to prevent users to select more than 12 times the same year, but when I print it, the cleaned_data comes in as a different dictionary for each form. I would like to have all forms grouped into 1 dictionary to check if one year appears more than 12 times, or to write this in a better way. My code: forms.py class SellerResultForm(forms.ModelForm): class Meta: model = SellerResult fields = ('month', 'year', 'result',) widgets = { 'month': forms.Select(attrs={'class': 'form-control',}), 'year': forms.Select(attrs={'class': 'form-control',}), 'result': forms.TextInput(attrs={'class': 'form-control',}), } def has_changed(self): #used for saving data from initial changed_data = super(SellerResultForm, self).has_changed() return bool(self.initial or changed_data) def clean(self): cleaned_data = super(SellerResultForm, self).clean() print(cleaned_data) # prints a set of dictionaries # {'month': 4, 'year': 2017, 'id': 1, 'result': 1000} # {'month': 5, 'year': 2017, 'id': 1, 'result': 1000} # {'month': 6, 'year': 2017, 'id': 1, 'result': 1000} views.py def seller_result(request, user_id): SellerResultFormSet = modelformset_factory(SellerResult, form=SellerResultForm, extra=1, max_num=1) queryset = SellerResult.objects.filter(seller=user_id,).order_by('year', 'month') formset = SellerResultFormSet(request.POST or None, queryset=queryset, initial=[ {'month': datetime.now().month, 'year': datetime.now().year, 'result': 1000,}]) if formset.is_valid(): instances = formset.save(commit=False) for instance in instances: instance.seller_id = user_id instance.save() context = { 'formset': … -
Extending Django filer image model by category field
I recently had problems with extending django filer, probably my knowledge about django is not sufficient yet. Basically what I would like to achieve is to extend django filer image model to be able to add category to images. Of course would be nice to have manytomany relation to category model. Could someone help me with this topic? my code (all in myPlugins app): models.py from filer.models.abstract.BaseImage class CustomImage(BaseImage): category = models.CharField(max_length=20, blank=True, null=True,) class Meta: app_label = 'myPlugins' admin.py from django.contrib import admin from filer.admin.imageadmin import ImageAdmin from myPlugins.models import CustomImage class CustomImageAdmin(ImageAdmin): pass CustomImageAdmin.fieldsets = CustomImageAdmin.build_fieldsets( extra_main_fields=('author', 'default_alt_text', 'default_caption', 'category'), extra_fieldsets=( ('Subject Location', { 'fields': ('subject_location',), 'classes': ('collapse',), }), ) ) admin.site.unregister(ImageAdmin) admin.site.register(CustomImage, CustomImageAdmin) in settings.py I've added: FILER_IMAGE_MODEL = 'myPlugins.models.CustomImage' and I'm getting an error: File ".../mysite/myPlugins/admin.py", line 27, in admin.site.unregister(ImageAdmin) File ".../venv/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 118, in unregister for model in model_or_iterable: TypeError: 'MediaDefiningClass' object is not iterable -
Extremely high CPU usage in Django
I am helping to develop a fairly complex web application with Django. However some pages are taking 10+ seconds to render. I can't seem to get to the bottom of why this is so slow. The Django Debug Toolbar shows that the bottleneck is clearly CPU, rather than the database or anything else, but it doesn't go into any further detail (as far as I can see). I have tried running a profiler on the system, but can't make head or tail of what is going on from this either. It only shows deep internals as taking up the vast majority of the time, especially <method 'poll' of 'select.poll' objects>, and other such functions as builtins.hasattr, getmodule, ismodule, etc. I've also tried stepping through the code manually, or pausing execution at random points to try to catch what's going on. I can see that it takes quite a long time to get through a ton of import statements, but then it spends a huge amount of time inside render() functions, taking especially long loading a large number of model fields--something in the order of 100 fields. None of what is happening looks wrong to me, except for the insame amount … -
Django ORM how to use datetime_trunc_sql
I am trying to truncate a datetime field to a date and afterwards use that filed for aggregation operations. I managed to that with date_trunc_sql function like this: truncate_date = con inner_query = "mytable.datetime AT TIME ZONE '%s'" % 'Europe/Amsterdam' truncate_date = conection.ops.date_trunc_sql('day', inner_query) queryset = queryset.extra({'day': truncate_date}) Now i saw that there is also a function datetime_trunc_sql that takes the timeozone as paramater but could not make that work. I tried: truncate_date = conection.ops.datetime_trunc_sql('day','mytable.datetime','Europe/Amsterdam') queryset = queryset.extra({'day': truncate_date}) It fails with the error StopIteration at api/v3/... and closes the connection at the second line: queryset = queryset.extra({'day': truncate_date}) Any ideas why? Thanks -
Django Rest Framework Browsable Api Specify display/value pair for foreign key field dropdown
My model is as (only pseudocode) class Country(models.Model): Name = models.CharField(max_length=255, unique=True) Code= models.CharField(max_length=3, unique=True) def label(self): return self.Name + " - " + self.Code def __unicode__(self): return str(self.label()) def __str__(self): return str(self.label()) class Mountain(models.Model): Country = models.ForeignKey(Country, related_name='mountain') I have successfully created a custom foreign key serializers.RelatedField that displays "Name - Code" on read but only accepts the Code on write. This works fine using Postman. However in my Browserble api I see a dropdown of countres displayed as "Name - Code" but when i post it posts the Name field of the model. I need send the Code field from the browsable api. How do I specify this and where. Primarily how do i specify what the display/value pair should be for a foreign key dropdown field in the browsable api -
Unit tests in Django: no such table error for class that does not exist
I have very annoying problem. If I run my unit tests in Django with python manage.py jenkins environment=local I get error: Creating test database for alias 'default'... Traceback (most recent call last): ... django.db.utils.OperationalError: no such table: connectors_testex1 My test database is sqlite3, real database is postgres. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': CONFIG['database']['db'], 'USER': CONFIG['database']['user'], 'PASSWORD': CONFIG['database']['password'], 'HOST': CONFIG['database']['host'], 'PORT': CONFIG['database']['port'], } } if 'test' or 'jenkins' in sys.argv: DATABASES['default'] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test', } Problem is that connectors_testex1 does not exist. Even if I do grep -r -i "connectors_testex1" /myproject/* it doesn't found anything. If I use same code on different machine (same git branch) it works normally. what could be the problem? -
Failed to check INSTALLED_APPS in django template
I am trying to load some HTML element in my django template, if a specific app is defined in my settings.py file. But it doesn't work. The if statement behaves like the app doesn't exist: {% if 'myapp.edit_data' in INSTALLED_APPS %} <p> dfsdfsdf </p> {% endif %} I also tried with other apps and I get the same behavior. What am I missing? -
Django AppRegistryNotReady when defining a model
I wanted to add the first model to an already working app, and now I can't start it because it always gives AppRegistryNotReady. This does only happen, if my model MailLog is child of models.Model. from __future__ import unicode_literals from django.db import models #class MailLog(models.Model): # like this, it crashes class MailLog(): # like this, it works # Field definitions The error occurs no matter what's inside the class, even if there is only a pass. However, I can import my models in the admin.py, and it crashes when I import from a file I called core.py. That file looks like this: import boto3 from botocore.exceptions import ClientError from django.template import loader from django.conf import settings from .templates import * from .models import MailLog -
django-mptt: test for consistency
I'm using django-mptt for my application and I found that a branch with no consistency between parent and left/right. So I launched .rebuild() to fix it. But the question is: is there a way to test if the tree is consistent? -
Django How to route to a js file from urlpattern
I want to route to a js file (may be static or dynamic). The js file has format same thing: (function() { var img = new Image, url = encodeURIComponent(document.location.href), title = encodeURIComponent(document.title), ref = encodeURIComponent(document.referrer); img.src = '%s/a.gif?url=' + url + '&t=' + title + '&ref=' + ref; })(); And from client I will run this script from header by: <script async="" src="https://localhost/a.js"> </script> without use staticfile, I think we can use it by urlpattern. But I don't know use for javascript file. -
How to join not relational model in django rest framework?
i have a problem about join not relational model in django rest framework. for example, i have two model : Model Category template class CategoryTemplate(models.Model): name = models.CharField(max_length=256) Model Commodity class Commodity(models.Model): name = models.CharField(max_length=255, default=None, null=False) Example Data: *category template id | name 1 | Pupuk 2 | Pestisida *commodity id | name 1 | Pisang 2 | Semangka my question is, with that model how to join that model to get the result like this ? cat_temp_id | cat_temp_name | comm_id | comm_name | category 1 | Pupuk | 1 | Pisang | Pupuk Pisang 1 | Pupuk | 2 | Semangka | Pupuk Semangka 2 | Pestisida | 1 | Pisang | Pestisida Pisang 2 | Pestisida | 2 | Semangka | Pestisida Semangka Please advice. Thank you. -
Creating a Table of Context from a list of dicts using Django templates
Say that I have the following dict list: fruits = [ {"Name": "Apple", "id": 1, "url": "/apple", "Desc": "Red or green skin with white flesh."}, {"Name": "Pear", "id": 2, "url": "/pear", "Desc": "Green fruit with white flesh."}, {"Name": "Coconut", "id": 3, "url": "/coco", "Desc": "Brown hairy shell with with flesh."} ] and it's passed to the context of a Django template via a view. How would I go about building a Table of Context that looks something Like this? A Apple Red or green skin with white flesh. C Coconut Brown hairy shell with with flesh. P Pear Green fruit with white flesh.. I was thinking of doing something like this: {% for fruit in fruits %} <B>{{ fruit.Name|first_letter_upper }}</B><BR> <A HREF="{{ fruit.url }}">{{ fruit.Name }}</A><BR> {{ fruit.Desc }}<BR> {% if not forloop.last %}<BR>{% endif %} {% endfor %} But then I would have to implement the custom filter "first_letter_upper". Not a big deal, but I'm just wondering if there's a simpler way to do that without having to use custom filters? -
django - extending User model for registration
I am really new to django. I have a model and 2 forms like this below extending the User model. The UserProfile is linked to the user model which would be where I have my extra field. I have seen numerous posts but still was't able to solve it. I would like to save the profile with additional parameters like the phone number stated below when the registration form is submitted, I have been spending hours trying to make it work, thanks a lot for your help in advance: class UserProfile(models.Model): user = models.OneToOneField(User) name = models.CharField(max_length = 50) phone_number = models.CharField(max_length=12) #In form.py class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2' ] def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user class RegistrationFormProfile(forms.ModelForm): phone_number = forms.CharField(max_length = 12) class Meta: model = UserProfile fields = [ 'phone_number', ] def save(self, commit=True): profile.phone_number = self.cleaned_data['phone_number'] if commit: profile.save() return profile #In views.py def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) profileForm = RegistrationFormProfile(request.POST) if form.is_valid(): user = form.save() if(profileForm.is_valid()): profileForm.save() return redirect('accounts/profile') else: return redirect('accounts/wrong') else: form … -
Static files are not loading in django1.11
I'm a newbie in django. I've been trying to develop a website with django1.11. But I got stuck at some point. The static files are not coming through the templates. Any help! settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'agr8w4(pcdz077#8n2ow1z8_@e-%6(evtw((-3g$&$_wf1&!@1' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'photo', ] 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 = 'pro.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,"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 = 'pro.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static", "static_root") STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static", "our_static" ), ] STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder' ) MEDIA_URL ='/media/' MEDIA_ROOT =os.path.join(BASE_DIR, "media_root") urls.py from django.conf import settings from django.conf.urls import include,url from django.conf.urls.static import static from django.contrib import admin from photo.views import home … -
Django REST Framework. How to handle FileNotFoundError error
When I make dumb from dev DB to local, I don't have files to show on my machine. Is some smart way to avoid this error without changing DB? Thank you. UPD My serializer: class ProductImageSerializer(serializers.ModelSerializer): image_size = serializers.IntegerField( source='image.size', required=False, ) image_name = serializers.SerializerMethodField( required=False, ) image = serializers.FileField(required=False) class Meta: model = ProductImage fields = ( 'id', 'image', 'product', 'is_main', 'image_size', 'image_name', ) -
White HTML page after redirection with Django CBV model
I'm getting an issue and I don't find a way to solve this problem. All seems to be fine, but it doesn't work. This is the process : I have a template with all informations about the object which is just created by Django form. I have a button which have to redirect to an other template taking account the object id but when I'm redirect to this template, I'm getting an html white page. This is my model : class Societe(models.Model): NumeroIdentification = models.CharField(max_length=30, null=True, verbose_name='Numero Identification physique', unique=True) Nom = models.CharField(null= False, max_length=30, verbose_name='Nom de Société') Etat = models.CharField(max_length = 30, choices = CHOIX_ETAT_SOCIETE, null=False, verbose_name="Etat") ... def get_absolute_url(self): return reverse_lazy('SocieteResume', kwargs={'id': self.id}) def __unicode__(self): return unicode (self.id, self.NumeroIdentification, self.Nom, ...) I have a first class which let to display created object in detail : class IdentitySocieteResumeView(LoginRequiredMixin, ListView) : template_name = 'Identity_Societe_Resume.html' model = Societe def get_context_data(self, **kwargs) : context_data = super(IdentitySocieteResumeView, self).get_context_data(**kwargs) id = self.kwargs['id'] societe = get_object_or_404(Societe, pk=id) obj = Societe.objects.filter (Nom=societe.Nom, SIRET=societe.SIRET, SIREN=societe.SIREN, Ville=societe.Ville) if obj: sc_obj = obj[0] ... return context_data With the associated template which has this button in order to redirect to the next template : <form method='POST' action="{% url 'SocietePDF' societe.id … -
Retrieve data on a django templates
I am having trouble to understand the principles of retrieving data in template. I understand very well how to do it from the Shell. But I always block on how to do it using class based view. I have a simple view : class ProjectDetailView(generic.DetailView, LoginRequiredMixin): #import pdb; pdb.set_trace() model = Project template_name = 'project_details.html' so in my template I easily retrieve data from the model Project like {{project.name}} or {{project.team_id}} But If I want I would like to show in my project detail data from other models, how can I do it ? Let assume I would like to show a list of all team members ? here are my models: class Team(models.Model): team_name = models.CharField(max_length=100, default = '') team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) members = models.ManyToManyField(MyUser, related_name="members") def __str__(self): return self.team_name class Project(models.Model): name = models.CharField(max_length=250) team_id = models.ForeignKey(Team, blank=True, null=True) project_hr_admin = models.ForeignKey('registration.MyUser', blank=True, null=True) candidat_answers = models.ManyToManyField('survey.response') -
Django-Allauth is getting failed to login the other users for Facebook Django Pyhton 2.7
Here is the scenario: I am trying to login or authenticate the user using the Django-allauth Application. I am using Django 1.11.5 and python 2.7 as environment for the application. I am getting stuck at the url: http://websiteIP:port/accounts/facebook/login/callback/?code=AQA2UQcbZ7GKyikNSV3rIRY3MxF6QcIsVrElIlSaN51Uhbz10qKtEuphoR1kj4CziEctuZbeXLOlCejMUqTP8yJOgm7NhS7QSTypyTU3eUVaHVY59cb6wdbUDihaRYgzU9WiwM9e1D52s_7XPMT8F3EgaPiowKjhdwzDltm58ZvgOj-P3GCfr8JZaHroWqukNPckhHw11uylfzjo8UIcDiCOjBD3Qs92DD1quTgqNsx9XX95smkXWVeHPhRG7M80X8jIeUa2JUOqPf3YoY5CAwluIN_f587GiEkQFZM9sCUQyK5Nc2r11cmCutlSVi2kHxSSH0oQKwiThs7s4OAbBRT0&state=9p3yt6ErhCRP#_=_ I have tried hard to check what can be the reason for this issue. I found that the people has always said that the application is trying to verify the email address. and some suggested to apply some EMAIL_HOST setting. I tried to set that. Have a look at my settings.py as below: SITE_ID = 1 LOGIN_REDIRECT_URL = '/' SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'SCOPE': ['email', 'user_posts', 'user_photos', 'user_about_me', 'user_likes', 'user_friends'], 'METHOD': 'oauth2', 'FIELDS': [ 'email', 'name', 'first_name', 'last_name', 'posts', 'about', 'picture.type(large)', 'likes', 'cover', 'taggable_friends.limit(1){name,picture.type(large){url},first_name}', ], 'LIKED_FIELD': [ 'link', 'name', # 'picture.type(normal){url}', ], 'EXCHANGE_TOKEN': True, # 'VERIFIED_EMAIL': True, 'VERSION': 'v2.10', } } ACCOUNT_LOGOUT_ON_GET = True EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'example@gmail.com' EMAIL_HOST_PASSWORD = 'password' I am now fed up, as I got nothing at the end. Kindly, suggest me what is the missing part. I have setup Django Alluth usong the GoDjango Tutorials -
django.db.utils.IntegrityError: duplicate key value violates unique constraint "auth_permission_pkey"
Got stuck I have an database in which when I try to make python manage.py migrate it's giving this error as follows: django.db.utils.IntegrityError: duplicate key value violates unique constraint "auth_permission_pkey" DETAIL: Key (id)=(241) already exists. following is whole error : Operations to perform: Apply all migrations: admin, auth, companyapp, contenttypes, djcelery, kombu_transport_django, loginapp, projectmanagement, recruitmentproject, sessions, smallproject Running migrations: No migrations to apply. Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/ubuntu/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 227, in handle self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan, File "/home/ubuntu/.local/lib/python2.7/site-packages/django/core/management/sql.py", line 53, in emit_post_migrate_signal **kwargs File "/home/ubuntu/.local/lib/python2.7/site-packages/django/dispatch/dispatcher.py", line 193, in send for receiver in self._live_receivers(sender) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/contrib/auth/management/__init__.py", line 83, in create_permissions Permission.objects.using(using).bulk_create(perms) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/db/models/query.py", line 443, in bulk_create ids = self._batched_insert(objs_without_pk, fields, batch_size) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/db/models/query.py", line 1080, in _batched_insert inserted_id = self._insert(item, fields=fields, using=self.db, return_id=True) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/db/models/query.py", line 1063, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1099, in execute_sql cursor.execute(sql, params) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) … -
Django 1.11 csrf_token dose not generate
I'm new in Django, When I try to use csrf, I didn't event see the csrfmidderwaretoken generate in html code. Please someone help me out:) blow is clips of my code: urls.py: `url(r'^register/$', register, name="register"),` views.py: def register(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] if not (User.objects.filter(username=username)): User.objects.create(username=username, password=password) User.save() return render(request, "register.html", {"status":True}) else: return render_to_response('register.html') register.html: Template Html Code Link And what shows out is this:Appearance on site . Django 1.11, Python3.6. Can somebody help me check this, much appreciated in advance. -
access to another model fields with foreign key in django admin
I have a contact us class in django model,that using "user_id" foreign key,in admin.py file,i want using userprofile data with user_id key,such as "name" filed,in userprofile model "user_id" is foreign_key too,how can do it? -
Is it a good idea to use 'GET' or 'POST' to retrieve an image from user for Flask Restful API (python)?
I am new to Restful API development. I am developing a Restful API (using python flask) which will accept an image array from Client. There are two ways I can get image from a user: one way is using 'GET' where the user will pass the image in URI. e.g. http://127.0.0.1:5000/api/example?image=[[1,2,3,4,5,6,7,8], [1,2,3,4,5,6,7,8]] another way is using 'POST' where the user will post the image through some sort of request library. Which is a better option? I am looking for answers in terms of security, performance, ease-of-use. -
How to add to REcaptcha to django login form
I need to integrate Google's REcaptcha to the standard django authentication system. I already have a working template which shows the reCaptcha. Now I need to integrate the validation against google's API endpoint. I found this tutorial which basically explains how to do it with generic forms. https://simpleisbetterthancomplex.com/tutorial/2017/02/21/how-to-add-recaptcha-to-django-site.html But how can I integrate this into the standard authentication mechanism of django? I guess, I need to implement and overload some function in my views.py file. But what would be that function?