I am facing weird issue, after wasting so much time I found out that this is the problem because of Database cache.
I made a Model Name "Profile" later flushdb / deleted it.
After few hours I made it again but getting this error
"No such column"
then I removed all sql3db files *.pyc file etc,
& run my model again (so django will recreate db structure {also performed migrate & makemigrations}).
But still same error,
then I just renamed my db & the same code working now fine.
My problem is I have to use that old Old Model name again
but not able to get because of db cache (or maybe something)
please guide me.
admin.py
from django.contrib import admin
from django.contrib.auth.models import User
from .models import Profiles
admin.site.register(Profiles)
my model:
from django.contrib.auth.models import User
from django.db import models
class Profiles(models.Model):
# p2= models.CharField(max_length=14)
phone = models.CharField(max_length=14)
city = models.CharField(max_length=20)
province = models.CharField(max_length=20)
username2 = models.ForeignKey(User, on_delete=models.CASCADE)
Note: I have tried all old solution available on this web,
but in my case not working.
Please check this django documentation link,it will surly helps you.
https://docs.djangoproject.com/en/2.1/topics/cache/
here are the basic related queries,it may helpful for understanding.
# You can delete keys explicitly with delete(). This is an easy way of clearing the
#cache for a particular object:
#cache.delete(key, version=None)
#cache.delete_many(['a', 'b', 'c'])
#cache.clear()
Related
I am relatively new to Django and I'm looking for some guidance in how to setup permissions in a certain way. Basically I have an app that consists of a couple of models similar to this:
class Project(models.Model):
name = models.CharField(max_length=100)
users = models.ManyToManyField(CustomUser, related_name="projects")
class Task(models.Model):
name = models.CharField(max_length=100)
project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="tasks")
class Asset(models.Model):
name = models.CharField(max_length=100)
project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="assets")
My idea is that if a user is "assigned" to a project (via M2M field), that user will have access to all assets and tasks that are related to that Project. I have looked into django-guardian for per-object permissions and I think that could be the way to go, but to me it seems like I then would have to setup those permissions on each model..?
It feels like this should be a pretty common way of setting up permissions for any project-based app but I have a hard time finding similar examples and starting to wonder if I'm overthinking this or looking in the wrong direction?
Thank you,
Jonas
You can use django-rules to take advantage of object-level permissions without a database; with it, you can add permissions in many levels - models, views, templates, admin or DRF.
So, you'd need to create a predicate like
#rules.predicate
def is_project_manager(user, project):
return project.users == user
which will return True if the project's manager is the given user, False otherwise.
Then, to add it in a model, you'd do something like
import rules
from rules.contrib.models import RulesModel
class Project(RulesModel):
class Meta:
rules_permissions = {
"add": rules.is_project_manager,
"read": rules.is_authenticated,
}
There's ofc other considerations to attend to but I think that gives an overview of how it works.
Let's say I already have existing User instances in my database. Then, I just introduced a new model in my app:
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
nickname = models.CharField(max_length=30, blank=True)
I want to create a UserProfile instance for every user. I know that signals can handle this upon something like User().save(). However, what do I do with the users already in my database?
Currently I handle it in views.py:
try:
user.profile.nickname = 'my_nickname'
except:
profile = UserProfile()
profile.user = user
profile.nickname = 'my_nickname'
profile.save()
But this makes the view quite long. Is there a better way to do it?
For users already in your database, you can run a script on your django shell.
python manage.py shell
Then:
>>from .models import *
>>from django.contrib.auth.models import User
>>users_without_profile = User.objects.filter(profile__isnull=True)
>>for user in users_without_profile:
....user.profile.nickname = 'your_choice_of_nickname'
....user.save()
Just a side note: doing a wild import like from .models import * is a bad practice, but I did it anyway just for illustration and also I didn't know you appname. Hence, import the appropriate models from the respective app.
Hope this helps you.
I have 5 models in one of my apps
Report ReportData Customer ..etc
For some reason, ever since my last deployment, I can no longer change or create new Report or Customer objects, but everything else works? Any idea why this would be happening? The admin page just outputs nothing on the add link and the change link outputs nothing as well.
Django==1.9.1
I have tried restarting servers, running migrations, and restarting database. The development version works fine. Such a strange problem.
As you can see, there are no fields even though this object has been populated with tons of data in the database.
Here is my Report model:
class Report(models.Model):
public_uuid = models.UUIDField(max_length=256,default=util.make_uuid,unique=True)
customer = models.ForeignKey('Customer')
has_payed = models.BooleanField(default=False)
#... etc
Here is how I register items in the admin:
admin.site.register(Customer)
admin.site.register(Report)
admin.site.register(...etc)
The other 3 models I have work fine. The only difference between these two models and the other three (that work and are editable with the admin tool) is that these two models have #property and #staticmethod methods attached to them.
Just had this issue
When using auto_now_add=True or editable=False in the field definition, the admin will not show the corresponding fields unless you specify them in the readonly_fields of the admin form definition.
if in models.py
class TransmissionLog(models.Model):
dataSource = models.ForeignKey(Browser, editable=False)
dateCreated = models.DateTimeField(auto_now_add=True, editable=False)
then admin.py needs
class TransmissionAdminManager(admin.ModelAdmin):
readonly_fields = ['dataSource', 'dateCreated']
admin.site.register(TransmissionLog, TransmissionAdminManager)
I have a django app called my_app that uses django-userena; I am trying to create and use my own profile model by following the django-userena installation documentation.
In my_app/models.py I've added
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from userena.models import UserenaBaseProfile
class MyProfile(UserenaBaseProfile):
user = models.OneToOneField(User,
unique=True,
verbose_name=_('user'),
related_name='my_profile')
favourite_snack = models.CharField(_('favourite snack'),
max_length=5)
And then I've modified my_app/settings.py to include AUTH_PROFILE_MODULE = 'my_app.MyProfile' .
And yet, when I try to view any web page from my_app I get a SiteProfileNotAvailable. This error goes away if I move MyProfile to accounts/models.py
It seems like a bad idea to modify the accounts app in order to add custom fields. Am I wrong? Is there a way to add a custom profile module without modifying accounts/models.py?
I had the same issue. For me it happened because I forgot to put my_app (or accounts as in the official docs) into INSTALLED_APPS.
I have a problem that I hope someone with insight can aid with. My first Django project is near completion and I’m currently transitioning to a Postgres database in anticipation of deploying via Heroku. The process was going fairly smoothly until this occurred when I ran python manage.py syncdb.
django.db.utils.DatabaseError: relation “report_userprofile” does not exist
LINE 1: INSERT INTO “report_userprofile” (“user_id”, “first_name”, “…
Apparently, it did not create DB tables for the UserProfile model. I’m now getting this exception when I attempt to run the server:
Exception Type: DoesNotExist at /accounts/login/
Exception Value: Site matching query does not exist.
Among the additional apps I'm using for the project is django-profiles, which I had some issues setting up which are apparently common. The "Missing Manual" site – http://birdhouse.org/blog/2009/06/27/django-profiles/ – helped resolve those but may have led to the current problem.
I am using the signals.post_save.connect(create_profile, sender=User) recommended there. I was researching what might have gone wrong and came across this post on Google Groups and answer which states that “If you’re using a post_save signal on User you can’t do that because it results in a race condition." I’m wondering if this may be causing the issue and, obviously, what would be best to resolve it and get these tables into the new database and functioning.
Any insight into how to remedy this issue would be greatly appreciated.
This is the database model that may be causing the problem:
class UserProfile(models.Model):
user = models.OneToOneField(User, unique=True, related_name="profile")
first_name = models.CharField(max_length=25)
last_name = models.CharField(max_length=35)
email = models.EmailField()
birth_date = models.DateField(blank=True, null=True)
city = models.CharField(max_length=25)
state = models.CharField(max_length=20)
zip_code = models.CharField(max_length=10)
profile_pic = models.ImageField(upload_to='profilepictures', blank=True)
def __unicode__(self):
return " %s" % (self.user)
def get_absolute_url(self):
return ('profiles_profile_detail', (), { 'username': self.user.username })
get_absolute_url = models.permalink(get_absolute_url)
signals.post_save.connect(create_profile, sender=User)
Something seems suspicious here:
INSERT INTO “report_userprofile” (“user_id”, “first_name”, “…
Those two fields are fields on the native User model, not fields on the custom Profile model. Why would it be trying to insert those fields into your Profile table?
Is there more code you're not showin here?
Looking around, I see some interesting alternative approaches to automatically creating Profile records:
http://djangosnippets.org/snippets/500/
http://www.turnkeylinux.org/blog/django-profile
But I know that the technique you're using (listed at Birdhouse) has worked well for every Django site I've built, so I'm not particularly suspicious of that.