How we can create generic API in django? - python

I'm totally new to Django.
I'm creating Generic API. List and Create are working well but ID is not visible in DELETE and UPDATE.
This is my views.py file
from rest_framework import generics
from rest_framework import mixins
This is my urls.py code
from .views import GenericApiView
path('inspections-templates', GenericApiView.as_view()),
But as I check documents the ID is not available for UPDATE & DELETE.
Can you please someone guide me on how can I update and delete the record.
Thanks in advance

Actually you have to pass that id in your URL.Try this in urls.py:
path('inspections-templates/<int:id>/', GenericApiView.as_view()),
Because in UPDATE and DELETE user id is required to perform PUT and DELETE.

Related

How to add actions to Python django admin page

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

Where to best execute database operations using Django framework?

Thanks in advance for any help. I am new to django specifically as well as web development in general. I have been trying to teach myself and develop a website using the Django framework and while everything is working so far, I am not sure if I am really doing things in the best possible way.
Typically, within my django app, I will have certain points where I want to modify the contents of my database model in some way. A typical use case is where I have button on my site that says "Add a post":
models.py:
from django.db import models
# data model import
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
post = models.CharField(max_length=1024)
urls.py:
from django.urls import include, path
from . import views
urlpatterns = [
path('', views.post, name='new_post'),
path('post_exec', views.post_exec, name='post_exec'),
]
views.py:
from django.contrib import messages
from django.shortcuts import render, redirect
# import data models
from django.contrib.auth.models import User
from .models import Post
def post(request):
# make sure the user has privileges
user = User.objects.get(id = request.user.id)
if not user.is_superuser:
return redirect('home')
return render(request, 'post.html')
def post_exec(request):
# make sure the user has priveledges
user = User.objects.get(id = request.user.id)
if not user.is_superuser:
return redirect('home')
# create the post
new_post = Post.objects.create()
new_post.user = user
new_post.post = request.POST['post']
new_post.save()
# this could redirect to a confirmation page or something too
return redirect('home')
You can see what I am doing here is that everytime I need a change to the database due to user input, I am executing the code to do the requested database change in a django view and then redirecting to another page following completion of the database change. While this works, it feels kind of clunky (you end up needing pages that you never actually use), it seems pretty sketchy in terms of security (although I am checking for credentials on each page), and I imagine there is a better way to do this.
Can any experience Django developers offer some advice for how I should be best structuring my project for these specific types of common database operations?
The Django's views is a good place to organize the project's CRUD system so users can manage their data. You can use the class-based views to group the GET, POST etc requests. Also there are better ways of using the authorization system with the login_required() decorator, the LoginRequiredMixin class and other solutions that you can rich here

Django Admin template override

I am following the tutorial on django website to create my first django app.
Now I am stuck trying to override Django Admin template.
My project directory is this:
First I tried creating a new admin template in the surveys app. It works.
Then, I tried with the override function. For this I created at surveys/admin.py the following code:
from django.contrib.admin import AdminSite
from django.utils.translation import ugettext_lazy
class SurveysAdminSite(AdminSite):
site_header = ugettext_lazy('Test administration')
surveys_admin_site = SurveysAdminSite()
And add to computationalMarketing/urls.py the following:
from .admin import surveys_admin_site
urlpatterns = [
path('admin/', surveys_admin_site.urls, name='admin'),
]
It doesn't work, so I search, and tried something different. Add this same previous code to surveys/urls.py. Neither works. Then I rollback the changes to save the code to computationalMarketing/urls.py, but this time I changed the code from surveys/admin.py to computationalMarketing/admin.py (in fact I created the file because it doesn't exists.
It works and now I see the site header that I want, but I get You don't have permission to edit anything. I have seen that is something related with superuser creation, but until now I was able to admin my surveys app without problem, so I believe in some solution related with override properly the admin.py at surveys app
Does anybody knows why this does not works as expected?
You are overriding the complete admin site. You may want to override only specific templates and keep using the default admin site.
A first approach to solve your problem is to add models to your admin site:
surveys/admin.py:
from django.contrib.admin import AdminSite
from django.utils.translation import ugettext_lazy
from surveys.models import OneModel, OtherModel
class SurveysAdminSite(AdminSite):
site_header = ugettext_lazy('Test administration')
surveys_admin_site = SurveysAdminSite()
surveys_admin_site.register(OneModel)
surveys_admin_site.register(OtherModel)
And maybe use ModelAdmin objects to add advanced behavior.
Hope this helps.

Export button is not visible with django-import-export package

I am trying to use django-import-export module in my admin and here are my settings
admin.py
from import_export.admin import ImportExportMixin, ImportMixin, ExportActionModelAdmin, ImportExportActionModelAdmin
class RegistrationAdmin(ImportExportActionModelAdmin):
list_display = ('user', 'activation_key_expired')
raw_id_fields = ['user']
search_fields = ('user__username', 'user__first_name', 'user__last_name')
admin.site.register(RegistrationProfile, RegistrationAdmin)
With the above code, i can able to see an Import button in admin as below
But i can't able to see Export option, so what's the problem what am i missing here ?
I have seen some ticket about export button permission here
https://github.com/django-import-export/django-import-export/issues/38 ? can anyone please let me know what need to be done in order for Export to appear ?
By the way i am using django suit as my admin theme
You need to use ImportExportModelAdmin
ImportExportActionModelAdmin only adds the export to the list of things you can do to selected items (see the dropdown in your screenshot)
Docs for ImportExportActionModelAdmin state
Export functionality is implemented as an admin action.
You need to use ImportExportModelAdmin
Eg:
from django.contrib import admin
from .models import Question, Choice
from import_export.admin import ImportExportModelAdmin
# Register your models here.
#admin.register(Question)
class ViewAdmin(ImportExportModelAdmin):
pass
#admin.register(Choice)
class ViewAdmin(ImportExportModelAdmin):
pass

Read only usernames in django admin site

I'm using django and its built in admin site for the project I'm working on. (Python 3.4, django 1.7)
For the current project I'm working on I require usernames to be fixed after object creation. I have made a small test project, which literally contains one app, and that app only contains this admin.py:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
class MyAdmin(UserAdmin):
def get_readonly_fields(self,request, obj=None):
ro_fields = list(super().get_readonly_fields(request, obj))
if obj is not None:
ro_fields.append('username')
return ro_fields
admin.site.unregister(User)
admin.site.register(User, MyAdmin)
As expected, the Username can be set in the Add page and is Read Only in the change page. However, I cannot save when on the change page, I receive the message "please correct the errors below" but no field is highlighted. Can anyone suggest a way to work round this problem?
EDIT: as a diferent option I attempted to replace the username with a widget that didn't allow input - no luck there either

Categories