This is my forms.py file!!!
from django import forms
from . models import URLModel
class URLForm(forms.ModelForm):
class Meta:
model = 'URLModel'
fields = ['url']
This is my models.py file
from django.db import models
# Create your models here.
class URLModel(models.Model):
url=models.URLField(unique=True)
short=models.CharField(max_length=200,unique=True)
def __str__(self):
return self.url
Now i just wanted to ask that why this error is coming and i have revieved and i cant observe any error for real...please help
# Remove single quote from your model specification in forms.py
from django import forms
from .models import URLModel
class URLForm(forms.ModelForm):
class Meta:
model = URLModel
fields = ('url',)
Related
In my django app I want to set focus to the first CharField (task) when the page loads.
my models.py is
from django.db import models
class ListModel(models.Model):
task = models.CharField(max_length=255)
status = models.BooleanField(default=False)
def __str__(self):
return f"{self.task} : {str(self.status)}"
and forms.py is
from django.forms import ModelForm
from .models import ListModel
class ListForm(ModelForm):
class Meta:
model = ListModel
fields = ["task", "status"]
I have tried adding the following widget in my CharField (in models.py):
task = models.CharField(max_length=255, widget=models.TextInput(attrs={'autofocus': True})
but it gives an AttributeError: module 'django.db.models' has no attribute 'TextInput'
I have also tried adding the following to the ListForm class (in forms.py):
def __init__(self):
self.fields['task'].widget.attrs.update(autofocus = 'autofocus')
though I am not getting any error for this, but when I load my page the focus is not set to the task CharField either. What can I do add auto-focus to my CharField?
You are confusing model fields (which are used to store data in the database), and form fields, which are used to obtain, validate and clean data the user has entered.
You thus work with:
from django.forms import ModelForm
from django import forms
from .models import ListModel
class ListForm(ModelForm):
# forms ↓
task = forms.CharField(
max_length=255,
# forms ↓
widget=forms.TextInput(attrs={'autofocus': True})
)
class Meta:
model = ListModel
fields = ['task', 'status']
I create and save user from django-rest-framework, but it do when i am anonymous user. Now i dont see those model in django-admin. How to add model to django-admin?
admin.py
from django.contrib import admin
from possible_blacklist.models import PossibleBlacklist
class PossibleBlacklistAdmin(admin.ModelAdmin):
list_display = [field.name for field in PossibleBlacklist._meta.get_fields()]
admin.site.register(PossibleBlacklist, PossibleBlacklistAdmin)
serializers.py
from rest_framework import serializers
from possible_blacklist.models import PossibleBlacklist
class PossibleBlacklistSerializer(serializers.ModelSerializer):
class Meta:
model = PossibleBlacklist
fields = '__all__'
def create(self, validated_data):
return PossibleBlacklist.objects.create(**validated_data)
def validate_mobile_phone(self, data):
if data.startswith('0'):
raise serializers.ValidationError("Номер должен начинаться на +380")
return data
I had this problem and when I research, I've found this good documentation which will add the model automatically to your Django admin interface.
and no need to touch your admin with every single model which are you adding.
https://medium.com/hackernoon/automatically-register-all-models-in-django-admin-django-tips-481382cf75e5
This is my first time using Django and I am completely stuck at how to use ModelForms in my project. I have been able to follow the online tutorials this far but without ModelForms(to add data into a Postgresql database), I can't proceed onward. I am trying to simply make a form page that lets the users add a few inputs (2 datefields and 1 textfield) and by submitting that form, the data will be added to the database.
The error I have been getting is:
AttributeError: 'Hyuga_Requests' object has no attribute 'name' [where Hyuga_Request is a class set in the models.py]
models.py
from __future__ import unicode_literals
from django.db import models
from django.forms import ModelForm
class Hyuga_Requests(models.Model):
name = models.CharField(max_length=50)
s_date = models.DateField(auto_now=True)
e_date = models.DateField(auto_now=True)
reason = models.TextField(max_length=500)
def __unicode__(self):
return self.name
views.py
from django.shortcuts import render
from django import forms
from .forms import Hyuga_RequestForm
def create_req(request):
form = Hyuga_RequestForm()
context = {"form":form,}
return render(request,"request_form/requestform.html", context)
forms.py
from django import forms
from .models import Hyuga_Requests
from django.forms import ModelForm
class Hyuga_RequestForm(forms.ModelForm):
class Meta:
model = Hyuga_Requests()
fields = ['name','s_date','e_date','reason']
Please help this noobie...
Don't instantiate the model in the class Meta inside the Hyuga_RequestForm class.
model = Hyuga_Requests() should be model = Hyuga_Requests
model = Hyuga_Requests() -> model = Hyuga_Requests
The error come because you are calling the model on the form.
from django import forms
from .models import Hyuga_Requests
from django.forms import ModelForm
class Hyuga_RequestForm(forms.ModelForm):
class Meta:
model = Hyuga_Requests
fields = ['name','s_date','e_date','reason']
Note: i suggest to you use on the any class you define on python not use "_", you can check more about PEP8 and code styles here: https://www.python.org/dev/peps/pep-0008/
So here is the code that I am working with right now
models.py
from django.db import models
class Building(models.Model):
name = models.TextField(max_length=60)
def __str__(self):
return self.name
class Charge(models.Model):
item = models.CharField(max_length=60)
cost = models.CharField(max_length=15)
last_updated = models.DateField(default='',auto_now=True)
buildings = models.ManyToManyField(Building)
def __str__(self):
return self.item
admin.py
from django.contrib import admin
from rlscharges.models import Charge, Building
from django.db import models
from django.forms import CheckboxSelectMultiple
class MyModelAdmin(admin.ModelAdmin):
formfield_overrides = {
models.ManyToManyField: {'widget': CheckboxSelectMultiple},
}
class BuildingInline(admin.TabularInline):
model = Charges.building.through
class BuildingAdmin(MyModelAdmin):
fields = ['name']
inlines = [BuildingInline]
admin.site.register(Charge, MyModelAdmin)
admin.site.register(Building, BuildingAdmin)
I basically just want the checkboxselectmultiple to show up on the Charge and Building models admin pages. Right now the checkbox only shows up on the Charge model and the TabularInline shows up on the Building model. Is there a way to get formfield_overrides to apply to the BuildingInline so it shows the checkboxes and not the TabularInline? Or do I need to do something to the relationship of the models? I apologize ahead of time if this is a stupid question, I am just getting started with django.
I have completed my models and I am trying to customise the admin model for a particular model.
Here is my admin.py
from project.base.models import *
from django.contrib import admin
from django import forms
class StaffModuleForm(forms.ModelForm):
user = forms.ModelChoiceField(queryset=User.objects.all())
class Meta:
model = StaffModule
class StaffModuleAdmin(admin.ModelAdmin):
form = StaffModuleForm
class Meta:
pass
Modules = [UserProfile, Student, Module, StaffModule, Exercise, Result]
admin.site.register(Modules)
and here is the model in question
class StaffModule(models.Model):
user = models.ForeignKey(User)
modules = models.ManyToManyField(Module) # Field name made lowercase.
department = models.CharField(max_length=6)
def __unicode__(self):
return str(self.user)
Here is the error I am currently unable to pass:
AttributeError at /admin/base/staffmodule/2/
type object 'StaffModuleAdmin' has no attribute '_meta'
Here is the trace: http://pastebin.com/tCJ9Q978
I would really appreciate some help, as I believe I am following the django admin docs and i am not quite sure what the issue is.
Thanks.
The problem is in this:
class StaffModuleAdmin(admin.ModelAdmin):
form = StaffModuleForm
class Meta:
pass
Inner Class Meta should not be defined for the admin.ModelAdmin class.