I'm running a photography app in Django. I have a Photograph model and a PhotoSet model with a ManyToManyField relationship to Photograph. I would like to create an admin action where I can select several Photograph objects in the admin list view, choose the "Create photo set from selected photos" action, and be taken to the admin:photography_photoset_add view with the photos field pre-populated with the photos I selected on the previous page. I'd then be able to enter the title, slug, and description as needed. Is this flow possible? I haven't been able to find it after quite a bit of searching and the only route I currently know of would be handling all of this myself with custom add views and storage of my selection in session state. Seems messy.
See this part of the docs:
https://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/#actions-that-provide-intermediate-pages
And this answer:
https://stackoverflow.com/a/4924985/202168
from django.core.urlresolvers import reverse
def create_photoset_from_photos(modeladmin, request, queryset):
ids = ','.join([str(photo_id) for photo_id in queryset.values_list('id', flat=True)])
add_photoset_url = '{url}?photos={ids}'.format(url=reverse('admin:photography_photoset_add'), ids=ids)
return HttpResponseRedirect(add_photoset_url)
Related
I have a django project in which the the form records the name and the email addresses of the users and I was able to put that data using forms.py and models.py.
What I want to do nextis to create an action through which I can download that in csv file.
My admin page looks like this now and I want to add action right above.
in order to add an action to a model in the admin page you have to create a new class like this and register it with your model:
admin.py
from youSite.views import downloadCSV
from yourSite.models import Info
class infoAdmin(admin.ModelAdmin):
actions =[downloadCSV]
admin.site.register(infoObject, infoAdmin)
You have to create the function in your views and import it into the admin page. It create a new action in that model.
Hope it helps
I would like to get some advice from the community.
I have recenlty started learning Django and have a question regarding the structure of the application.
I have a URL http://127.0.0.1:8000/asset/2/, a DetailView for my Asset model which also has two card blocks that houses data for two other models Tenant and Service. Check the screenshot below.
I am generating the above view from the asset/views.py file. Code as below.
class AssetMultipleDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView):
model = Asset
context_object_name = 'asset'
template_name = 'asset/asset_multiple_detail.html'
def test_func(self):
asset_multiple = self.get_object()
if self.request.user == asset_multiple.owner:
return True
return False
def get_context_data(self, **kwargs):
context = super(AssetMultipleDetailView, self).get_context_data(**kwargs)
context['tenants'] = Tenant.objects.filter(asset=context['asset']).order_by('created')
context['services'] = Service.objects.filter(asset=context['asset']).order_by('created')
return context
When you click on the Add New Tenant button, I use the below URL in tenant/urls.py
path('new/asset/<int:pk>/', TenantAssetCreateView.as_view(), name='tenant_asset_create'),
This URL generates a CreateView for Tenant. I use the primary key of the asset in the URL to load up only the right asset to the Asset selection field. Please see the image below.
Everything works well.
I would like to know whether is this the best way to achieve this? Will this be easily maintainable as there are more views similar to this upcoming in the application.
Any advice is much appreciated. Thank you in advance.
I am not quite sure what your models look like. Does tenant have a manytomany relation to asset (a tenant can be related to any amount of assets)? Or does tenant have a foreign key to asset in your design (a tenant has exactly one related asset)? Based on the screenshot I assume the latter.
Or do you want an asset to only have one tenant (foreign key on asset to tenant)?
Loading the correct asset from the URL is perfectly valid. You should maybe make asset in the form disabled, so it can not be manipulated.
In the CreateView you could override form_valid(self,form) to set self.object.asset to the one you need.
so I have set up Django allauth on my Django project and connected to Instagram,
when doing so I have now on my admin site Social accounts category with my account registers, all good so far
on the lower page, I can see a field called extra data,
how can I put it inside the normal Users database so I can use it to take how many followers I got out of the extra data?
can I request the followers with the Token i have maybe?
You can simply access the SocialAccount model like any other django model:
from allauth.socialaccount.models import SocialAccount
def instagram(request):
data = SocialAccount.objects.get(user=request.user).extra_data
follows = data.get('counts')
return render(request, 'Path.to.html', {"follows": follows})
Im trying to use Django Suit's form includes to add a button to the list display of all my subscribers in the admin. In the documentation it says to add this to your admin.py file in the right app.
class SubscriberAdmin(admin.ModelAdmin):
list_display = ('email', 'date')
readonly_fields = ('email', 'date')
def has_add_permission(self, request):
return False
suit_form_includes = (
('admin/suit_includes/suit_csv.html', 'top'),
)
However this only appears when clicking into an instance of an object, and doesn't show up on the admin page that shows the entire list of objects in the database. Is there a way to do this with Django Suit ? I had trouble finding anything on google.
suit form include template:
<button class="btn btn-info">Export to File</button>
Admin instance display (Where its appearing):
Admin list display (Where I want it to appear):
What's doing django-suit, here, is that it is including your HTML snippet in the change_form that is displayed for your model, the change_form being where you can modify your model and save the changes into the database.
Where you want it to appear is the "change_list", aka the place where you can see all of your instances of that model in your database.
To add it your html snippet, you should extend your change_list.html with your own snippet : More info on expanding templates in the official documentation
Good luck !
I have installed the django-registration app to my project. After a successful log in step, I am redirecting the user to localhost:8000/ - this is my default testing host and port. And I am displaying somewhere on the page, the username of the logged in user.
What I want to do now is that when I click the username some options like edit profile or change password will appear. My questions are the following:
Should I create another model (inside another new app) containing fields like profile photo, gender, birthday etc and add a foreign key to the User model from django.contrib.auth.models ? Or should I modify the model from django-registration to add some additional fields but which I do not ask for at registration phase and only update them later?
if I want my profile edit feature to be at /accounts/edit, which would be the best practice to do it? to edit the URLconf of my project and add a line like (r'^accounts/edit$',.....) just before (r'^accounts/', include('registration.backends.default.urls')), ?
I hope I made myself clear. I'm trying to figure out which would be the best approach before coding, as I am new to Django... Thanks
I find it's easier to decouple the profile table from the auth table. Just like you mentioned you can use a foreign key relationship to link that profile to the user. You can also apply a lambda inside of your profile table to automatically create a profile when a new user object is created.
Inside your template you can link to the profile page dynamically based on the current authenticated party by using
{% if request.user.is_authenticated %}
Update Profile
{% endif %}
user_profile being the name of your app which holds your user_profile table. That way when the request is made you use the regular expression for the current user id (similar to the polls example provided by django) to get the id number of the currently logged in user than inside the views you just query the database for that particular user.
views.py
def myView(request, user_id):
userProfile = UserProfile.objects.get(user.pk=user_id)
This is a high level example to give an idea of one way to accomplish it.