I'm doing a to-do web app and I want user to input deadline and I have DateTimeField for it, but user can write whatever they want, but I want them to choose a legit date.
models:
class Task(models.Model):
title = models.CharField(max_length=50)
completed = models.BooleanField(default=False)
uploaded = models.DateTimeField(auto_now_add=True)
deadline = models.DateTimeField(null=True)
forms:
class TaskForm(forms.ModelForm):
title = forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Add new task...'}))
class Meta:
model = Task
fields = '__all__'
views:
def TaskView(request):
tasklist = Task.objects.all()
tasks = Task.objects.order_by('uploaded')
form = TaskForm()
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
context = {
'tastlist': tasklist,
'tasks': tasks,
'form': form,
}
return render(request, "pages/index.html", context)
Related
In my note taking project, I want to do so, that notes should be showed only for the author of the object. I am trying to solve this problem for 3 days. But, I could not solve this. Please Help! Thanks in an advance
view.py
#login_required(login_url='login')
def index(request):
tasks = Task.objects.all()
if request.method=='POST':
form = TaskForm(request.POST)
if form.is_valid():
obj = form.save()
obj.owner = request.user
obj.save()
return redirect('/')
form = TaskForm()
user = request
context = {
'tasks' : tasks,
'form':form,
'obj':obj
}
return render(request, 'list.html',context)
models.py
class Task(models.Model):
title = models.CharField(max_length=200)
completed = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
Your Task will need a ForeignKey to the user model, to keep track who created the task, so:
from django.conf import settings
class Task(models.Model):
title = models.CharField(max_length=200)
completed = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
I think in that case it is better to recreate the migration file that creates the table for the Task model.
Now that we have an owner of the Tasks, we can filter with:
#login_required(login_url='login')
def index(request):
tasks = Task.objects.filter(owner=request.user)
if request.method=='POST':
form = TaskForm(request.POST, request.FILES)
if form.is_valid():
form.instance.owner = request.user
obj = form.save()
return redirect('/')
else:
form = TaskForm()
context = {
'tasks' : tasks,
'form': form
}
return render(request, 'list.html', context)
I'm developing a small exchange system and I want to give everyone who joins this app a random amount (1-10) of btc. When someone compiles the register form succesfully, recives a random amount of Btc in the wallet. That is my code but doesn't work
models.py
class Profile(models.Model):
_id = ObjectIdField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
wallet = models.FloatField()
class Order(models.Model):
_id = ObjectIdField()
profile = models.ForeignKey(User, on_delete=models.CASCADE)
datetime = models.DateTimeField(auto_now_add=True)
price = models.FloatField()
quantity = models.FloatField()
views.py
def registerPage(request):
bonus = randint(1,10)
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.wallet = bonus
form.save()
return redirect('login')
contex = {'form':form}
return render(request, 'app/register.html', contex)
forms.py
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
I don't know if is't important but I'm working with Mongodb. Thanks
Try this:
def registerPage(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
new_user = form.save()
bonus = random.randint(1,10)
new_profile = Profile.objects.create(user=new_user, wallet=bonus)
new_profile.save() # unnecessary after calling `create` but I still do this just in case :)
return redirect('login')
else:
form = CreateUserForm()
contex = {'form':form}
return render(request, 'app/register.html', contex)
I am using the same form for profile_edit and create_profile functionality. It is updating the multi-choice values in the profile_edit page but does not create in create_profile.
Below is the form code in forms.py
class ProfileForm(ModelForm):
full_name = forms.CharField(required=True)
current_position = forms.CharField(required=True)
about_me = forms.Textarea(attrs={'required':True})
topic_name = forms.ModelMultipleChoiceField(Topic.objects.all())
class Meta:
model = Profile
fields =(
"full_name",
"current_position",
"about_me",
"topic_name",
)
Below is the views.py for profile creation
def create_profile(request, user_id):
if request.method == "POST":
form = ProfileForm(request.POST)
if form.is_valid():
form = form.save(commit=False)
user = get_object_or_404(User, id=user_id)
form.user = user
print(form.topic_name.all()) # Prints empty queryset
form.save()
return redirect("profile_view", user_id=user_id)
else:
context = {"form": form}
return render(request, "profile/create_profile.html", context)
else:
form = ProfileForm()
context = {
"form": form
}
return render(request, "profile/create_profile.html", context)
Below is Model.py
class Topic(models.Model):
topic = models.CharField(max_length=12)
def __str__(self):
return self.topic
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True,)
full_name = models.CharField(max_length=60, null=True)
current_position = models.CharField(max_length=64, null=True)
about_me = models.TextField(max_length=255, null=True)
topic_name = models.ManyToManyField(Topic)
def __str__(self):
return self.full_name
Both create_profile and edit_profile templates are exactly the same.
It saves everything except Multichoice field.
When you do save(commit=False),
you need to use mymodelform.save_m2m() below save(commit=True) on your ModelForm,
because many to many relationships cannot be saved without an ID.
see this docs
so in your views.py
if form.is_valid():
profile = form.save(commit=False)
user = get_object_or_404(User, id=user_id)
profile.user = user
profile.save()
form.save_m2m()
return redirect("profile_view", user_id=user_id)
I have a question concerning a new project I'm creating. To put it simply, the website has user accounts, and each user has the ability to create a simple paragraph. The form is functioning perfectly, but I can't seem to assign the user's ID to the saved form.
model.py
class UserProfile(models.Model):
user = models.OneToOneField(User)
class Thoughts(models.Model):
user = models.ForeignKey(UserProfile, null=True)
title = models.CharField(max_length=150, default='')
description = models.CharField(max_length=5000, default='')
forms.py
class ThoughtForm(ModelForm):
class Meta:
model = Thoughts
fields = ['title', 'description']
views.py
#login_required(login_url='sign_in')
def add_thought(request):
context = {}
populateContext(request, context)
user_details = UserProfile.objects.get(user=request.user)
context.update(user_details=user_details)
if request.method == 'POST':
new_thought_form = ThoughtForm(request.POST)
if new_thought_form.is_valid():
new_thought_form.save()
return HttpResponse('Hurray, saved!')
else:
new_thought_form = ThoughtForm()
c = {'new_thought_form': new_thought_form,}
c.update(csrf(request))
return render_to_response('lala/add_new_thought.html', c)
Whenever I try adding "instance=user_details.id", it says that the 'int' object has no attribute '_meta'. Any thoughts?
You can simplify the models by removing the UserProfile model:
# models.py
class Thoughts(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=150, default='')
description = models.CharField(max_length=5000, default='')
Your forms.py looks good.
Change your views:
# views.py
#login_required(login_url='sign_in')
def add_thought(request):
if request.method == 'POST':
form = ThoughtForm(request.POST)
if form.is_valid():
thought = form.save(commit=False)
thought.user = request.user
thought.save()
return HttpResponse('Hurray, saved!')
else:
form = ThoughtForm()
return render(request, 'lala/add_new_thought.html', {
'form': form
})
Getting Error "Todos.user" must be a "UserProfile" instance. can someone explain why?
I want users in Todos should point to UserProfile and whatever I save in Todos should be displayed in /profile/ ?
class UserProfile(models.Model):
user = models.OneToOneField(User)
birth =models.DateField()
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Todos(models.Model):
user = models.ForeignKey(UserProfile)
title = models.CharField(max_length=100)
created = models.DateField()
start_time = models.TimeField()
end_time = models.TimeField()
def __unicode__(self):
return unicode(self.user)
Form
class todosform(ModelForm):
title = forms.CharField(label=(u'Todo'))
created = forms.DateField(label=(u'Date'))
start_time = forms.TimeField(label=(u'Start Time'))
end_time = forms.TimeField(label=(u'End Time'))
#user = forms.CharField(label=(u'username')
class Meta:
model = Todos
exclude=('user',)
#url todo url(r'^todo/$', 'registration.views.todo'),
def todo(request):
if request.user.is_authenticated():
Todos.objects.filter(user=request.user)
if request.method == 'POST':
form =formtodos(request.POST)
if form.is_valid():# All validation rules pass
todoss = form.save(commit=False)
todoss.user = request.user
form.save()
return HttpResponseRedirect('/profile/')
else:
form = formtodos()
context = {'form':form}
return render_to_response('todo.html', context, context_instance=RequestContext(request))
#url profile url(r'^profile/$', 'registration.views.Profile'),
#login_required # decorator to check if request login
def Profile(request):
if not request.user.is_authenticated(): #if user not logged in
return HttpResponseRedirect('/login/')
#model = request.user.todos_set.all().order_by('created')[:7]
#u = Todos.objects.filter(created_by = request.user).get(pk=user)
registration = request.user.get_profile
context = {'registration':registration }
return render_to_response('profile.html',context,context_instance=RequestContext(request))
Your user field on Todos is a ForeignKey to UserProfile, not User. request.user is an instance of User. You could to this:
todoss.user = request.user.get_profile()