Django TabularInline error in the admin.py file - python

Hey guys i have been trying to create an inline TabularInline view of the my model in the django admin.py file. I am facing an issue where i am getting the following error in the code below.
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/home/brian/Desktop/django react learning /site/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "/home/brian/Desktop/django react learning /site/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run
self.check(display_num_errors=True)
File "/home/brian/Desktop/django react learning /site/lib/python3.8/site-packages/django/core/management/base.py", line 442, in check
raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
<class 'tweets.admin.TweetlikeAdmin'>: (admin.E202) 'tweets.Tweet' has no ForeignKey to 'tweets.Tweet'.
So at first I thought I had missed something but when I tried changing it I got more errors which really don't make sense. so I made sure I share with you my models.py file and my admin.py file
here is my models.py file
class Tweetlike(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
tweet = models.ForeignKey('Tweet',on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
class Tweet(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE) #this means that one user can own tweets
likes = models.ManyToManyField(User,related_name='tweet_user', blank=True, through=Tweetlike)
content = models.TextField(blank=True,null=True)
timestamp = models.DateTimeField(auto_now_add=True)
image = models.FileField(upload_to='images/',blank=True,null=True)
def __str__(self):
return self.content
and lastly here is the admin.py file. this is where the error is coming from when i tried running the server
class TweetlikeAdmin(admin.TabularInline):
model = Tweet
class TweetAdmin(admin.ModelAdmin):
inlines = [TweetlikeAdmin,]
list_display = ['__str__','user']
search_fields = ['content','user__username', 'user__email']
class Meta:
model = Tweet
admin.site.register(Tweet,TweetAdmin)

You've not set the correct model, you've got them both pointing at the Tweet model. Change the inline model;
class TweetlikeAdmin(admin.TabularInline):
model = Tweetlike

Related

how to bind two models in django

please help a beginner. I'm trying to build a poll app in Django and I want to change my admin panel so that I can change and add questions and choices in the same page iv already tried to create a new model and bind the question and choice model together but didn't work please help me.
this is my models.py inside my poll app and another problem I have is that I want to have different numbers of choices for different questions but I don't know how to write
from django.db import models
# Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
class Bind(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
add_question =Question(question_text=question_text,pub_date=pub_date)
choice_text_1= models.CharField(max_length=200,default='yes')
votes_1= models.IntegerField(default=0)
choice_text_2= models.CharField(max_length=200,default='yes')
votes_2= models.IntegerField(default=0)
choice_text_3= models.CharField(max_length=200,default='yes')
votes_3= models.IntegerField(default=0)
choice_text_4= models.CharField(max_length=200,default='yes')
votes_4= models.IntegerField(default=0)
add_choice1=Choice(choice_text=choice_text_1,votes=votes_1)
add_choice2=Choice(choice_text=choice_text_2,votes=votes_2)
add_choice3=Choice(choice_text=choice_text_3,votes=votes_3)
add_choice4=Choice(choice_text=choice_text_4,votes=votes_4)
def __str__(self):
return self.question_text
return self.choice_text
and this is my admin panel id like to change it that I can add question with different number of choices and when I save I can find save question in question model pannel and choices in the choice model panel please help me I'm a beginner
enter image description here
and this is views.py file:
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/detail.html', {'question': question,'error_message': "You didn't select a choice.",})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
and the error by executing the python manage.py migrate
C:\projects\AM\FM\mysite>python manage.py migrate Operations to
perform: Apply all migrations: admin, auth, contenttypes, polls,
sessions Running migrations: Applying
polls.0009_auto_20200914_1002...Traceback (most recent call last):
File
"C:\projects\AM\FM\lib\site-packages\django\db\models\fields_init_.py",
line 1774, in get_prep_value
return int(value) ValueError: invalid literal for int() with base 10: 'choice'
The above exception was the direct cause of the following exception:
Traceback (most recent call last): File "manage.py", line 22, in
main() File "manage.py", line 18, in main
execute_from_command_line(sys.argv) File "C:\projects\AM\FM\lib\site-packages\django\core\management_init_.py",
line 401, in execute_from_command_line
utility.execute() File "C:\projects\AM\FM\lib\site-packages\django\core\management_init_.py",
line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\projects\AM\FM\lib\site-packages\django\core\management\base.py",
line 330, in run_from_argv
self.execute(*args, **cmd_options) File "C:\projects\AM\FM\lib\site-packages\django\core\management\base.py",
line 371, in execute
output = self.handle(*args, **options) File "C:\projects\AM\FM\lib\site-packages\django\core\management\base.py",
line 85, in wrapped
res = handle_func(*args, **kwargs) File "C:\projects\AM\FM\lib\site-packages\django\core\management\commands\migrate.py",
line 243, in handle
post_migrate_state = executor.migrate( File "C:\projects\AM\FM\lib\site-packages\django\db\migrations\executor.py",
line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File
"C:\projects\AM\FM\lib\site-packages\django\db\migrations\executor.py",
line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File
"C:\projects\AM\FM\lib\site-packages\django\db\migrations\executor.py",
line 227, in apply_migration
state = migration.apply(state, schema_editor) File "C:\projects\AM\FM\lib\site-packages\django\db\migrations\migration.py",
line 124, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File
"C:\projects\AM\FM\lib\site-packages\django\db\migrations\operations\fields.py",
line 104, in database_forwards
schema_editor.add_field( File "C:\projects\AM\FM\lib\site-packages\django\db\backends\sqlite3\schema.py",
line 328, in add_field
self.remake_table(model, create_field=field) File "C:\projects\AM\FM\lib\site-packages\django\db\backends\sqlite3\schema.py",
line 189, in remake_table
self.effective_default(create_field) File "C:\projects\AM\FM\lib\site-packages\django\db\backends\base\schema.py",
line 303, in effective_default
return field.get_db_prep_save(self.effective_default(field), self.connection) File
"C:\projects\AM\FM\lib\site-packages\django\db\models\fields\related.py",
line 971, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection) File
"C:\projects\AM\FM\lib\site-packages\django\db\models\fields_init.py",
line 823, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False) File
"C:\projects\AM\FM\lib\site-packages\django\db\models\fields_init.py",
line 2388, in get_db_prep_value
value = self.get_prep_value(value) File "C:\projects\AM\FM\lib\site-packages\django\db\models\fields_init.py",
line 1776, in get_prep_value
raise e.class( ValueError: Field 'id' expected a number but got 'choice'.
You cannot directly assign other models to other model's fields. You have to use either ForeignKey (One Object To Many Referrable Objects) or ManyToManyField (Many Objects Can Be Contained To This Object).
At this point, you might want to consider making class Bind to class Questionnaire since you're combining them.
With that, with fixes applied and redundancies, this should be the final code (for inheritances only!)
class Question(models.Model):
question_text = models.CharField(max_length=200)
question_choices = models.ForeignKey("Choice", on_delete=models.CASCADE)
pub_date = models.DateTimeField(help_text='date published', auto_now_add=True)
def __str__(self):
return self.question_text
# No need to refer to the `Question` Model unless you have something to do important.
# Cross-Reference is okay, but its redundant unless special handling is required (for instance, you want pure integrity of ownership of this object, etc. But its quite hard to manage if your models were scaling.)
class Choice(models.Model):
# question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
class Questionnaire(models.Model):
questions = models.ManyToManyField("Question", blank=True)
pub_date = models.DateTimeField(help_text='date published', auto_now_add=True)
def __str__(self):
return self.question_text
NOTES:
If you read the changes closely, you might see yourself, why I assigned the object in "str" form? That's because Django was able to load objects, even or after the one who requires it. Meaning, You don't need to put another object on the top to refer at, but rather, just put it in str reference even the object is placed anywhere and you're good to go.
Note that in DateTimeField, you would want to consider auto_now_add=True, it automatically handles the time where this object has been saved for the first time.
I want to make all choices under Question. This would be nice because if you want to make a question, there's a field available for you to create a choice to.
I changed Bind with Questionnaire for clarity. This should be enough to see the relationship or inheritance to your model.
I used ManyToManyField to set number of questions (or objects) to this Questionnaire.
Usually, in such cases, you don't need to create "Bind" model. You just need to add "sequence" integer field into your Choice model. Then, each question can have infinite number of choices, for example:
Choice.objects.create(question=question1, sequence=0)
Choice.objects.create(question=question1, sequence=1)
Choice.objects.create(question=question1, sequence=2)...

Error while importing data with foreign keys in django import-export

I have implemented importing data using django import-export library. When i try to import data with names of object that do not exists it throws error matching query does not exist.
It ends with generating template with error stack trace like this:
Line number: 1 - CustomUser matching query does not exist.
sample#sample.com, data1, firstname, secondname
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/import_export/resources.py", line 520, in import_row
self.import_obj(instance, row, dry_run)
File "/usr/local/lib/python3.7/site-packages/import_export/resources.py", line 385, in import_obj
self.import_field(field, obj, data)
File "/usr/local/lib/python3.7/site-packages/import_export/resources.py", line 368, in import_field
field.save(obj, data, is_m2m)
File "/usr/local/lib/python3.7/site-packages/import_export/fields.py", line 110, in save
cleaned = self.clean(data)
File "/usr/local/lib/python3.7/site-packages/import_export/fields.py", line 66, in clean
value = self.widget.clean(value, row=data)
File "/usr/local/lib/python3.7/site-packages/import_export/widgets.py", line 364, in clean
return self.get_queryset(value, row, *args, **kwargs).get(**{self.field: val})
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 408, in get
self.model._meta.object_name
accounts.models.CustomUser.DoesNotExist: CustomUser matching query does not exist.
Custom resouce import class:
class UserResourceImport(resources.ModelResource):
""" Resource class for import utilities """
# set foreign key relations for model, this way we can provide name instead of id
custom_user = fields.Field(column_name='custom_user',
attribute='custom_user',
widget=ForeignKeyWidget(CustomUser, 'name'))
class Meta:
model = user_model
fields = ('email','custom_user','first_name','last_name')
skip_unchanged = False
report_skipped = True
export_order = ('email', 'custom_user', 'first_name', 'last_name')
import_id_fields = ['email']
Every other error of importing will result in generation of following template:
Normal error
Is there any way to handle this error so it won't print stack trace into the import template and skip row with invalid data?

Django Error (Attribute): 'CharField' object has no attribute 'is_related'

I am trying to make a description to every user, in my new project. But i get an error when i try to makemigrations. I do not know how to fix it.
I have tried different things but nothing worked, my coding is maybe very bad, but i am also new to python and django.
The Error:
C:\Users\bruger\Dropbox\min-login-web\web_login>python manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 353, in execute
output = self.handle(*args, **options)
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\makemigrations.py", line 143, in handle
loader.project_state(),
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\loader.py", line 322, in project_state
return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps))
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\graph.py", line 378, in make_state
project_state = self.nodes[node].mutate_state(project_state, preserve=False)
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\migration.py", line 87, in mutate_state
operation.state_forwards(self.app_label, new_state)
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\operations\models.py", line 85, in state_forwards
list(self.managers),
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\state.py", line 377, in __init__
if field.is_relation and hasattr(field.related_model, '_meta'):
AttributeError: 'CharField' object has no attribute 'is_relation'
My Models file:
from django import forms
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from PIL import Image
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
def save(self):
super().save()
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.image.path)
class Desc(models.Model):
description = forms.CharField(widget = forms.Textarea, max_length = 250, required=False)
def __str__(self):
return f'{self.user.username} Desc'
I Hope somebody can help me, because this is really getting on my nerves.
You mixed forms and models. A model does not specify a (HTML) form, it specifies how the database should store data, so you need to use a models.CharField:
class Desc(models.Model):
description = models.CharField(max_length=250)
Such CharField has no widget assigned to it, this is something you should handle at the form level.
You probably will need to make migrations, since up to this point, there was no description field in your Desc model.
I agree to some extent that it is confusing that the forms have frequently a field with the same name (well those typically are the default form fields for the model field with the same name). The idea is however that model fields specify the columns in a database, whereas form fields specify text boxes, check boxes, etc. in a (HTML) form.

Using OneToOneField in Django

I'm realized some models in application:
from django.db import models
class Commentary(models.Model):
user_id = models.ForeignKey(User)
created_date = models.DateField()
comment = models.TextField()
class Role(models.Model):
role_name = models.CharField(max_length=25)
class User(models.Model):
login = models.CharField(max_length=50)
password = models.CharField(max_length=50)
address = models.CharField(max_length=255)
phone = models.CharField(max_length=25)
postcode = models.CharField(max_length=25)
email = models.EmailField()
role_id = models.OneToOneField(Role)
After that typed in console "python manage.py makemigration mainws" for making migrations in my database, however, taken stacktrace with error. If looking in django documentation for one-to-one example, we can see the similarity with him, but without option primary_key=True. How can I fix this or maybe better using ForeignKey with unique=True for this issue, or something other?
Stacktrace:
=> python manage.py makemigration mainws
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/savicvalera/code/lab8/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/Users/savicvalera/code/lab8/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute
django.setup()
File "/Users/savicvalera/code/lab8/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/savicvalera/code/lab8/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/Users/savicvalera/code/lab8/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/usr/local/Cellar/python/2.7.8_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/savicvalera/code/lab8/website/mainws/models/__init__.py", line 1, in <module>
from . import Commentary, MailList, Product, Provider, Rate, Review, Role, Sale, ShoppingCart, Status, Supplies, User
File "/Users/savicvalera/code/lab8/website/mainws/models/Commentary.py", line 11, in <module>
from . import Product, User
File "/Users/savicvalera/code/lab8/website/mainws/models/User.py", line 14, in <module>
class User(models.Model):
File "/Users/savicvalera/code/lab8/website/mainws/models/User.py", line 21, in User
role_id = models.OneToOneField(Role,to_field='id')
File "/Users/savicvalera/code/lab8/lib/python2.7/site-packages/django/db/models/fields/related.py", line 1799, in __init__
super(OneToOneField, self).__init__(to, to_field, OneToOneRel, **kwargs)
File "/Users/savicvalera/code/lab8/lib/python2.7/site-packages/django/db/models/fields/related.py", line 1612, in __init__
assert isinstance(to, six.string_types), "%s(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT)
AssertionError: OneToOneField(<module 'mainws.models.Role' from '/Users/savicvalera/code/lab8/website/mainws/models/Role.pyc'>) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string u'self'
If I understand your code organization correctly, the problem is in your imports. When you say
from . import Role
you're importing Role.py into a module object named Role. Inside that module (I assume) is your Role model class. So what you really want is:
from .Role import Role
Or:
from . import Role
...
role_id = models.OneToOneField(Role.Role)
You should define an app_label in your meta class
class Foo(models.Model):
class Meta:
app_label = 'mainws'

Cannot Create Superuser After Add Custom User Model

I create CustomUser class that extends AbstractUser, and add a ForeignKey field that reference to City Model
class City(models.Model):
created_dt = models.DateTimeField("Created Time", auto_now_add=True)
code = models.CharField(max_length=64, unique=True)
name = models.CharField(max_length=64)
class CustomUser(AbstractUser):
city = models.ForeignKey(City)
REQUIRED_FIELDS = ['city']
I add the CustomUser to setting:
AUTH_USER_MODEL = "myapp.CustomUser"
When I tried to syncdb, it prompted me to create super user, when I fill in the city, I got this error:
City: 1
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
utility.execute()
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/core/management/base.py", line 242, in run_from_argv
self.execute(*args, **options.__dict__)
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/core/management/base.py", line 285, in execute
output = self.handle(*args, **options)
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 116, in handle
user_data[field_name] = field.clean(raw_value, None)
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 255, in clean
self.validate(value, model_instance)
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 1201, in validate
using = router.db_for_read(model_instance.__class__, instance=model_instance)
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/db/utils.py", line 250, in _route_db
return hints['instance']._state.db or DEFAULT_DB_ALIAS
AttributeError: 'NoneType' object has no attribute '_state'
can someone explain to me why ?
I'm still a newbie in django, thanks
You can't set a required field to be a foreign key according to the docs. There's a ticket open with something similar to what you're encountering. I'd suggest subclassing CustomUserManager and override the create_superuser method on it, then use it for the objects manager on your CustomUser model.

Categories

Resources