How can I override the django AuthenticationForm input css class? - django

I have a django site using the basic django registration framework. I have my login page working fine, but I want to change the css class on the inputs. The form passed to the login page looks to be an AuthenticationForm class.
What would be a good way to add a css class to the username, and password fields?

Sub class your auth form
forms.py
from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.forms.widgets import PasswordInput, TextInput
class RFPAuthForm(AuthenticationForm):
username = forms.CharField(widget=TextInput(attrs={'class': 'span2','placeholder': 'Email'}))
password = forms.CharField(widget=PasswordInput(attrs={'class': 'span2','placeholder':'Password'}))

I do what you want like this:
def login(request):
form = AuthenticationForm(request)
form.fields['username'].widget.attrs['class'] = "custom_css"
form.fields['password'].widget.attrs['style'] = "background:red"
return render_to_response("login.html", {'form':form},
context_instance=RequestContext(request))

Related

Django rich text editor inside django template not for Admin

How can I set rich text editor inside Django Template without using crispy form {{form.media}}. I am not using crispy form right now. What to do.
I don't think there's any other method to do this. But, I can provide you the simplest solution.
Create a forms.py file inside your Django APP
from django.forms import ModelForm
from .models import Order
class OrderForm(ModelForm):
class Meta:
model = Order
fields = ['description']
Here, Order is your Model Name.
Inside your views.py
from django.shortcuts import render
from order.models import Order
from .forms import OrderForm
# Create your views here.
def post_order(request):
if request.method == "GET":
order_form = OrderForm()
required_dict = {
'form':order_form,
}
return render(request, "themes/order/order_post.html",required_dict)

how can i overide django allauth signup success_url

I'm working on a project using allauth and i'm using customer user model and i wan the newly registered user to be redirected to a different page (say profile form page) which will be totally different from the login_redirect_url, I have tried it this way
any idea how i can make this work pls?
from django.shortcuts import get_object_or_404, redirect, render
from allauth.account.views import LogoutView
from django.urls import reverse_lazy
from allauth.account.views import SignupView
from django.views.generic import TemplateView
from .models import CustomUser
class Signup(SignupView):
success_url = reverse_lazy('business:company_profile')
def get_success_url(self):
return self.success_url
I am not sure there is way to override SignUp redirection since when you sign up in the application, you also sign in, which will use the login_redirect_url.
If you overrode login_redirect_url (documentation) you can update your logic and redirect the user to his profile if some fields are missing/empty?
def get_login_redirect_url(self, request):
if not request.user.your_custom_field:
path = "/accounts/{username}/"
return path.format(username=request.user.username)
else
return "/"
You could also implement another logic by adding a bool is_first_visit on your CustomerUser model (with default=True) and set it to False after his first visit.
Is the code that you proposed not working? What errors does it produce?
On first glance, the view that you've proposed should work. You would just have to make sure it's being used in "urls.py".

Django Admin: How to Access to Logged-in User for Using It in Custom 'list_display' Field?

I want to create a hyperlink (custom field in display_list) and I have to use logged-in User's id as a part of query parameters in the link.
Is there any solution for this?
You can extend the model admin's get_list_display method to access the request object and you can add your custom method inside that method where it can access the request object.
from django.utils.html import format_html
Class FooAdmin(admin.ModelAdmin):
def get_list_display(self, request):
def custom_url_method(obj):
user = request.user
return format_html("<a href='http://url.com/{0}'>link</a>", user.pk)
return ['model_field_1', 'model_field_2', custom_url_method]
for this implement you can create function and return the html file to your admin panel and pass the content to your html than render in admin panel with render_to_string
for example:
in your admin.py:
from django.contrib import admin
from django.template.loader import render_to_string
from .models import CustomModel
class CustomAdmin(admin.ModelAdmin):
list_display = ('model_field 1', 'custom_link', 'model_field 2',)
def custom_link(self, object):
return render_to_string('custom.html', {'content':'content'})
custom_link.allow_tags = True
admin.site.register(CustomModel, CustomAdmin)
in template/custom.html:
custom link {{content}}
or
custom link {{content}}
Good Luck :)
As per my Understanding, you need to have a link which takes user.id to send you somewhere according to your requirement. In my code i navigate to user detail page of that particular user inside admin.
Admin.py
class CustomAdmin(admin.ModelAdmin):
list_display = ['field1', 'field2', 'anotherfield', 'link_to_user']
def link_to_user(self, obj):
link = reverse("admin:auth_user_change", args=[obj.model_name.user.id])
return format_html(' {}', link, obj.model_name.user.id)
link_to_user.short_description = 'UserID'

How to remove username from Django registration 1.0

I have customize Django 1.5 (from djangoproject docs) authentication to login with email instead of username and its working perfect, but I am using Django-registration 1.0 to register users.
How do I remove the username field from django registration so users will only need to enter e-mail & password when registering.
Thank you all in advance.
Yaniv M
This should get you started.
Create your own form that is a subclass of RegistrationForm.
In forms.py
from registration.forms import RegistrationForm
class MyRegistrationForm(RegistrationForm):
# Override RegistrationForm
def __init__(self, *args, **kwargs):
super(RegistrationForm, self).__init__(*args, **kwargs)
self.fields.pop('username')
In views.py
from registration.views import RegistrationView
from yourapp.forms import MyRegistrationForm
class MyRegistrationView(RegistrationView):
form_class = MyRegistrationForm
In urls.py
url(r'^accounts/register/$', MyRegistrationView.as_view(),
name='registration'),
You can create a custom form class based on default RegistrationForm and use that class in the RegistrationView view.
As-is, it's complicated. You need to:
apply this patch because in d-r-1.0, models.py assumes your User model has a "username" field
create your own "backend" by copy/pasting/editing registration/backends/default/views.py
copy/paste/edit the registration form as well from registration/forms.py
most of the time you can use the registration views without modification

Implement Django Simple Captcha with the existing django.contrib.auth.forms

I would like to add captcha on my django registration form using Django Simple Captcha found here: http://code.google.com/p/django-simple-captcha/
This works great if you create a new form but I'm using the django.contrib.auth.forms the one that comes with django. Any idea how I might be able to implement captcha with the existing django auth views? Thank you!
You could simply subclass the django.contrib.auth.forms forms and add a CaptchaField, like this:
from django.contrib.auth.forms import UserCreationForm
from captcha.fields import CaptchaField
class CaptchaUserCreationForm(UserCreationForm):
captcha = CaptchaField()
and use the new Form in your view as usual:
if request.POST:
form = CaptchaUserCreationForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/?ok')
else:
form = CaptchaUserCreationForm()