Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Once set Username=None. it is not a undo able after migrations + migrate
class User(AbstractUser): name = models.CharField(max_length=255, null=True) email = models.CharField(max_length=255, unique=True) password = models.CharField(max_length=255) username= None status = models.IntegerField(null=True, blank=True, default=2) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] After migrate in this i lost username field and i cannot get this field back also check my migration file operations = [ migrations.RemoveField( model_name='user', name='username', ), ] what should i do? to get back my username field again. Thanks -
modify the field-labels in auth_views.LogInView
I'm trying to make the user log in using email instead of username, thus I have created the following register-view def register(request): if request.method=="POST": #post request form = UserRegisterForm(request.POST) if form.is_valid(): form.instance.username=form.cleaned_data["email"] form.save() messages.success(request, "Your account has been created!") return redirect("login") else: form = UserRegisterForm() return render(request,"users/register.html",context= {"form":form}) which seems to work fine. I have seen people create their own ModelBackEnd classes but I cant see any issues doing it this way (please let me know, if this for some reason does not work?). The problem is, using the LoginView the field says Username and I want to change the saying to Email. Is there a way to do that? -
Retry a Huey task when something fails
Hi we are using Python Huey https://pypi.org/project/huey/1.1.0/ on a django project for running our background task, we are use it as a decorator @task() on some functions. To be more precise we are importing the library the following way: from huey.contrib.djhuey import task So, on our functions, that are executed by this task, in some cases we have database connections. If for some reason this task fails, for example, today we had a database issue that the connections to the database were closing (this is an issue that we have to figure out why this connections were closing). As you may imagine the task doesn't finish it's job due to the database connection. My question is: Is there any way, that we can configure this Huey task to retry the execution. Let's say, retry 5 times with 2 seconds between each retry ? -
How do query a query without getting an empty set in Django/python?
For instance, using Django/python I have queried data from a mysql db to a variable. When the variable is printed out in the terminal I can see the data in the query set. Now I want to run a second query on the first query set that is in the variable, but it returns an empty set. I have tried many things. Any help at all is much appreciated. -
github social login in django
I am trying to do social login through GitHub in Django and everything is working fine. when I click on login with GitHub it redirects to my GitHub login page. when I provide credentials and it redirects me to the home page of my website. Now it should display the username of my github's profile but it is not showing it to me. what could be the problem? I am going to display all of the code which I wrote for social login via github. UserAccounts/views.py: from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate, logout, login # Create your views here. # @login_required # it is being used here to restrict Anonymous users def home(request): return render(request, 'home_page.html') # @login_required # it is being used here to restrict Anonymous users to access thehome page without being authenticated def github_login(request): if request.user.is_authenticated: return render(request, 'home_page.html') else: return render(request, 'github_auth_login.html') def github_logout(request): return True UserManagement/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('UserAccounts.urls')), path('oauth/', include('social_django.urls')), ] UserAccounts/urls.py: from django.urls import path from django.contrib.auth import views as auth_views # for authentication from . import views as auth_views # importing views from … -
Filter a field not in the model in Graphene?
I have a model GroupCode that has a OneToOne to Rol, and i want to filter rol by one of the fields in GroupCode(GroupCode is the one with the OneToOneField), i have searched a little, but many examples and questions about this seem to mention how to filter found on the model, but not ones defined on the type, like enabled in this case, this is an example of my schema: class RolType(ModelType): class Meta: model = Group interfaces = [graphene.relay.Node] connection_class = CountableConnection permissions = ['security.view_group'] filter_fields = { 'name': ['exact', 'icontains', 'istartswith'] } enabled = graphene.Boolean() def resolve_enabled(self, info): return f"{GroupCode.objects.get(group=self.id).enabled}" class Query(graphene.ObjectType): rol = graphene.relay.Node.Field(RolType) roles = DjangoFilterConnectionField(RolType, enabled=graphene.Boolean()) Does anyone knows how to filter based on this enabled field? -
DRF- Custom User changes never migrate
I made the mistake of not using a custom user model for the first migration and I paid the price by having to delete all the migrations and makemigrations and migrate again as I switched the project to use my custom user. # models.py """ Changes are never picked by makemigrations """ from django.contrib.auth.models import AbstractUser from django.db import models from .managers import CustomUserManager class User(AbstractUser): username = models.CharField(max_length=120, unique=True, blank=False, validators=[MinLengthValidator(2)]) email = models.EmailField('Email Address', unique=True, blank=False) FCM_ID = models.CharField(max_length=300, blank=True) def __str__(self): return self.username Everytime I made any changes to the custom user, I have had to delete all migrations related files and apply migrations again just to get past the errors- this SO answer and this. Now I realized that I needed a newer change, but migrations are not detected after changing the User model. The only solution I have is to delete the migrations again! So far I have done this chore like 5 times and I am tired, what am I doing wrong? I have tried python3 manage.py makemigration <app_name>, and of course, the custom user model is defined in settings.py using AUTH_USER_MODEL. -
Populating Two Fields of one model based on fields in another model
I have the following models from django.db import models class Program(models.Model): title = models.CharField(max_length=190) block_time = models.TimeField(default="00:00:00") block_time_delta = models.DurationField(default="00:00:00") running_time = models.TimeField(default="00:00:00") running_time_delta = models.DurationField(default="00:00:00") remaining_time = models.TimeField(default="00:00:00") remaining_time_delta = models.DurationField(default="00:00:00") def __str__(self): return f"{self.pk} : {self.title}" class Segment(models.Model): program_id = models.ForeignKey(Program, on_delete=models.CASCADE, related_name='segments', #new link to Program ) sequence_number = models.DecimalField(decimal_places=2,max_digits=6,default="0.00") title = models.CharField(max_length=190) length_time = models.TimeField(null=True,default=None, blank=True) length_time_delta = models.DurationField(default="00:00:00") def __str__(self): return f"{self.title}" The form to create a program would allow you to enter a block time, but the other times are calculated based on the segment(s). The form(s) would have a program create/update function, and the segment form would have both the program info, and the ability to add one or more segment(s) on it. So, if I had a program that was an hour long (block_time = 1 hour), and two segments that were 28 minutes, then on the Program screen the Duration would be 1 hour, running time 56:00 min(calculated), and remaining time 4 minutes (calculated). Note at Program creation the user only enters Block Time, so at first the remaining time and the running time will be zero because there are no segments created yet. The Segment section(s) would not only have … -
How to include Parentalkey for django admin?
I have a Clusterable model along with a parental key relationship. The clusterable model is an "Order" model with the parental relationship from "OrderItem". The related name is "items". How can I include it in the django admin panel? For Order model class OrderAdmin(admin.ModelAdmin): fields = ["items"] # from (OrderItem model) but doesn't appear search_fields = ['id', 'user'] list_display = ('user', 'full_name', 'ordered', 'paid', 'total_to_pay') list_filter = ('ordered', 'paid',) -
instance data not loaded in template udpateview fields
This is my models: class User(AbstractUser): """Default user for awesomeinventory.""" is_organisor = models.BooleanField(default=True) is_agent = models.BooleanField(default=False) is_associatetoCompany = models.BooleanField(default=False) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) def __str__(self): return self.user.username class Agent(models.Model): FUNCTIONS = Choices( (1, 'Procurement', _('Procurement')), (2, 'Request_User', _('Request')), (3, 'Receptionist', _('Receptionist')), ) user = models.OneToOneField(User, on_delete=models.CASCADE) organisation = models.ForeignKey(UserProfile, on_delete=models.CASCADE) role = models.PositiveSmallIntegerField( choices=FUNCTIONS, default=FUNCTIONS.Request_User, ) def __str__(self): return self.user.email Agent form is: FUNCTIONS = Choices( (1, 'Procurement', _('Procurement')), (2, 'Request_User', _('Request')), (3, 'Receptionist', _('Receptionist')), ) class AgentModelForm(forms.ModelForm): role = forms.ChoiceField(choices=FUNCTIONS, widget=forms.Select, label='Role') class Meta: model = User fields = ( 'email', 'username', 'first_name', 'last_name', 'role', ) my views.py: class AgentUpdateView(OrganisorAndLoginRequiredMixin, UpdateView): template_name = "agents/agent_update.html" form_class = AgentModelForm def get_success_url(self): return reverse("agents:agent_list") def get_queryset(self): return Agent.objects.all() I'm working on Agent and I've no issue to create an agent, view details of an agent. I'm using crispy form and generic views. My update view template is: {% extends "base.html" %} {% load tailwind_filters %} {% block content %} <form form method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="w-full text-white bg-blue-500 hover:bg-blue-600 px-3 py-2 rounded-md">Submit</button> </form> {% endblock content %} In this form all fields stay empty except role. When I look at what … -
"null value in column violates not-null constraint" When saving Django Form
I am getting the following error in my code: "null value in column "bbso_record_id_id" of relation "sos_categorytoolsandequipment" violates not-null constraint DETAIL: Failing row contains (1, 1, , null)." The thing this, the code I have works with SQLlite but since I upgraded to Postgress all of a sudden it breaks and if I go back to SQllite it works again. I realize that the problem is with the OneToOne relationship but I am not sure how to retify it. It seems like my BBSO_Record has to save and get an id to pass to the OneToOne field first. But the problem is it works in SQLlite. This is my code and any assistance will be greatly appreciated. MODELS from django.db import models from django.db.models.deletion import CASCADE from django.core.validators import RegexValidator, MinValueValidator, MaxValueValidator #from django.db.models.enums import choices from django.utils import timezone from django.urls import reverse # page 138 Django for Beginneers from django.conf import settings # from django.utils import timezone from django.utils.timezone import now class BBSO_Records(models.Model): COMPANY_OR_CONTRACTOR = ( ('company', 'Company'), ('contractor', 'Contractor'), ) severityLevel = ( ('1', 'Level 1'), ('2', 'Level 2'), ('3', 'Level 3'), ) severity_level = models.CharField(max_length=6, default= 3 , choices=severityLevel) date_recorded = models.DateField() observer_name_ID = models.ForeignKey(settings.AUTH_USER_MODEL , … -
How to annotate in a model the agregates from other model
I need some help for making queries in my three models. The first is Cyclist, with fields like number (pk), name, birthday, etc. The second model is Classification with id (pk), type of classification, stage number, number(foreign key) and points. The first query I need to make is to get for every cyclist the total points in every stage number. My option is: puntos=Corredor.objects.values('dorsal','etapa').aggregate(total_puntos=Sum('puntos') After that, I have another model for Team. A team is a group of cyclist selected by a client. I want to get for every team the total sum of the points of the cyclists who form that team, but in this case I don't know how to use the query puntos in the new query for annotate. Maybe: team_points=Equipo.objects.annotate(F(Sum(lid__dorsal__puntos))+(Sum(lid2__dorsal__puntos))+...........))) Thanks in advance for the help. These are the models: class Corredor (models.Model): dorsal=models.IntegerField(primary_key=True) tipo=models.CharField(max_length=50) nombre=models.CharField(max_length=50) f_nacimiento=models.DateField(default=1/1/1975) nacimiento=models.IntegerField() categoria=models.CharField(max_length=50) pais=models.CharField(max_length=50) equipo=models.CharField(max_length=50) nombre_equipo=models.CharField(max_length=50) lid=models.BooleanField() gre=models.BooleanField() jor=models.BooleanField() giro=models.BooleanField() tour=models.BooleanField() vuelta=models.BooleanField() abandono_giro=models.IntegerField(default=0) etapa_aban_giro=models.IntegerField(default=0) abandono_tour=models.IntegerField(default=0) etapa_aban_tour=models.IntegerField(default=0) abandono_vuelta=models.IntegerField(default=0) etapa_aban_vuelta=models.IntegerField(default=0) class Meta: ordering=['nombre'] def __str__(self): return self.nombre class Equipo (models.Model): alias=models.CharField(max_length=50, primary_key=True) lid1=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid1", on_delete=models.CASCADE) lid2=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid2", on_delete=models.CASCADE) lid3=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid3", on_delete=models.CASCADE) lid4=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid4", on_delete=models.CASCADE) gre1=models.ForeignKey(Corredor,limit_choices_to={'gre':True, 'giro':True, 'tipo': "Rider"}, related_name="gre1", on_delete=models.CASCADE) … -
I can't post in django
-I can't post in django, because when I import an image it doesn't work for me. it tells me that there's no file selected but I selected one. here's my models.py file this is the post model that I created class Post(models.Model): publisher = models.ForeignKey(User,on_delete=models.CASCADE) caption = models.CharField(max_length=100) date_created = models.DateTimeField(default=timezone.now()) image = models.ImageField(upload_to="post_images") def __str__(self): return self.caption -here's the forms.py file for the Post model: from django import forms from .models import Post class CreatePostForm(forms.ModelForm): class Meta: model = Post fields = ['caption','image'] -here's the Publish function in views.py file wich implements the logic for my publish feature: @login_required def Publish(request): if request.method == "POST": form = CreatePostForm(request.POST,request.FILES) if form.is_valid(): form.publisher = request.user form.save() return redirect("home") else: form = CreatePostForm() return render(request,"posts/publish.html",{ "form":form, }) int the urls.py file: from django.urls import path from . import views urlpatterns = [ path('publish/',views.Publish,name="publish"), path('',views.home,name="home"), ] and here's in html template: {% extends "users/base.html" %} {% load crispy_forms_tags %} {% block title %}create{% endblock title%} {% block content %} <div class="container-fluid"> <div class="row"> <div class="col-sm-6 col-md-5 authentification"> <div class="form-header"> <h1> publish </h1> </div> <div class="form-body"> <form method="POST"> <fieldset class="form-group" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} </fieldset> <div class="form-group"> <button type="submit" class="btn btn-primary … -
Django - database order_id bug
I have a app in Django, that has models.py like that: from django.db import models from django.utils import timezone from django.contrib.auth.models import User import base64 class Order(models.Model): name = models.CharField(max_length=45) #note = models.CharField(blank=True, max_length=45) class Product(models.Model): name = models.CharField(max_length=40) quantity = models.CharField(max_length=32) price = models.CharField(max_length=32) #name = models.CharField(max_length=128, blank=True) #access_to_doors = models.ManyToManyField(Door, blank=True) class Review(models.Model): review_id = models.CharField(max_length=15) review_name = models.CharField(max_length=128) #username = models.ManyToManyField(Users) class Contact(models.Model): email=models.CharField(max_length=200) password=models.CharField(null=True, max_length=32) subject=models.CharField(null=True, max_length=1024) #def __str__(self): # return self.email I delete database, make a new one, run python manage.py migrate/makemigrations/migrate --run-syncdb and it says this Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying building_access.0001_initial...Traceback (most recent call last): File "D:\dev\building_access\myvenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql) File "D:\dev\building_access\myvenv\lib\site-packages\django\db\backends\mysql\base.py", line 74, in execute return self.cursor.execute(query, args) File "D:\dev\building_access\myvenv\lib\site-packages\MySQLdb\cursors.py", line 206, in execute res = self._query(query) File "D:\dev\building_access\myvenv\lib\site-packages\MySQLdb\cursors.py", line 319, in _query db.query(q) File "D:\dev\building_access\myvenv\lib\site-packages\MySQLdb\connections.py", line 259, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (1170, "BLOB/TEXT column 'order_id' used in key specification without a … -
How can I sort a Django query by user input?
I have a Django website with the following relevant models, views and templates. My question is below, after the relevant bits of code (note the code here is likely longer than what is needed to answer the question). Model: class Article(models.Model): title = models.CharField(max_length=255) comment = models.TextField() entry_date_time = models.DateTimeField(default=timezone.now, null=True) class Meta: ordering = ['-entry_date_time'] score_choices = [(-5,'-5'), (-4, '-4'), (-3,'-3'), (-2, '-2'), (-1,'-1'), (0,'0'), (1,'1'), (2,'2'), (3,'3'), (4,'4'), (5,'5')] fundamental_score = models.FloatField(choices=score_choices, default=0) equity = models.ForeignKey(Equity, on_delete=models.CASCADE, null=True) View: class ArticleListView(ListView): model = Article paginate_by = 50 fields = ('equity', 'entry_date_time', 'fundamental_score', 'sentiment_score', 'source') template_name = 'article_list.html' context_object_name = 'object_list' equity_query="" date_query="" start_query="" industry_query="" broker_query="" def get_queryset(self): if self.request.method == 'GET': if self.request.GET.get('equityQuery') is None: self.equity_query = "" else: self.equity_query = self.request.GET.get('equityQuery') if self.request.GET.get('dateQuery') is None: self.date_query = "" else: self.date_query = self.request.GET.get('dateQuery') if self.request.GET.get('startQuery') is None: self.start_query = "" else: self.start_query = self.request.GET.get('startQuery') if self.request.GET.get('industryQuery') is None: self.industry_query = "" else: self.industry_query = self.request.GET.get('industryQuery').title() if self.request.GET.get('brokerQuery') is None: #new self.broker_query = "" #new else: #new self.broker_query = self.request.GET.get('brokerQuery').title() #new self.equity_query = self.equity_query.upper() articles_list = Article.objects.filter(Q(equity__equity_name__contains=self.equity_query) & Q(entry_date_time__contains=self.date_query) & Q(equity__industry__contains=self.industry_query) & Q(source__contains=self.broker_query)) Equity.objects.all().filter(industry=industry) return articles_list Template: {% extends 'base.html' %} {%block title %}Entries{% endblock title %} {% block … -
Django - Ldap setting issue
import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType Baseline configuration. AUTH_LDAP_SERVER_URI = 'ldap://sub.domain.com' AUTH_LDAP_BIND_DN = 'CN=Bind Account,CN=Users,DC=ad,DC=users,DC=com' AUTH_LDAP_BIND_PASSWORD = 'passwrd' AUTH_LDAP_USER_SEARCH = LDAPSearch( 'OU=XXX,DC=users,DC=yyy,DC=com', ldap.SCOPE_SUBTREE, '(uid=%(user)s)', ) AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,OU=XXX,DC=users,DC=yyy,DC=com" AUTH_LDAP_GROUP_BASE = "OU=XXX,DC=users,DC=yyy,DC=com" AUTH_LDAP_GROUP_FILTER = 'member={0}' Set up the basic group parameters. AUTH_LDAP_GROUP_SEARCH = LDAPSearch( AUTH_LDAP_GROUP_BASE, ldap.SCOPE_SUBTREE, AUTH_LDAP_GROUP_FILTER, ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr='CN') Simple group restrictions AUTH_LDAP_REQUIRE_GROUP = 'CN=enabled,OU=XXX,OU=groups,DC=users,DC=yyy,DC=com' AUTH_LDAP_DENY_GROUP = 'CN=disabled,OU=XXX,OU=groups,DC=users,DC=yyy,DC=com' Populate the Django user from the LDAP directory. AUTH_LDAP_USER_ATTR_MAP = { 'first_name': 'givenName', 'last_name': 'sn', 'email': 'mail', } AUTH_LDAP_USER_FLAGS_BY_GROUP = { 'is_active': 'CN=Bind Account,CN=Users,DC=ad,DC=users,DC=com', 'is_staff': 'CN=Bind Account,CN=Users,DC=ad,DC=users,DC=com', 'is_superuser': 'CN=Bind Account,CN=Users,DC=ad,DC=users,DC=com', } view.py user_obj = authenticate(request, username='userid', password='passwrd') user_detail = login(request, user_obj, backend='django.contrib.auth.backends.ModelBackend') I'm getting the below error, 'AnonymousUser' object has no attribute '_meta' I tried the below code also, conn = ldap.initialize('ldap://sub.domain.com') result = conn.search_s('CN=Bind Account,CN=Users,DC=ad,DC=users,DC=com',ldap.SCOPE_SUBTREE, '(objectClass=*)') For the above code, I got a different error, NO_SUCH_OBJECT at / {'msgtype': 101, 'msgid': 1, 'result': 32, 'desc': 'No such object', 'ctrls': [], 'matched': 'DC=ad,DC=users,DC=com', 'info': "0000208D: NameErr: DSID-03152973, problem 2001 (NO_OBJECT), data 0, best match of:\n\t'DC=ad,DC=users,DC=com'\n"} -
how to add a style in django
I want change the row color in a table whit class, how to put html classes if something happens e.g models.py class Car(models.Model): name = models.CharField(max_length=20) color = models.CharField(max_length=20) views.py from .models import Car def index(request): cars = Car.objects.all() context = { 'cars' = cars } return (request, 'index.html', context) index.html (i`m using bootstrap) <div class="table-responsive-md"> <table class="table tableh-hover"> <thead> <tr> <td>Name</td> <td>Color</td> </tr> </thead> <tbody> {% for car in cars %} <tr> <td>{{ car.name }}</td> <td {if car.color == red } style="background-color: red;"{% endif %}>{{car.color}}</td> </tr> {% endfor %} </tbody> </table> </div> {{car.color}} this line is what i want to make work --- I`m improving my english, please be patiente :D -
In Django, after user login if click on any link he gets logged out
Previously it was working fine. But now as long as user click on any link he is getting logged out. Does any know why it's happening? It's not issue with code as I didn't even change a single line and it was working finely. -
Getting unexpected token error while rendering array of json objects in Javascript from Django Views
I am using Google picker API to post data in django backend using fetch API function of javascript which gets the response as expected. Now i want to display the posted data in a list on frontend. However while trying to render a html template by the response array of json objects from django views, i get the unexpected '{' error while fetching it in a javascript variable. below is the response body I get after posting below is the view function i am using for saving the posted data in django backend and rendering it in html below is the corresponding html page code for displaying the data received from views here's the screenshot of error received shown in chrome developer tool -
How to use forms in a table to update specific model fields without pk or id in the url?
I have a tool in my Django project to monitor the correctness of new input data. Basically, it checks for custom validations in the fields of some models, query them and pass to a view as the context. If some of these data is incorrect, I have a page that lists all the instances of the model that have incorrect (but acceptable) data. On this page, where the data is showing as a table with columns for some of the fields that are incorrect, I want to have a column with a textbox and a Save button for each row of the table where some user will be able to write a comment, click save and this comment will be saved to the respective model.comment field for another team to see later on and do the proper fix (like in the image attached). Since this table is being displayed in a simple URL say: admin/my-tool/quality-check-table, I don't have any id, pk, or anything to link each button in each row to a specific instance of the model in my view function when doing a POST request to update the model. I feel like there might be a way of doing … -
Create a values filter by list of words
I'm trying to create a filter objects values without success: fields = 'sql_model', 'Host' parsed_table.objects.all().values(fields) Can somebody know what I did wrong? TX -
Why does my django form with recaptcha send data even empty the recaptcha?
I put the google recaptcha V2 to my django project form. It looks like working, but if I leave the recaptcha checkbox my form is sent still. forms.py from django import forms from captcha.fields import ReCaptchaField from django.forms import Textarea from .models import * class CustomerForm(forms.ModelForm): captcha = ReCaptchaField( public_key='key', private_key='key', ) class Meta: model = Customer fields = '__all__' def __init__(self, *args, **kwargs): # get 'user' param from kwargs user = kwargs.pop('user', None) super().__init__(*args, **kwargs) self.fields['i_have_read_rules'].widget.attrs['required'] = 'True' self.fields['i_agree'].widget.attrs['required'] = 'True' self.fields['captcha'].widget.attrs['required'] = 'True' for field in self.fields: self.fields[field].widget.attrs['class'] = 'form-control' self.fields['i_have_read_rules'].widget.attrs['class'] = 'form-check' self.fields['i_agree'].widget.attrs['class'] = 'form-check' -
Drf-yasg token authentification django rest
I try to setup drf-yasg(1.20) API for my Django project, I am using token authentification which is working very well but not with drf-yasg, when I enter my token in the swagger UI nothing happens, the same thing with session auth ?? swagger config : SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'Token': { 'type': 'apiKey', 'in': 'header', 'name': 'Authorization' } }, 'SHOW_REQUEST_HEADERS': True, 'USE_SESSION_AUTH': False, 'JSON_EDITOR': True, 'SUPPORTED_SUBMIT_METHODS': [ 'get', 'post', 'put', 'delete', 'patch' ], } 'JWT_AUTH_HEADER_PREFIX': 'Token', schema : schema_view = get_schema_view( openapi.Info( title="Voora api", default_version='v1', description="Test description", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="contact@snippets.local"), license=openapi.License(name="BSD License"), ), public=False, permission_classes=[permissions.AllowAny], ) django-rest settings : REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema' } -
django 'inventory' is not a registered namespace
I have two pages in my application, dashboard and inventory. Dashboard page is working as expected but the inventory page throws the following error: NoReverseMatch at /inventory/ 'inventory' is not a registered namespace urls.py from django.urls import path from account import views app_name = "account" urlpatterns = [ path('dashboard/', views.dashboard_page, name='dashboard'), path('inventory/', views.inventory_page, name='inventory'), ] views.py import csv import datetime from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator, InvalidPage from django.http import Http404, HttpResponse from django.shortcuts import render, redirect from django.db.models import Q from account.filters import InventoryFilter from account.models import Inventory # # Dashboard Page # @login_required def dashboard_page(request): return render(request, "account/dashboard.html", {}) # # Inventory Page # @login_required def inventory_page(request): card_list = Inventory.objects.exclude(card__side='b').order_by('-card_id__set_id__releaseDate', 'card_id__set_id__name', '-card__colors', 'card__convertedManaCost', 'card__name') inventory_filter = InventoryFilter(request.GET, queryset=card_list) card_list = inventory_filter.qs paginator = Paginator(card_list, 20) is_paginated = True if paginator.num_pages > 1 else False page = request.GET.get('page') or 1 try: current_page = paginator.page(page) except InvalidPage as e: raise Http404(str(e)) context = { 'is_paginated': is_paginated, 'current_page': current_page, 'inventory_filter': inventory_filter, } return render(request, "account/inventory.html", context) -
paypal-checkout-serversdk with Django
I want to integrate Paypal into my Django App. I tried using django-paypal it worked fine but it stopped working suddenly, PayPal was not sending confirmation to the notify URL anymore but it again started working now, so I decided that I will do this with python SDK but their not many docs online on how to achieve it I tried paypal-checkout-serversdk which is the newer version and could;t get it to work then I tried paypalrestsdk and no luck there as well there are docs on how to implement it on client-side and how to do it on the server side but I could not figure out how out.