I have tried all previous solutions such as syncdb, migrate, makemigrations etc. I am still not getting the program to work.
My models.py
class Role(models.Model):
ROLE_CHOICES = (
(1,'ADMIN'),
(2,'HR'),
(3,'MGR'),
(4,'EMP'),
)
id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES,primary_key=True)
def ___str___ (self):
return self.get_id_display()
class User(AbstractUser):
roles = models.ManyToManyField(Role)
class Admins(models.Model):
user = models.PositiveSmallIntegerField(choices=Role.ROLE_CHOICES)
first_name = models.CharField(max_length=256)
last_name = models.CharField(max_length=256)
class HRs(models.Model):
user = models.PositiveSmallIntegerField(choices=Role.ROLE_CHOICES)
first_name = models.CharField(max_length=256)
last_name = models.CharField(max_length=256)
Then here is my views.py
class AdminSignUpView(CreateView):
model = User
form_class = AdminSignUpForm
template_name = 'form1/signup_form.html'
def get_context_data(self, **kwargs):
kwargs['user_type'] = 'ADMIN'
return super().get_context_data(**kwargs)
def form_valid(self, form):
user = form.save()
login(self.request, user)
return redirect('/form1/forms/')
class HRSignUpView(CreateView):
model = User
form_class = HRSignUpForm
template_name = 'form1/signup_form.html'
def get_context_data(self, **kwargs):
kwargs['user_type'] = 'HR'
return super().get_context_data(**kwargs)
def form_valid(self,form):
user = form.save()
login(self.request, user)
return redirect('/form1/forms')
Here is my forms.py
class AdminSignUpForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = User
fname = forms.CharField(max_length=256)
lname = forms.CharField(max_length=256)
#transaction.atomic
def save(self):
user = super().save(commit=False)
user.roles = 1
user.save()
admin1 = Admins.objects.create(user=user)
admin1.first_name.add(*self.cleaned_data.get('fname'))
admin1.last_name.add(*self.cleaned_data.get('lname'))
return user
class HRSignUpForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = User
#transaction.atomic()
def save(self, commit=True):
user = super().save(commit=False)
user.roles = 2
user.save()
hr1 = HRs.objects.create(user=user)
hr1.first_name.add(*self.cleaned_data.get('fname'))
hr1.last_name.add(*self.cleaned_data.get('lname'))
return user
Finally, here is my error -
OperationalError at /accounts/signup/hr/
no such table: form1_user
Request Method: POST
Request URL: http://127.0.0.1:8000/accounts/signup/hr/
Django Version: 3.0.5
Exception Type: OperationalError
Exception Value:
no such table: form1_user
It doesn't even show me where my mistake is in my code which makes it really hard to fix my problem. Spent hours on the internet trying to find a solution and nothing works.
After creating new models did you create migrations by makemigrations and applied those migrations by migrate
I ran into the same exact error. It did not seem to fix. What I did, is that I copied all the files in that folder into another folder, deleted that folder, created a new one in my project directory, then pasted everything back in (be careful with your urls.py, don't forget to change them). Then I ran the makemigration and migrate commands and it worked smoothly!
Related
For some reason my UpdateView is not displaying the selected associated. The form is pre-populated with only the first form field data results, username, and none of the other field data. I suspect this is due to the ManytoMany field being queried. I've searched for and tried possible solutions but nothing has worked. Any ideas?
Models.py
class Company(models.Model):
"""All company specific details. For each main manager, a company is created. The main manager can then add company members, creating for them their user accounts."""
members = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name='teams', through='CompanyMembership'
)
...
class CompanyMembership(models.Model):
"""Acts as a gateway between User model and Company model"""
STAFF = "STAFF", "Staff"
MANAGERS = "MANAGERS", "Managers"
my_company = models.ForeignKey(Company, on_delete=models.CASCADE)
my_identity = models.ForeignKey(User, on_delete=models.CASCADE)
my_role = models.CharField(max_length=100, choices=MemberTypes.choices, default=None)
class User(models.Model):
"""Users can be main managers or staff. Each main manager has their own Company. Many staff can belong to a single Company associated with a main manager."""
username = models.CharField(_("Login Name"), blank=True, null=True, max_length=155, unique=True)
...
Views.py
class TeamMembersView(LoginRequiredMixin, CompanyMembershipCheckMixin, UserPassesTestMixin, ListView):
"""Lists all the company team members for the specific company"""
model = Company
template_name = 'users/dashboard/team.html'
def test_func(self):
user_obj = User.objects.get(id=self.request.user.id)
return user_obj.groups.filter(name='Company_Main_Manager').exists()
def get_context_data(self, **kwargs):
context = super(TeamMembers, self).get_context_data(**kwargs)
user_obj = User.objects.get(id=self.request.user.id)
companymembership_obj = CompanyMembership.objects.get(my_identity=user_obj)
company_obj = Company.objects.get(id=companymembership_obj.my_company.id)
slug = company_obj.slug
context['members'] = ecosystem_obj.members.all()
context['slug'] = slug
return context
class TeamMemberUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
"""Allows the main manager to change or update the specific staff member's user data"""
model = User
template_name = 'users/dashboard/user_create.html'
form_class = TeamMemberCreateForm
def test_func(self):
user_obj = User.objects.get(id=self.request.user.id)
return user_obj.groups.filter(name='Company_Main_Manager').exists()
def get_context_data(self, **kwargs):
data = super(TeamMemberUpdateView, self).get_context_data(**kwargs)
if self.request.POST:
data['member'] = TeamMemberCreateForm(self.request.POST, self.request.FILES)
else:
data['member'] = TeamMemberCreateForm()
return data
def form_valid(self, form):
context = self.get_context_data()
member = context['member']
with transaction.atomic():
form.instance.created_by = self.request.user
self.object = form.save()
if member.is_valid():
member.instance = self.object
member.save()
return super(TeamMemberUpdateView, self).form_valid(form)
Forms.py
class TeamMemberCreateForm(ModelForm):
"""Allows the main manager to create (and update) a user account for additional staff members."""
first_name = forms.CharField(max_length=200, help_text="Enter member's first name", required=True)
last_name = forms.CharField(max_length=200, help_text="Enter member's last name")
email = forms.EmailField(max_length=200, help_text="Member's primary email address")
phone = forms.CharField(max_length=100, help_text="Primary phone number")
position_title = forms.CharField(max_length=200, help_text="Member's job position or title for the company")
class Meta(UserCreationForm.Meta):
model = User
exclude = ['company_name']
#transaction.atomic
def save(self):
member_user = super().save(commit=False)
member_user.firstname = self.cleaned_data.get('first_name')
member_user.lastname = self.cleaned_data.get('last_name')
member_user.email = self.cleaned_data.get('email')
member_user.phone = self.cleaned_data.get('phone')
member_user.is_company_main_manager = False
member_user.is_active = True
member_user.user_type = User.UserTypes.STAFF
member_user.save()
CompanyMembership.objects.create(my_company=ecosystem_create, my_identity=user, my_role=CompanyMembership.MemberTypes.STAFF)
return member_user
As an example, if I am the main manager I can create a user account for my staff member through the above form. For the staff member account I enter username="username_example", first_name="pete", last_name="smith", phone="333-333-3333",... and so on. CreateView works as expected. The user account is created, saved, etc. UpdateView, though, display would show in this example:
username: username_example
first name:
last name:
phone:
...
# The first field of the form is pre-populated but none of the others... why?
You have to super init your form and rewrite the field with the
def init(self, *args, **kwargs):
super(TeamMemberCreateForm, self).__init__(*args, **kwargs)
self.fields[your_field] = forms.ModelMultipleChoiceField(
queryset=Company.objects.all(),
widget=forms.CheckboxSelectMultiple(attrs=
{'dir': 'ltr', 'type': "checkbox",'switch':"bool"}))
By using fields = ['username', 'firstname', 'lastname', 'email', 'phone'] instead of form_class = TeamMemberCreateForm in UpdateView, the problem was solved.
I want to save the Portfolio products details in PortfolioProducts model in django
I have models like below:
class Product(models.Model):
name = models.CharField(max_length=255,null=True, verbose_name ='Name')
class Portfolio(models.Model):
name = models.CharField(max_length=100, blank=True, null=True, verbose_name ='Name')
class PortfolioProducts(models.Model):
portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, verbose_name ='Portfolio')
product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name ='Product')
Portfolio form:
class PortfolioForm(forms.ModelForm):
class Meta:
model = Portfolio
fields = ['name']
My view file:
def edit(request):
portfolio_form = PortfolioForm
if request.method=="POST":
portfolio_id=request.POST.get('portfolio_id')
portfolio_detail = Portfolio.objects.get(pk=portfolio_id)
pform = portfolio_form(request.POST, instance=portfolio_detail)
if pform.is_valid():
portfolio = pform.save(commit = False)
portfolio.save()
products=request.POST.getlist('product_id[]')
for product in products:
ppform = PortfolioProducts(product_id=product, portfolio_id=portfolio_id)
port_product = ppform.save()
I am trying to save and update the Portfolio products like this, but is adding products to portfolio multiple time.
Well, you don't need to update PortfolioProduct for updating Portofilio. Because even if you update Portfolio, its primary key remains same as before. So the relationship remains the same.
But, in your case, if PortofolioProduct does not exist for a product in products and Portfolio object, then you can create one like this:
for product in products:
ppform, _ = PortfolioProducts.objects.get_or_create(product_id=product, portfolio_id=portfolio_id)
Update
From comments: you need to either remove def save(self): methods from you Model(Because you are not doing anything particular in those save methods) or if intend to keep you save() methods, then you need to call the super properly, like this:
class Product(models.Model):
name = models.CharField(max_length=255,null=True, verbose_name ='Name')
def save(self, *args, **kwargs):
super(Product, self).save(*args, **kwargs)
class Portfolio(models.Model):
name = models.CharField(max_length=100, blank=True, null=True, verbose_name ='Name')
def save(self, *args, **kwargs):
super(Portfolio, self).save(*args, **kwargs)
class PortfolioProducts(models.Model):
portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, verbose_name ='Portfolio')
product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name ='Product')
def save(self, *args, **kwargs):
super(PortfolioProducts, self).save(*args, **kwargs)
Yes, I also got stuck with the same issue in my django project. The thing it does in my case was everytime the user tries to update his/her profile, it created a new one, this is because of the Foreign Key to it. I fixed the issue by deleting the previous user profile (in your case it's portfolio) every time the user updates it.
class UserEdit(TemplateView):
template_name = 'accounts/homee.html'
def get(self, request):
form = UserProfilee()
ppp = UserProfile.objects.get(user=request.user)
return render(request, self.template_name, {'form': form, 'ppp': ppp})
def post(self, request):
form = UserProfilee(request.POST, request.FILES)
pppp = UserProfile.objects.get(user=request.user)
if form.is_valid():
post = form.save(commit=False)
post.user = request.user
if not post.image:
post.image = pppp.image
UserProfile.objects.filter(user=post.user).delete()
post.save()
return redirect('/home/homepage/')
args = {'form': form}
return render(request, self.template_name, args)
As you see,I filter the user and delete the user profile whenever user updates his/her profile thus leaving only 1 user profile.
I'm trying to customize the authentication that comes by default in Django with a table of Mysql already made (collaborators).
When I want to register a user (with the command python manage.py createsuperuser) I get the following error:
django.db.utils.OperationalError: (1054, "Unknown column 'collaborators.password' in 'field list'").
That error mentions that the password column does not exist, and indeed I do not have it in the table, is there any way to indicate that the password is obtained from a column called contrasena_general?
I attach my code.
models.py
class MyUserManager(BaseUserManager):
use_in_migrations = True
def create_superuser(self, no_colaborador, nombres_colaborador, apellido_paterno_colaborador, apellido_materno_colaborador,
id_plantel, id_area_colaborador, no_empleado_sup, contrasena_general, empleado_interno):
user = self.model(no_colaborador = no_colaborador, nombres_colaborador = nombres_colaborador,
apellido_paterno_colaborador = apellido_paterno_colaborador, apellido_materno_colaborador = apellido_materno_colaborador,
id_plantel = id_plantel, id_area_colaborador = id_area_colaborador, no_empleado_sup = no_empleado_sup,
contrasena_general = contrasena_general, empleado_interno = empleado_interno,)
user.set_password(contrasena_general)
user.save(using=self._db)
return user
class Colaboradores(AbstractBaseUser):
no_colaborador = models.IntegerField(primary_key=True)
nombres_colaborador = models.CharField(max_length=150)
apellido_paterno_colaborador = models.CharField(max_length=150)
apellido_materno_colaborador = models.CharField(max_length=150)
id_plantel = models.IntegerField()
id_area_colaborador = models.IntegerField()
id_centro_costos = models.IntegerField()
no_empleado_sup = models.IntegerField()
contrasena_general = models.CharField(max_length=100)
empleado_interno = models.CharField(max_length=10)
objects = MyUserManager()
USERNAME_FIELD = "no_colaborador"
class Meta:
managed = False
db_table = 'collaborators'
app_label = "journal"
def __str__ (self):
return self.email
def def_full_name (self):
return self.nombres_colaborador
def has_perm(self, perm, obj=None):
return self.no_colaborador
def has_module_perms(self, app_label):
return self.no_colaborador
# backends.py
class MyAuthBackend(object):
def authenticate(self, no_colaborador, contrasena_general):
try:
user = Colaboradores.objects.get(no_colaborador=no_colaborador)
if user.check_password(contrasena_general):
return user
else:
return None
except Colaboradores.DoesNotExist:
logging.getLogger("error_logger").error("user with login %s does not exists " % login)
return None
except Exception as e:
logging.getLogger("error_logger").error(repr(e))
return None
def get_user(self, no_colaborador):
try:
user = Colaboradores.objects.get(no_colaborador=no_colaborador)
if user.is_active:
return user
return None
except Colaboradores.DoesNotExist:
logging.getLogger("error_logger").error("user with %(no_colaborador)d not found")
return None
# setting.py
...
AUTH_USER_MODEL = 'journal.Colaboradores'
AUTHENTICATION_BACKENDS = ('clientes.backends.MyAuthBackend', 'django.contrib.auth.backends.ModelBackend',)
How could you indicate that the password is obtained from a column in the table that is not called a password?
I think creating your own createsuperuser command would solve this issue.
Ref: Is it possible to make my own createsuperuser command in django?
You can make your based on the the original source code for Django's createsuperuser that can be found on Github.
As you can see from there, there is a constant on line 20 that says:
PASSWORD_FIELD = 'password'
So I guess that since you changed it in the model to contrasena_general, you need to make your own custom command.
I can't work out how to get the correct instance for the form_valid part of my generic view.
I am trying to allow a user to post on their project wall(bit like Facebook). I need the post to be related to an individual project(a user can have more than one project). Should the instance be a pk or the project title? Any example code or help would be very appreciated! I struggle understanding how when you create a new post, it knows which project to associate itself with.
views
class NewPost(CreateView):
model = ProjectPost
form_class = ProjectPostForm
template_name = 'howdidu/new_post.html'
def form_valid(self, form):
newpost = form.save(commit=False)
form.instance.user = self.request.user
newpost.save()
self.object = newpost
return super(NewPost, self).form_valid(form)
def get_success_url(self):
project_username = self.request.user.username
project_slug = self.object.slug
return reverse('user_project', kwargs={'username':project_username, 'slug': project_slug})
models
class UserProject(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=100)
project_overview = models.CharField(max_length=1000)
project_picture = models.ImageField(upload_to='project_images', blank=True)
date_created = models.DateTimeField(auto_now_add=True)
project_views = models.IntegerField(default=0)
project_likes = models.IntegerField(default=0)
project_followers = models.IntegerField(default=0)
slug = models.SlugField(max_length=100, unique=True) #should this be unique or not?
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(UserProject, self).save(*args, **kwargs)
def __unicode__(self):
return self.title
class ProjectPost(models.Model):
project = models.ForeignKey(UserProject)
title = models.CharField(max_length=100)
post_overview = models.CharField(max_length=1000)
date_created = models.DateTimeField(auto_now_add=True)
post_views = models.IntegerField(default=0)
post_likes = models.IntegerField(default=0)
forms
#form to add project details
class UserProjectForm(forms.ModelForm):
class Meta:
model = UserProject
fields = ('title', 'project_picture', 'project_overview')
#form to create a post
class ProjectPostForm(forms.ModelForm):
class Meta:
model = ProjectPost
fields = ('title', 'post_overview')
Ok, in that case, I would recommend a URL something like
url(r'^(?P<pk>\d+)/post/add/$', views.NewPostCreateView.as_view(), name='...'),
and then a view like
class NewPost(CreateView):
model = ProjectPost
form_class = ProjectPostForm
template_name = 'howdidu/new_post.html'
def form_valid(self, form):
self.object = form.save(commit=False)
# Find project by using the 'pk' in the URL
project = get_object_or_404(UserProject, pk=self.kwargs['pk'])
# Then just set the project on the newPost and save()
self.object.project = project
self.object.save()
return super(NewPost, self).form_valid(form)
def get_success_url(self):
# Unchanged ...
I see in your code that you were trying to do something with the user but I don't understand why your Post does not have a user field (you may want to add a created_by) and the UserProject should already have a user set.
I am also assuming the user got to the his/her project first, so you know by definition that the project he is adding a post to is his. If that is not the case, then just change the logic to get the UserProject through a regular query. e.g. maybe with `UserProject.objects.get(user = self.request.user) if there is one project per user (again, just as an example).
Anyway, I am making some assumptions here, but hopefully the main question was how to set the project on the newPost and that is answered in my example.
I'm creating a custom profile page and I need the user to be able to save or update his profile. For some reason I'm getting the following error when I hit the update profile button:
User matching query does not exist.
Below is the code I have for the forms, models and views files:
forms.py
class ProfileForm(forms.Form):
profile_name = forms.CharField( max_length=50)
models.py
class UserProfile(models.Model):
user = models.ForeignKey(User)
profile_name = models.CharField(blank=True, max_length=50)
def __unicode__(self):
return u'%s %s' % (self.user, self.profile_name)
views.py
def edit_profile(request):
if 'edit_button' in request.POST:
form = ProfileForm(request.POST)
f_user = User.objects.get(username=request.user.id)
f_profile_name = form.cleaned_data['profile_name']
p = UserProfile(user=f_user, profile_name=f_profile_name)
p.save()
else:
form = ProfileForm()
return render_to_response('userprofile_template.html', locals(), context_instance=RequestContext(request))
Any idea what am I not doing right? Thank You!
f_user = User.objects.get(username=request.user.id)
Username is presumabely request.user.username
Or, just user User.objects.get(id=request.user.id)
Actually what is my caffienated ass saying? You have your user object right there!
request.user : )