Unable to migrate Django models - python

So I'm trying to automatically assign the current logged in user to a variable in my model. I think this make sense but I'm not able to migrate the models and it is going me this error.
models.py:
from django.db import models
from django.contrib.auth.models import User
from datetime import date
# Create your models here.
class UserProfileInfo(models.Model):
user = models.OneToOneField(User)
portfolio_site = models.URLField(blank=True)
profile_pic = models.ImageField(upload_to='profile_pics',blank='True')
def __str__(self):
return self.user.username
class UserPosts(models.Model):
post_title = models.CharField(max_length=100,unique=True)
post_sub_title = models.CharField(max_length=250,unique=False)
post_author = models.ForeignKey('User',User.username)
post_date = models.DateField(default=date.today,blank=True)
post_body = models.TextField(max_length=1000,unique=False)
def __str__(self):
return str(self.post_title)
The Error:
ValueError: Cannot create form field for 'post_author' yet, because its related model 'User' has not been loaded yet

Remove the quotation from this line:
post_author = models.ForeignKey('User',User.username)
It should be like this:
post_author = models.ForeignKey(User,User.username)

I think the problem is this:
from django.contrib.auth.models import User
post_author = models.ForeignKey('User',User.username)
Your ForeignKey want's to use the attribute 'username' of the imported User. Not of your User object when related.

I think I just deleted the migrations and then migrated again from scratch...

Related

Save multiple values in one field (Django)

The problem:
I have a model, which is referencing the basic User model of django. Right now, if I submit the form Django updates my database by replacing the existing data with the new one. I want to be able to access both of them. (In weight and date field)
Models file:
I saw other posts here, where they solved a problem by specifying a foreign key, but that doesn't solve it for me.
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
weight = models.FloatField(max_length=20, blank=True, null=True)
height = models.FloatField(max_length=20, blank=True, null=True)
date = models.DateField(auto_now_add=True)
def __str__(self):
return self.user.username
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
Views file:
This is where I save the data that I get from my form called WeightForm
from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from users import models
from users.models import Profile
from .forms import WeightForm
def home(request):
form = WeightForm()
if request.is_ajax():
profile = get_object_or_404(Profile, id = request.user.id)
form = WeightForm(request.POST, instance=profile)
if form.is_valid():
form.save()
return JsonResponse({
'msg': 'Success'
})
return render(request, 'Landing/index.html',{'form':form})
What I tried:
I used to have a OneToOneField relation with this model, but as you can see I changed it to foreignkey, according to answers I saw on this site.
Thanks if you've gotten this far in my mess :D
I didn't understood exactly what you mean by "I want to be able to access both of them. (In weight and date field)" but I guess you want user to be able to see their previous data of weight and Date also, so you can try doing this:
In your models.py do try doing this,
class Profile(models.Model):
user_id = models.AutoField(primary_key=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
height = models.FloatField(max_length=20, blank=True, null=True)
def __str__(self):
return self.user.username
class UserData(models.Model):
Data_id = models.AutoField(primary_key=True)
user_id = models.ForeignKey(Profile, on_delete=models.CASCADE)
weight = models.FloatField(max_length=20, blank=True, null=True)
date = models.DateField(auto_now_add=True)
then u can have seperate forms for both the models and use them combined.
You can make a workaround
Create new model which would include something like "version"
Reference to version with foreign key
class ProfileChange(models.Model):
Date = models.DateField(default=datetime.datetime.today().strftime('%Y-%m-%d'))
#classmethod
def create(cls):
object = cls()
return object
class Profile(models.Model):
version = models.ForeignKey(ProfileChange,on_delete=models.CASCADE)
Unfortunately, you could see only one ProfileChange a day. If you want to see more of them, instead of models.DataField use models.IntegerField

Is there a way to block self-following in Follow model?

My model structure looks like this:
from django.db import models
class Follow(models.Model):
follower = models.ForeignKey('accounts.User', related_name='following',
on_delete=models.CASCADE)
user = models.ForeignKey('accounts.User', related_name='followers',
on_delete=models.CASCADE)
class Meta:
unique_together = (('user', 'follower',),)
def __str__(self):
return f'{self.follower.username} follows {self.user.username}'
I'm looking for something similar to "unique_together" but for the same user.
I know there're possibilities to block it in API but I want it to do it from model level.
You can either:
as the other answer says, override clean() or save() to ensure follower != user,
or if you're using a supported database, you could add a Check constraint to do the same on the database level.
Overriding the save method can do the trick here. In your model save method you can check and raise an exception if both follower and user are same. I don't think you would be able to do it using any constraint as unique_together.
Thanks for the answers but I did it this way.
from django.dispatch import receiver
from django.db import models
from django.db.models.signals import pre_save
from django.core.exceptions import ValidationError
class Follow(models.Model):
follower = models.ForeignKey('accounts.User', related_name='following',
on_delete=models.CASCADE)
user = models.ForeignKey('accounts.User', related_name='followers',
on_delete=models.CASCADE)
class Meta:
unique_together = (('user', 'follower',),)
def __str__(self):
return f'{self.follower.username} follows {self.user.username}'
#receiver(pre_save, sender=Follow)
def check_self_following(sender, instance, **kwargs):
if instance.follower == instance.user:
raise ValidationError('You can not follow yourself')

NOT NULL constraint failed: users_userprofile.user_id

I am trying to insert django form data inside the UserProfile model in my app. I tried using the django shell and views.py but I keep getting this error.
Models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
section = models.CharField(max_length=255, blank=True)
year = models.IntegerField(null=True, blank=True)
course = models.CharField(max_length=255, blank=True)
qrcode = models.CharField(max_length=255, blank=True)
present = models.BooleanField(default=False)
def __str__(self):
return self.user.username
views.py
#staticmethod
def generate_qr(request):
if request.method == "POST":
form = MakeAttendance(request.POST)
if form.is_valid():
course = form.cleaned_data.get('courses')
section = form.cleaned_data.get('section')
year = form.cleaned_data.get('year')
profile = UserProfile.objects.get_or_create(user=request.user)
userobj = UserProfile(qrcode=unique_id)
userobj.save().filter(course=course, section=section, year=year)
return redirect('/users/dashboard')
This question has been answered many times here, but none of the solutions worked for me. I tried Creating a user profile with get_or_create method. I tried deleting my entire database and making migrations again. I manually tried to pass the user ID but nothing.
First create a user using user=User.objects.create_user(username=request.user, password='password'), then save it using user.save() and create profile using profile=UserProfile.objects.get_or_create(user=user). The reason this error occours is because the UserProfile looks for a user instance which you did not provide.
The problem is in these two line
userobj = UserProfile(qrcode=unique_id)
userobj.save().filter(course=course, section=section, year=year)
In the first line you created an instance of UserProfile with only qr_code
and in the next line you are trying to save it which will try to insert a new row in the database without the user.
in models.py you should create user object:
from django.conf import settings
User = settings.AUTH_USER_MODEL
before class creating

Foreign key constraint error on Django app

I'm trying to have this third class noticeTime be constrained to the foreign key email. I am using the same syntax that worked for the 2nd class location, but when I use it on noticeTime it throws an error:
Exception Value: no such column: setupNotifications_noticetime.email_id
Here is the code:
from django.db import models
# Create your models here.
from django.db import models
class email(models.Model):
email = models.CharField(max_length=200)
def __unicode__(self):
return self.email`
class location(models.Model):
email = models.ForeignKey(email)
zip_code = models.CharField(max_length=5)
def __unicode__(self):
return self.zip_code
class noticeTime(models.Model):
email = models.ForeignKey(email)
time = models.CharField(max_length=200)
def __unicode__(self):
return self.time
here is admin.py:
from django.contrib import admin
# Register your models here.
from setupNotifications.models import email
from setupNotifications.models import location
from setupNotifications.models import noticeTime
admin.site.register(email)
admin.site.register(location)
admin.site.register(noticeTime)
I'm using the sqlite database
Perhaps your problem is that you ran syncdb, assuming that it would alter the table to match your model change. Unfortunately, it does not do that. There are some separate tools available, such as South, which can help with database migrations.

Model has either not been installed or is abstract

When I try to migrate my code I get this error.
Here are my code and classes:
from django.db import models
from core.models import Event
class TicketType(models.Model):
name = models.CharField(max_length=45)
price = models.DecimalField(max_length=2, decimal_places=2, max_digits=2)
type = models.CharField(max_length=45)
amount = models.IntegerField()
event = models.ForeignKey(Event)
class Meta:
app_label = "core"
import datetime
from django.core.serializers import json
from django.db import models
from core.models import User
class Event(models.Model):
page_attribute = models.TextField()
name = models.TextField(max_length=128 , default="New Event")
description = models.TextField(default="")
type = models.TextField(max_length=16)
age_limit = models.IntegerField(default=0)
end_date = models.DateTimeField(default=datetime.datetime.now())
start_date = models.DateTimeField(default=datetime.datetime.now())
is_active = models.BooleanField(default=False)
user = models.ForeignKey(User)
ticket_type=models.ForeignKey('core.models.ticket_type.TicketType')
class Meta:
app_label = "core"
Here is the error I get:
CommandError: One or more models did not validate:
core.event: 'ticket_type' has a relation with model core.models.ticket_type.TicketType,
which has either not been installed or is abstract.
You're unnecessarily confusing yourself by having these in separate files within the same app.
But your issue is caused by the way you're referenced the target model. You don't use the full module path to the model: you just use 'app_name.ModelName'. So in your case it should be:
ticket_type=models.ForeignKey('core.TicketType')
Another issue can be when using multiple models in separate files missing statement like:
class Meta:
app_label = 'core_backend'
You can also get this error if there a bug in your models file that prevents it from loading properly. For example, in models.py
from third_party_module_i_havent_installed import some_method
I hit this error when I didn't put a third-party app in my INSTALLED_APPS setting yet.

Categories