How can I add dynamic field in the model in django? - python

I'm using django to create a application download site. I try to write a model, that the admin can add the different download content dynamically in the admin page. For example I have a software named foobar, it have 3 different version: 1.1, 1.2, 1.3. I would like the user can admin the model by using an add button to add the download link with a download version. But I don't know how to do this in django.

Set up your models to have a main model and ancillary models that have foreign keys to the main model:
class DownloadItem(models.Model):
name = models.CharField( etc etc)
... other attributes here ...
class DownloadItemFile(models.Model):
parent = models.ForeignKey('DownloadItem', related_name="versions")
version = models.CharField( etc etc)
file = models.FileField(upload='path/to/uploaddir/')
then, when you have an instance of your DownloadItem model, you can get hold of your various file versions with:
mydownloaditem.versions.all()
To be able to add files via the Admin, you will need to use an inline. In your admin.py for the app in question, you'll need to add something like:
class DownloadItemFileInline(admin.TabularInline):
model = DownloadItemFile
class DownloadItemAdminOptions(admin.ModelAdmin):
inlines = [ DownloadItemFileInline, ]
...other admin options here...
admin.site.register(DownloadItem, DownloadItem AdminOptions)

Related

Wagtail: How to overwrite create/edit template for PageModel

I want to overwrite create.html and edit.html used for models derived from Wagtails 'PageModel'.
If I understand the docs correctly it should be as simple as specifying the attributes:
class MyAdmin(ModelAdmin):
model = MyPage
create_template_name = "myapp/create.html"
edit_template_name = "myapp/edit.html"
My templates are located at projectroot/templates/myapp. It works fine if my model is a Django model but for a PageModel based model the create view still uses wagtailadmin/pages/create.html. I also tried the other location patterns mentioned in the docs w/o success.
Is it possible to change the edit and create templates for a PageModel? Or do the same limitations as for views apply, i.e. only index.html and inspect.html can be overwritten?
ModelAdmin does not provide create, edit, or delete functionality for Page models, as per the documentation note.
NOTE: modeladmin only provides ‘create’, ‘edit’ and ‘delete’ functionality for non page type models (i.e. models that do not extend wagtailcore.models.Page). If your model is a ‘page type’ model, customising any of the following will not have any effect.
It can be a bit confusing as the ModelAdmin system would seem to work for page models also, but there are some other ways to modify how your page can be edited. These will not be scoped to the ModelAdmin area though.
Option 1 - customise the generated form for your MyPage model
If you only want to customise how the edit page form that gets generated you can modify the base_form_class on your page model.
Wagtail has documentation about how to create a custom page form.
Note: WagtailAdminPageForm extends Django's ModelFormMetaClass
Example
from django import forms
from django.db import models
from wagtail.admin.forms import WagtailAdminPageForm
from wagtail.core.models import Page
class EventPageForm(WagtailAdminPageForm):
# ...
class MyPage(Page):
# ...
base_form_class = MyPageForm
Option 2 - customise the view via hooks
To customise the create & edit views for the normal (e.g. clicking edit page on the Wagtail user bar or explorer) page editing interface, you will need to use Wagtail hooks. Here you have access to the request so you will likely be able to determine if you are in the ModelAdmin area.
Create a file called wagtail_hooks.py in your app folder and provide a hook that will return a custom response (this will need to be rendered by your custom view.).
There are separate hooks for before_create_page and before_edit_page
Example from before_create_page docs below.
from wagtail.core import hooks
from .models import AwesomePage
from .admin_views import edit_awesome_page
#hooks.register('before_create_page')
def before_create_page(request, parent_page, page_class):
# Use a custom create view for the AwesomePage model
if page_class == AwesomePage:
return create_awesome_page(request, parent_page)
```python

Access Django DB objects without shell?

I have a request - can you help me access and manage django DB objects without using shell ?
I have created my models, but now (for example) i want to make a login system. I store users and passes(again, only an example), and i want to get the info from the DB, but i dont want to use shell.
What can i do in this case, im quite new to Django ?!
Best Regards
Why not use django-admin?
Maybe this is what you want:https://docs.djangoproject.com/en/3.0/ref/contrib/admin/
In views.py you can import
from .models import modelname
data = modelname.objects.all() - using this you can get all the data from the Database
Eg:-
for d in data:
print (d.email)
Will give all emails in the database
You can also use
t = modelname.objects.get(email='name#lk.com')
By this you can get the data of the person who's email is name#lk.com
Django already has database support where you can register your models and access them with a graphical interface.
See the documentation: django-admin-site
First you need to create a super user account, if you don't have one, create it with the terminal in the project directory, use this row:
python manage.py createsuperuser
For your model to appear on the admin site you need to register it
# models.py
class MyModel(models.Model)
field1 = models.CharField()
field2 = models.TextField()
# ...
# admin.py
from django.contrib import admin
from .models import MyModel
admin.site.register(MyModel)
So it's the basic way to register your model, if you want to personalize you need to check the documentation ModelAdmin.fieldsets
with this done, just access the admin site at the link http://localhost:8000/admin/ and log in with the super user account and you will see the model registered.

Manager isn't available while setting up django-fmc

I'm trying to get django-fmc set up with Django (v 1.97, Python v2.7.12, djangorestframework v3.3.3) to handle storing registration ids and sending notifications to devices. I am following the tutorial they provide but it doesn't seem to be working.
I am getting the following error when running my local server and python manage.py fcm_urls:
...
File "C:\Work\Dev\LiveTracking\Api\app\views.py", line 50, in DeviceViewSet
queryset = Device.objects.all()
File "C:\Work\Dev\LiveTracking\Api\env\lib\site-packages\django\db\models\manager.py", line 277, in __get__
self.model._meta.swapped,
AttributeError: Manager isn't available; 'fcm.Device' has been swapped for 'app.MyDevice'
I don't want to add additional fields to the MyDevice model for now. I've looked all over but can't fix this error. If anyone can shed some insight into this error it would be much appreciated.
Here are some of my code snippets:
settings.py
INSTALLED_APPS = (
'fcm',
)
# Firebase Cloud Messaging Key
FCM_APIKEY = 'AIzaSyCaqHZIcaGDOpfTZUmAHEowsqD-fCtow6A'
# Location of device model
FCM_DEVICE_MODEL = 'app.MyDevice'
serializers.py
from fcm.models import Device
class DeviceSerializer(serializers.ModelSerializer):
class Meta:
model = Device
fields = ('dev_id','reg_id','name','is_active')
views.py
from rest_framework import viewsets
from fcm.models import Device
from fcm.serializers import DeviceSerializer
class DeviceViewSet(viewsets.ModelViewSet):
queryset = Device.objects.all()
serializer_class = DeviceSerializer
urls.py
from rest_framework import routers
from fcm.views import DeviceViewSet
router = routers.DefaultRouter()
router.register(r'devices', DeviceViewSet)
urlpatterns = [
url(r'^v1/', include(router.urls)),
]
swappable is an undocumented feature, actually only supposed to be used for custom User models. The doc on custom user models clearly states that once you use a custom user model, directly referencing contrib.auth.models.User won't work:
If you reference User directly (for example, by referring to it in a foreign key), your code will not work in projects where the AUTH_USER_MODEL setting has been changed to a different user model.
You probably want to read the rest of this chapter FWIW.
To make a long story short: as Daniel Roseman mentions, you very probably want to use your own MyDevice model instead of the default Device one. And eventually contribute back a patch to django-fcm doc if it solves the issue.

Cannot create form field for 'country' yet, because its related model 'address.Country' has not been loaded yet (when upgrading Django 1.8 to 1.9)

I'm developing a subscription site which includes a 'signup' app. I'm also using a django-oscar shop for one-off purchases and using its UserAddress classes across the whole site. However, as my address and username/email forms are on the same page at subscription signup I use a temporary custom ModelForm based on AbstractAddress with specific fields in signup/forms.py:
# signup/forms.py
from oscar.apps.address.abstract_models import AbstractAddress
class CustomAddressForm(ModelForm):
class Meta:
"""
Using AbstractAddress because UserAddress requires a User and there
is none when signup form is displayed. A UserAddress instance is then
created later, using the User object created after request.POST.
"""
model = AbstractAddress
fields = ['line1', 'line2', 'line4', 'state', 'postcode', 'country']
With INSTALLED_APPS:
# settings.py
from oscar import get_core_apps
INSTALLED_APPS = [
...
'signup',
...
] + get_core_apps()
It's all been working fine in Django 1.8 but I've just tried upgrading to 1.9 prior to deploying and I get the following error message:
File "path/to/python3.4/django/db/models/fields/related.py", line 942, in formfield(self.name, self.remote_field.model))
Cannot create form field for 'country' yet, because its related model 'address.Country' has not been loaded yet
Presumably I could move my custom modelform into the django-oscar core but would rather not.
I've seen this question but as the model in my case is called in the form's Meta fields list as the string 'country', I'm not sure how to import the Country model here.
I can't find any sign of ModelForms having changed in Django 1.9. Or does anyone know why my form would work in 1.8 but not 1.9?

django framework can't see new model online

I have to make some modification to a website built with the django framework (version 1.6).
The problem I am having is that I can not transfer the modification I made offline to the online server. I can see the new page, the database has been modified, but in the administration website the new category I created does not appear, thus i can not fill the fields with the new information.
The steps I went through are:
create the new model in models.py,
import the model in admin.py,
execute the command: touch wsgi.py
in order to reload the file.
In the offline version everything is working fine. I do not know that to do!
Code I added in admin.py file (I added the "Article" section):
from active.models import x, z, y, j, Article
class ArticleAdmin(admin.ModelAdmin):
ordering = ["title"]
list_display = ('title',)
search_fields = ['title']
admin.site.register(Article, ArticleAdmin)
Solved.
There was no problem at all, simply the user I access the administration site with did not have the right access to see the new section!
Have you imported admin in the admin.py file?
from django.contrib import admin

Categories

Resources