Add Plus to dropdown with django - django

Any ideia how to implement form field with plus icon to add ? Like form in django admin.
Thank You

This can be done using ModelAdmin.autocomplete_fields. For example:
# admin.py
from django.contrib import admin
from .models import Car, Driver
#admin.register(Car)
class CarAdmin(admin.ModelAdmin):
autocomplete_fields = [
"driver",
]
#admin.register(Driver)
class DriverAdmin(admin.ModelAdmin):
search_fields = [
"name",
]

Related

Django Admin: How to customize autocomplete_fields width to adapt to the content?

I'm trying to customize the widget rendered by autocomplete_fields for a ForeignKey Model field.
Basically the problem is that the widget is too narrow for the content and it's breaking in two lines inside the select:
I have seen that the JS library or JQuery plugin is called Select2 and it has a "dropdownAutoWidth" to make it adapt to the parent element size that kind of works but I'm completely clueless on how to set that option from admin.py since it seems that options are never passed in the code at django.contrib.admin.widgets.AutocompleteMixin.media:
def media(self):
extra = '' if settings.DEBUG else '.min'
i18n_name = SELECT2_TRANSLATIONS.get(get_language())
i18n_file = ('admin/js/vendor/select2/i18n/%s.js' % i18n_name,) if i18n_name else ()
return forms.Media(
js=(
'admin/js/vendor/jquery/jquery%s.js' % extra,
'admin/js/vendor/select2/select2.full%s.js' % extra,
) + i18n_file + (
'admin/js/jquery.init.js',
'admin/js/autocomplete.js',
),
css={
'screen': (
'admin/css/vendor/select2/select2%s.css' % extra,
'admin/css/autocomplete.css',
),
},
)
Django 3.0.9:
forms.py
from django import forms
from django.contrib import admin
from django.contrib.admin.widgets import AutocompleteSelect
from .models import MyModel
class MyModelForm(forms.ModelForm):
class Meta:
fields = ('my_field', )
widgets = {
'my_field': AutocompleteSelect(
MyModel.my_field.field.remote_field,
admin.site,
attrs={'style': 'width: 400px'} # You can put any width you want.
),
}
admin.py
from django.contrib import admin
from .forms import MyModelForm
MyModelAdmin(admin.ModelAdmin):
form = MyModelForm
You can pass data-* attributes to select2 by including them in the autocomplete widget's attrs. One way to do this is to initialize the widget yourself using a custom form.
Note that if you also include the field in autocomplete_fields then the widget will be initialized by your ModelAdmin instance and your custom initialization won't have any effect.
Also note that the AutocompleteSelect and AutocompleteSelectMultiple widgets require a couple of positional arguments.
Something like this should work:
from django import forms
from django.contrib import admin
from django.contrib.admin.widgets import AutocompleteSelect
class MyForm(forms.ModelForm):
class Meta:
widgets = {
'my_field': AutocompleteSelect(
MyModel._meta.get_field('my_field').remote_field,
admin.site,
attrs={'data-dropdown-auto-width': 'true'}
),
}
class MyAdmin(admin.ModelAdmin):
#autocomplete_fields = ['my_field']
form = MyForm

Getting AttributeError while registering my model to Django admin?

What i am trying to do:
Trying to registering my model to django admin
What problem do i get:
I am getting the following error:
My Code:
admin.py:
from django.contrib import admin
from .models import UserProfile, Post
admin.site.register(UserProfile,Post)
model.py:
from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='static/media/',max_length=100)
class Post(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()
urls.py:
from django.conf.urls import url
from .import views
urlpatterns = [
url(r'^register/$',views.registerUser),
url(r'^$', views.index, name="Index"),
url(r'^validateRegisterForm/$',views.validateRegisterForm),
url(r'^validateLoginForm/$',views.validateLoginForm),
url(r'^article/$', views.article, name="Article"),
url(r'^Login/$',views.loginUser, name="Login"),
url(r'^Logout/$',views.logoutUser, name="Logout"),
]
Note: I am new to django so, don't know much about it.
This should be
admin.site.register(UserProfile)
admin.site.register(Post)
Admin.site.register takes two parameters, the first is the model class and the optional second parameter is an admin class. In your code, you were passing another model as the admin class.
for more information, please refer to :https://docs.djangoproject.com/en/1.10/ref/contrib/admin/

Django-registration-redux adding custom fields to app

I need to add custom fields to Django-registration-redux such as picture and few other fields. Is there a ref or 2 liner guide for how to do it? As per docs I can call RegistrationView in my app views and import my own created model fields to override it. If this is right approach please let me know.
You have to define your custom form and then set your registration url to use the custom form.
Defining your custom form:
users/form.py
from registration.forms import RegistrationForm
from users.models import User
class CustomRegistrationForm(RegistrationForm):
class Meta:
model = User
fields = ('email', 'picture', 'password',)
Your main urls file:
project_name/urls.py
from users.forms import CustomRegistrationForm
urlpatterns = [
[...]
url(r'^registration/register/$', RegistrationView.as_view(
form_class=CustomRegistrationForm), name='registration_register',),
url(r'^registration/', include('registration.backends.default.urls')),
[...]
]

Django Rest Framework - CreateAPIView doesn't let use POST method

I try to create a view, that will accept POST requests and create new instances of my model(see bottom of post). I follow this tutorial. The problem is that when I access URL associated with view, which inherits from CreateAPIView I dont see a form in html representation of API for creation of new instances and I also see that it accepts GET requests, not POST as it mentioned in documentation.
Page looks like this
My views.py
from django.shortcuts import render
from rest_framework.generics import ListAPIView, CreateAPIView
from datingapp.models import Profile
from .serializers import ProfileSerializer, ProfileCreateSerializer
class ProfilesAPIView(ListAPIView):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
class ProfileCreateAPIView(CreateAPIView):
queryset = Profile.objects.all()
serializer_class = ProfileCreateSerializer
My urls.py
from django.conf.urls import url
from django.contrib import admin
from datingapp.views import ProfilesAPIView, ProfileCreateAPIView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'api/profiles/', ProfilesAPIView.as_view(), name='list'),
url(r'api/profiles/create/$', ProfileCreateAPIView.as_view(), name='create')
]
My serializers.py
from rest_framework.serializers import ModelSerializer
from datingapp.models import Profile
class ProfileSerializer(ModelSerializer):
class Meta:
model = Profile
fields = [
'name',
'age',
'heigth'
'location',
]
class ProfileCreateSerializer(ModelSerializer):
class Meta:
model = Profile
fields = [
'name',
'age',
'heigth'
'location',
]
In my settings.py I have crispy_forms installed.
What am I doing wrong ?
UPD: here is what I want to achieve
As you see there is a form and it accepts only POST and also says that GET is not allowed
The problem is in your router. The first pattern matches both api/profiles/ and api/profiles/create/ so the second one will never be evaluated. You are seeing the ProfilesAPIView instead of the create view.
url(r'api/profiles/', ProfilesAPIView.as_view(), name='list'),
url(r'api/profiles/create/$', ProfileCreateAPIView.as_view(), name='create')
To fix it, either swap the order of the urls, or add a $ to the end of the first pattern. r'api/profiles/$'
I was following a tutorial and had a similar problem. Probably I was not following the same version of Django Rest Framework and they had changes.
But I solved this problem doing this.
class AssetBundleList(generics.ListAPIView):
to
class AssetBundleList(generics.ListCreateAPIView):
Hope this helps someone.

Not showing django application in admin

I created poll aplication in Django. Here is admin.py code:
from django.contrib import admin
from poll.models import Question, Choice
class ChoiceInline(admin.StackedInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date']})
]
inlines = [ChoiceInline]
admin.register(Question, QuestionAdmin)
Also, I added 'poll' to INSTALLED_APPS. Now I have no urls and views for my poll application. Maybe the problem is with it?
Also I have other application 'article', I did the same as with poll, and article has appeared in admin.
You should use admin.site.register instead of just admin.register