I get this error "employee_directory.thumbnail_kvstore' doesn't exist" when I use sorl-thumbnail to try and format my django admin profile image. Has anyone ran into this while working with sorl-thumbnail and django admin changelist?
DatabaseError at /directory/employee/
(1146, "Table 'employee_directory.thumbnail_kvstore' doesn't exist")
I doubled checked my sorl-thumbnail installation, and made sure I did a syncdb. Below is the code from my models.py and admin.py
models.py:
from django.db import models
from sorl.thumbnail import ImageField
# Department Table
class Department(models.Model):
department_name = models.CharField(max_length=128)
def __unicode__(self):
return self.department_name
# Employee Directory Table
class Employee(models.Model):
last_name = models.CharField(max_length=32)
first_name = models.CharField(max_length=32)
profile_image = models.ImageField(upload_to="images/profile_image", blank=True)
department_name = models.ForeignKey('Department')
job_title = models.CharField(max_length=64)
office_number = models.CharField(max_length=8, blank=True)
fax_number = models.CharField(max_length=8, blank=True)
mobile_number = models.CharField(max_length=8, blank=True)
intercom_number = models.CharField(max_length=3, blank=True)
email = models.CharField(max_length=128)
memo = models.TextField(blank=True)
def __unicode__(self):
return self.last_name + ', ' + self.first_name
admin.py:
from directory.models import *
from django.contrib import admin
from sorl.thumbnail import get_thumbnail
class EmployeeAdmin(admin.ModelAdmin):
def profile_img(self, obj):
if obj.profile_image:
t = get_thumbnail(obj.profile_image,"50x50",crop='center', quality=99)
return u'<img src="/media%s"/>' % t.url
else:
return u'profile_image'
profile_img.short_description = 'Profile image'
profile_img.allow_tags = True
search_fields = ['last_name', 'first_name']
list_display = ['profile_img', 'last_name', 'first_name', 'department_name',
'job_title', 'office_number', 'fax_number',
'mobile_number', 'intercom_number', 'email']
list_filter = ['department_name']
admin.site.register(Department)
admin.site.register(Employee, EmployeeAdmin)
Any help is greatly appreciated.
I totally noobed out, I forgot to put sorl.thumbnail in my apps in the django settings.
Related
I'm unsure of how I can edit a foreign key's fields from the template of another model - my changes do not update the model on post, see below.
models
class Projects(models.Model):
name = models.CharField(max_length=250)
class Current(models.Model):
fk_user = models.OneToOneField(User, on_delete=models.CASCADE)
fk_project = models.ForeignKey(projects, default='1', on_delete=models.CASCADE)
views
class current(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Current
fields = [
'fk_project'
]
template_name = 'users/current.html'
context_object_name = 'current'
def form_valid(self, form):
form.instance.fk_user = self.request.user
form.save()
# return super().form_valid(form)
return HttpResponseRedirect(self.request.path_info)
def test_func(self):
post = self.get_object()
if self.request.user == post.fk_user:
return True
return False
current.html
<form method="POST">{% csrf_token %}
<input type="text" value="{{ current.fk_project.name }}"/>
<button type="submit">post</button>
I would suggest you amend form_valid to follow the usual conventions. No idea if this will fix it, but
def form_valid(self, form):
instance = form.save( commit=False)
instance.fk_user = self.request.user
instance.save()
# return super().form_valid(form)
return HttpResponseRedirect(self.request.path_info)
If the desire is to update fields in the Project which is identified by the form as well as to store it in the Current instance which is the subject of this UpdateView, you can accomplish this by adding appropriate non-Model fields to the form and then processing the data in form_valid. For example, to pick a project, link it as at present, and simultaneously update its name:
class CurrentAndProjectUpdateForm( forms.ModelForm):
class Meta:
model = Current
fields = ['fk_project', ]
name = forms.CharField( ...) # new name for the related project
class current(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Current # don't think this now necessary
form_class = CurrentAndProjectUpdateForm # because it's implicit in this form
# fields = # DEFINITELY not needed here now
...
def form_valid(self, form):
instance = form.save( commit=False)
instance.fk_user = self.request.user
instance.save()
project = instance.fk_project
project.name = form.cleaned_data['name']
project.save()
# return super().form_valid(form)
return HttpResponseRedirect(self.request.path_info)
I am using MYSQL for the database. I want to upload my imagefield files in media folder that I have created in my project. I am getting "empty path didn't exist".
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
models.py
class Product(models.Model):
category = models.ForeignKey(Category, related_name='product', on_delete=models.CASCADE)
created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='product_creator')
title = models.CharField(max_length=255)
author = models.CharField(max_length=255, default='admin')
description = models.TextField(blank=True)
image = models.ImageField(upload_to='images/')
slug = models.SlugField(max_length=255)
price = models.DecimalField(max_digits=4, decimal_places=2)
in_stock = models.BooleanField(default=True)
is_active = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
verbose_name_plural = 'Products'
ordering = ('-created',)
def __str__(self):
return self.title
urls.py
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I have registered the model successfully in admin.py.
your code:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
test this:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I fixed this error by deleting the 'MEDIA_URL' and 'MEDIA_ROOT' path in settings.py file that I had previously added. The above code is then working.
I have been trying to add a friend system to django in which the user can add and remove friends, in the process I found a Friend matching query does not exist error and shows that this part of the code is bad:
friend = Friend.objects.get(current_user=request.user)
now here I will leave the complete code.
views.py
def profile(request, username=None):
friend = Friend.objects.get(current_user=request.user)
friends = friend.users.all()
if username:
post_owner = get_object_or_404(User, username=username)
user_posts=Post.objects.filter(user_id=post_owner)
else:
post_owner = request.user
user_posts=Post.objects.filter(user=request.user)
args1 = {
'post_owner': post_owner,
'user_posts': user_posts,
'friends': friends,
}
return render(request, 'profile.html', args1)
def change_friends(request, operation, pk):
friend = User.objects.get(pk=pk)
if operation == 'add':
Friend.make_friends(request.user, friend)
elif operation == 'remove':
Friend.lose_friends(request.user, friend)
return redirect('profile')
models.py
class Friend(models.Model):
users = models.ManyToManyField(User, default='users', blank=True, related_name='users')
current_user = models.ForeignKey(User, related_name='owner', on_delete=models.CASCADE, null=True)
#classmethod
def make_friend(cls, current_user, new_friend):
friend, created = cls.objects.get_or_create(
current_user=current_user
)
friend.users.add(new_friend)
#classmethod
def lose_friend(cls, current_user, new_friend):
friend, created = cls.objects.get_or_create(
current_user=current_user
)
friend.users.remove(new_friend)
if the profile.html is neede please let me know:)
request.user has no Friend record as the error indicates. You can simple change the get operation to filter&first operations. Friend.objects.filter(current_user=request.user).first() then do not forget to check friend instance exists. So your view should be something like:
def profile(request, username=None):
friend = Friend.objects.filter(current_user=request.user).first()
friends = []
if friend:
friends = friend.users.all()
if username:
post_owner = get_object_or_404(User, username=username)
user_posts = Post.objects.filter(user_id=post_owner)
else:
post_owner = request.user
user_posts = Post.objects.filter(user=request.user)
args1 = {
'post_owner': post_owner,
'user_posts': user_posts,
'friends': friends,
}
return render(request, 'profile.html', args1)
Since the auto_increment setting in the MySQL is for the global, which cannot be set to a specific table?
I'm considering if it's possible to make the id auto increasing by 2 in the Model of Django?
models.py
class Video(models.Model):
name = model.CharField(max_length=100, default='')
upload_time = models.DateTimeField(blank=True, null=True)
def __str__(self):
return self.name
What should I do? Thanks for ur help.
You could do it my overriding save() method of your model as
from django.db.models import Max, F
class Video(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100, default='')
upload_time = models.DateTimeField(blank=True, null=True)
def save(self, *args, **kwargs):
if not self.pk:
max = Video.objects.aggregate(max=Max(F('id')))['max']
self.id = max + 2 if max else 1 # if the DB is empty
super().save(*args, **kwargs)
def __str__(self):
return self.name
the correct way is to change your mysql server settings
check this out: auto_increment_increment
Possible Solutions:
Assume I have a Model of Customer.
Customer.objects.order_by('primay_key_id ').last().primay_key_id + 2)
primay_key_id = models.IntegerField(default=(Customer.objects.order_by('primay_key_id ').last().primay_key_id + 2),primary_key=True)
or
from django.db import transaction
#Uncomment Lines for Django version less than 2.0
def save(self):
"Get last value of Code and Number from database, and increment before save"
#with transaction.atomic():
#top = Customer.objects.select_for_update(nowait=True).order_by('-customer_customerid')[0] #Ensures Lock on Database
top = Customer.objects.order_by('-id')[0]
self.id = top.id + 1
super(Customer, self).save()
The Above Code would not have a Concurrency Issue for Django 2.0 as:
As of Django 2.0, related rows are locked by default (not sure what the behaviour was before) and the rows to lock can be specified in the same style as select_related using the of parameter!
For Lower Versions, you need to be atomic!
or
from django.db import transaction
def increment():
with transaction.atomic():
ids = Customer.objects.all()
length = len(ids)-1
if(length<=0): #Changed to Handle empty Entries
return 1
else:
id = ids[length].customer_customerid
return id+2
or
from django.db import transaction
def increment():
with transaction.atomic():
return Customer.objects.select_for_update(nowait=True).order_by('-customer_customerid')[0] #Ensures Atomic Approach!
and set primary key in model to Integer Field and on every new entry primary_key_field=increment() Like
and then in your Models.py
set the Primary_Key to:
import increment()
primay_key_id = models.IntegerField(default=increment(),primary_key=True)
So, I'm new to Django and this has become a major headache. So I'm trying to create an extended user profile a la the documentation. However, when I attempt to post an entry through the form I receive the following error:
Exception Type: IntegrityError at /signup/ Exception Value: (1062,
"Duplicate entry '64' for key 2")
Upon crashing with an Internal Server Error, I notice that a new user with the relevant fields (username, password, first name, last name) is created and so is the profile entry. However the profile entry is devoid of all the information entered, with the exception of the id of the user the profile is associated with. Here is the relevant code:
In views.py:
from django.shortcuts import render_to_response
from django.template import RequestContext
from portalman.models import FnbuserForm, AuthUserForm, Fnbuser
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
from django.db import IntegrityError
from django.utils.safestring import mark_safe
from django.contrib.auth.models import User
def signup(request):
viewParam = {}
errors = None
profileForm = FnbuserForm()
userForm = AuthUserForm()
if request.method == "POST":
profileForm = FnbuserForm(request.POST)
userForm = AuthUserForm(request.POST)
if userForm.is_valid() and profileForm.is_valid():
newuser = User.objects.create_user(userForm.cleaned_data['username'], userForm.cleaned_data['email'], userForm.cleaned_data['password'])
newuser.first_name = userForm.cleaned_data['first_name']
newuser.last_name = userForm.cleaned_data['last_name']
newuser.save()
newFnbUser = Fnbuser(user = newuser, #other profile elements#)
newFnbUser.save()
return HttpResponseRedirect('/thanks/')
else:
profileForm = FnbuserForm() # An unbound profile form
userForm = AuthUserForm() #An unbound user form
else:
viewParam = {'profileForm': profileForm, 'userForm' : userForm, 'links' : links}
viewParam.update(csrf(request))
return render_to_response('signup.html', viewParam, context_instance=RequestContext(request))
In portalman/models.py:
from django.db import models
from django import forms
from django.contrib.auth.models import User, UserManager
from django.db.models.signals import post_save
class Fnbuser(models.Model):
telephone = models.CharField(max_length=20, blank=True, null=True)
additionalNotes = models.TextField(help_text=("Feel free to add additional notes or comments here!"), blank=True,
verbose_name="Notes", null=True)
canCook = models.BooleanField(verbose_name="Can Cook", default=False, blank=True)
canTransport = models.BooleanField(verbose_name="Can Tranport", default=False, blank=True)
canServe = models.BooleanField(verbose_name="Can Serve Food", default=False, blank=True)
canGarden = models.BooleanField(verbose_name="Can Garden", default=False, blank=True)
canProgram = models.BooleanField(verbose_name="Can Program", default=False, blank=True)
canDesign = models.BooleanField(verbose_name="Can Design", default=False, blank=True)
canAlso = models.CharField(verbose_name="Other", max_length=255, blank=True, null=True)
user = models.ForeignKey(User, unique=True)
def __str__(self):
return self.user.username
def create_user_profile(sender, instance, created, **kwargs):
if created:
Fnbuser.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
class Meta:
verbose_name = "Food Not Bombs User"
verbose_name_plural = "Food Not Bombs Users"
class AuthUserForm(forms.Form):
username = forms.RegexField(label=("*Username:"), max_length=30, regex=r'^[\w.#+-]+$',
error_messages = {'invalid': ("This value may contain only letters, numbers and # . + - _ characters."),
'inUse' : ("This username is already in use, try another.")},
help_text = ("Required. 30 characters or fewer. Letters, digits and # . + - _ only."))
password = forms.CharField(label=("*Password:"), widget=forms.PasswordInput,
help_text = ("Required. 30 characters or fewer. Letters, digits and # . + - _ only."),
error_messages = {'invalid': ("This value may contain only letters, numbers and # . + - _ characters.")})
email = forms.CharField(label=("E-Mail Address:"), required=False)
first_name = forms.CharField(label=("First Name:"), required=False)
last_name = forms.CharField(label=("Last Name:"), required=False)
class FnbuserForm(forms.Form):
telephone = forms.CharField(label=("Telephone:"), required=False)
additionalNotes = forms.CharField(label=("Additional Notes about yourself, or general comments."),
widget = forms.widgets.Textarea(), required=False)
canCook = forms.BooleanField(label=("Can Help Cook:"), required=False)
canTransport = forms.BooleanField(label=("Can Help Transport:"), required=False)
canServe = forms.BooleanField(label=("Can Help Serve Food:"), required=False)
canGarden = forms.BooleanField(label=("Can Help Garden:"), required=False)
canProgram = forms.BooleanField(label=("Can Help Program Site:"), help_text=("""If you can help program the site,
note what languages you can program in within the "can also help with" box."""), required=False)
canDesign = forms.BooleanField(label=("Can Help With Design:"), help_text=("""Photography/Video Editing/Web Design/etc. Note
what you can do specifically within the "can also help with" box."""), required=False)
canAlso = forms.CharField(label=("Can Also Help With:"), required=False)
class Meta:
model=Fnbuser
Could anyone suggest what is going wrong? I would be very grateful!
You can't use:
Fnbuser.objects.create(user=instance)
after the object has already been created with:
newFnbUser.save()
That's why the call to the create method in the QuerySet (objects) will raise IntegrityError.
see doc