I need to have four file fields for my model so i am using Django inline model for that. I also need to create a model for with all thode fields so that the user can fill out the form and i am using Class based views- CreateView for that. However i do not know how to get the file fields in my model form.
Models.py
class Product(models.Model)
name= models.Charfield(maxlength=50)
city= models.Charfield(maxlength=50)
state=model.Charfield(maxlength=50)
year=models.Integerfield(blank=True, null=True)
class ProductAttachment(models.Model)
attachment = models.ForeignKey(Product, related_name='attachment')
appendix_a= models.Filefield(verbose_name='Appendix A')
appendix_b= models.Filedield(verbose_name='Appendix B')
Other = models.Filefield()
Admin.py
class ProductInline(admin.StackedInline)
model=ProductAttachment
class ProductAdmin(admin.modelAdmin)
inlines= [ProductInline,]
model=Product
admin.site.register(Product, ProductAdmin)
forms.py
class ProductForm(models.form):
class Meta:
model=Product
fields='__all__'
Views.py
class ProductCreateView(CreateView):
model=Product
form_class = ProductForm
However i do not know how to get all the filefield in the form. Any help is highly appreciated. Thank you
Looking at your code the model for your ProductForm and ProductCreateView is Product, which does not contain any FileFiled. You need to create form/view for ProductAttachment as well.
Related
I want to add a field for keywords that almost every model in my site will have. It would be ideal if I didn't have to define a "TaggedPage" class for every Page model. So I created a BasePage abstract model but ParentalKey doesn't appear to work with an abstract model. How can I solve this?
I get this error:
home.TaggedPage.content_object: (fields.E300) Field defines a relation with model 'home.BasePage', which is either not installed, or is abstract.
home.TaggedPage.content_object: (fields.E307) The field home.TaggedPage.content_object was declared with a lazy reference to 'home.basepage', but app 'home' doesn't provide model 'basepage'.
home/models.py contains these models:
class PageTag(TagBase):
""" Tag used for the keywords meta html tag"""
class Meta:
verbose_name = "search/meta keyword"
verbose_name_plural = "search/meta keywords"
class TaggedPage(ItemBase):
tag = models.ForeignKey(
PageTag,
related_name="tagged_pages",
on_delete=models.CASCADE,
)
content_object = ParentalKey(
to='home.BasePage',
on_delete=models.CASCADE,
related_name='tagged_items'
)
class BasePage(MetadataPageMixin, Page):
tags = ClusterTaggableManager(
through='home.TaggedPage',
blank=True,
help_text="Used for the keywords meta html tag",
)
promote_panels = Page.promote_panels + [
FieldPanel('tags'),
]
class Meta:
abstract = True
class HomePage(BasePage):
parent_page_types = []
Point the ParentalKey at the Page model instead:
content_object = ParentalKey(
to='wagtailcore.Page',
on_delete=models.CASCADE,
related_name='tagged_items'
)
At the database level this will have the behaviour you're looking for: a foreign key field referencing the ID of the page object. The one minor side effect is that the tagged_items relation will be defined on all Page objects, not just ones inheriting from BasePage, but that shouldn't cause any problems.
I have a #property in my model which is basically a string of several values in the model combined.
#property
def mfg_link(self):
return ''.join('http://mfg.com/model/' + str(self.model_numer))
I can add this mfg_link to the list_display on the admin model and it works fine, but its not showing up in the generated table when I pass the queryset to the table, the other fields show up fine.
This seems like something obvious, but unfortunately the couple of hours of searching didn't help.
Thanks a lot!
Do it like this in Table class:
class TableClass(tables.Table):
mfg_link = tables.Column('mfg_link', order_by='model_numer')
class Meta:
model = SomeModel
sequence = 'model_numer', 'mfg_link'
I want to get my object index as a "resource_uri" instead id
I take the usual way I make a model , views , serializers :
class User(BaseModel):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
models.CharField()
class UserSerailizers(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id','user','formatted_address')
classclass UserList(generics.ListCreateAPIView):
queryset = Image.objects.all()
serializer_class = UserSerializer
when i call < my_domain/user/ > I get this response
{
id:1,
name:'toto'
}
but I want to have an answer to this form:
{
'url': my_domain/user/1/
'name': 'toto'
}
Any thoughts?
If you want a hyperlink instead of a primary key in your model representations, you have to use either HyperlinkedModelSerializer or more generic Serializer along with HyperlinkedIdentityField and/or HyperlinkedRelatedField. The former is probably what you are looking for.
The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys.
See Django REST framework documentation for more details.
As already commented, you need to use the HyperlinkedModelSerializer as you've shown.
The lookup_field attribute should be inside the Meta class.
And the latest and this is a guess: You just have a ListView for your User model. In order to show the detail for the user, you need also the retrieve method. I would recommend you using the ModelViewset so it automatically implements all methods.
I am trying to build an example app in Google App Engine using django-nonrel. and am having problems implementing ListField attribute into a model.
I have created an app test_model and have included it as an installed app in my settings. The model.py is:
from django.db import models
from djangotoolbox import *
from dbindexer import *
# Create your models here.
class Example(models.Model):
some_choices = models.ListField('Choice_examples')
notes = models.CharField(max_length='20')
updated_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return u'%s' % (self.notes)
class Choice_examples(models.Model):
name = models.CharField(max_length='30')
def __unicode__(self):
return u'%s' % (self.name)
The above example gives me:
AttributeError:'module' object has no attribute 'Model'
If I comment out the djangotoolbox import, I get the following :
AttributeError: 'module' object has no attribute 'ListField'
What am I doing wrong here? I can't seem to find any documention as to how to go about using ListField in django-nonrel. Is that because it is supposed to really obvious?
Your imports are smashing each other:
from django.db import models
from djangotoolbox import *
The second import will replace the django.db models with djangotoolbox' empty models module. Using from X import * is a terrible idea in general in Python and produces confusing results like these.
If you're looking to use ListField from djangotoolbox, use:
from djangotoolbox import fields
and refer to the ListField class as fields.ListField.
OK, here is what I did to be able to use ListFields. MyClass the equivalent to your Example class and AnotherClass is the same as your Choice_examples. What I describe will allow you to use ListFields in the admin interface and your self implemented views.
I'll start from the beginning
This is what what my model looks like
class MyClass(models.Model):
field = ListField(models.ForeignKey(AnotherClass))
I wanted to be able to use the admin interface to create/edit instances of this model using a multiple select widget for the list field. Therefore, I created some custom classes as follows
class ModelListField(ListField):
def formfield(self, **kwargs):
return FormListField(**kwargs)
class ListFieldWidget(SelectMultiple):
pass
class FormListField(MultipleChoiceField):
"""
This is a custom form field that can display a ModelListField as a Multiple Select GUI element.
"""
widget = ListFieldWidget
def clean(self, value):
#TODO: clean your data in whatever way is correct in your case and return cleaned data instead of just the value
return value
These classes allow the listfield to be used in the admin. Then I created a form to use in the admin site
class MyClassForm(ModelForm):
def __init__(self, *args, **kwargs):
super(MyClasstForm,self).__init__(*args, **kwargs)
self.fields['field'].widget.choices = [(i.pk, i) for i in AnotherClass.objects.all()]
if self.instance.pk:
self.fields['field'].initial = self.instance.field
class Meta:
model = MyClass
After having done this I created a admin model and registered it with the admin site
class MyClassAdmin(admin.ModelAdmin):
form = MyClassForm
def __init__(self, model, admin_site):
super(MyClassAdmin,self).__init__(model, admin_site)
admin.site.register(MyClass, MyClassAdmin)
This is now working in my code. Keep in mind that this approach might not at all be well suited for google_appengine as I am not very adept at how it works and it might create inefficient queries an such.
I don't know, but try with:
class Choice_examples(models.Model):
name = models.CharField(max_length='30')
def __unicode__(self):
return u'%s' % (self.name)
class Example(models.Model):
some_choices = models.ListField(Choice_examples)
notes = models.CharField(max_length='20')
updated_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return u'%s' % (self.notes)
Looks like the answer is that you cannot pass an object into fields.ListField.
I have ditched trying to work with ListField as documentation is limited and my coding skills aren't at a level for me to work it out.
Anyone else coming across a similar problem, you should consider create a new model to map the ManyToMany relationships. And if the admin view is important, you should look into the following to display the ManyToMany table inline with any given admin view:
http://docs.djangoproject.com/en/1.2/ref/contrib/admin/#s-working-with-many-to-many-models
I get really confused with many-to-many database relationships, so can some one please clarify how I would achieve this?
I need a table of "Tags" (as in tag words) and a table for "Entries", such at many "Entries" could correspond to many Tag words.
Right now I have my models like this:
# models.py
class Tags(models.Model):
tag = models.CharField(max_length=255)
entry = models.ManyToManyField(Entry)
class Entry(models.Model):
entry = models.CharField(max_length=255)
description = models.TextField()
Now I'm confused, how would I setup my admin.py so I could then add tags when I create a new entry?
What you need is using the through feature of models:
class Tag(models.Model):
tag = models.CharField(max_length=255)
entry = models.ManyToManyField(Entry, through='TaggedEntries')
class Entry(models.Model):
entry = models.CharField(max_length=255)
description = models.TextField()
class TaggedEntries(models.Model):
entry = models.ForeignKey(Entry)
tag = models.ForeignKey(Tag)
and now use that model in your admin:
class TagsInline(admin.TabularInline):
model = TaggedEntries
extra = 1
class EntryAdmin(admin.ModelAdmin):
inlines = (TagsInline, )
admin.site.register(Entry, EntryAdmin)
admin.site.register(Tag)
You will need something along the lines of:
# admin.py
from django.contrib import admin
from models import *
class TagsInline(admin.TabularInline):
model = Tag
extra = 1
class EntryAdmin(admin.ModelAdmin):
inlines = (TagsInline, )
admin.site.register(Entry, EntryAdmin)
admin.site.register(Tag)
(Note, this code was written in a browser!)