I have looked at a lot of different places but none of their solutions work. This is most likely to do them being for older versions of django or my own stupidity. So I am making a blog type of app that for some reason is called reviews instead of blog... anyway I need to automatically fill up an author field with the username of the logged in user. Here is my models.py:
from django.db import models
from django.contrib.auth.models import User
#vars
# Create your models here.
class reviews(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(User, on_delete=models.PROTECT,)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True, blank=True)
and forms.py:
from django import forms
from django.forms import ModelForm
from .models import reviews
from django.contrib.auth.decorators import login_required
class CreatePost_form(ModelForm):
class Meta:
model = reviews
exclude = ['author']
fields = ['title', 'body',]
and views:
from django.shortcuts import render, render_to_response
from .forms import CreatePost_form
from django.http import HttpResponseRedirect
# Create your views here.
def reviewlist(request):
return render
def index(request, ):
return render(request, template_name="index.html")
def CreatePost(request):
form = CreatePost_form(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/reviews/succesfulpost')
return render(request, "reviews/CreatePostTemplate.html", {'form':form})
def succesfulpost(request):
return render(request, "reviews/succesfulpost.html")
def CreatePost(request):
form = CreatePost_form(request.POST)
if form.is_valid():
form.save(commit=False)
form.author = request.user
form.save()
return HttpResponseRedirect('/reviews/succesfulpost')
As simple as that. Rather than actually saving and committing the data, you simply save without committing then you're able to change the value of the excluded field.
Related
I am trying to make a simple to-do list in Django that each user could have their own task list so when they logged in they add a task and its save for themselves and the list only display their own tasks, but when I try to add a task from the template's form it won't save but when I add task manually from admin panel it work.
my models.py
from django.db import models
from django.contrib.auth.models import User
class Tasks(models.Model):
user = models.ForeignKey(User, null=True,on_delete=models.CASCADE)
title = models.CharField(max_length=200)
check = models.BooleanField(default = False)
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
forms.py
from django import forms
from django.forms import ModelForm
from .models import *
class TaskForm(forms.ModelForm):
class Meta:
model = Tasks
fields = '__all__'
views.py:
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .forms import *
from .models import Tasks
#login_required(login_url = 'login')
def tasks(request):
tasks = Tasks.objects.filter(user = request.user)
context = { 'tasks': tasks }
return render(request,'ToDo/list.html',context)
#login_required(login_url = 'login')
def add_task(request):
form = TaskForm()
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.user = request.user
form.save()
return redirect('/')
context = {'form' : form}
return render(request,'ToDo/add.html',context)
where is the problem?
You assign the user to the .user attribute of the form, not of the .instance wrapped in the form. You thus should alter the instance with:
#login_required(login_url = 'login')
def add_task(request):
if request.method == 'POST':
form = TaskForm(request.POST, request.FILES)
if form.is_valid():
form.instance.user = request.user
form.save()
return redirect('/')
else:
form = TaskForm()
return render(request, 'ToDo/add.html', {'form' : form})
You should furthermore only redirect in case of a successful POST request: in case the POST request is not successful, the form can render the error messages, and thus will inform the user what the problem is.
Furthermore you make the user field non-editable:
from django.conf import settings
class Tasks(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
editable=False,
on_delete=models.CASCADE
)
title = models.CharField(max_length=200)
check = models.BooleanField(default = False)
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.
The dropdown list appears correctly in the html, However I am unable to figure out why I run into the same error time after time when I try to submit / .
"Select a valid choice. That choice is not one of the available choices."
the problem context
I have two models defined in Django. One CourseModel database to hold all the offered courses and one registration database to link a course to a user.
models.py
from django.db import models
# Create your models here.
class CourseModel(models.Model):
course = models.CharField(max_length=100)
date = models.DateField(max_length=100)
time = models.TimeField()
location = models.CharField(max_length=100)
datetime = models.DateTimeField()
class RegistrationModel(models.Model):
name = models.CharField(max_length=100)
adress = models.CharField(max_length=100)
city = models.CharField(max_length=100)
email = models.EmailField(max_length=100)
course = models.ForeignKey('self', on_delete=models.CASCADE)
def __str__(self):
return self.name
I use modelForm to create a registration form, where the user can subscribe for a course from a dropdown list.
forms.py
from django.forms import ModelForm, RegexField
from home.models import RegistrationModel, CourseModel
from django import forms
import datetime
class RegistrationForm(ModelForm):
def __init__(self, *args, **kwargs):
super(RegistrationForm, self).__init__(*args, **kwargs)
self.fields['course'].queryset = CourseModel.objects.exclude(date__lt=datetime.datetime.today()).values_list('datetime', flat=True)
self.fields['course'].empty_label = None
class Meta:
model = RegistrationModel
fields = '__all__'
views.py
from django.shortcuts import render, redirect
from home.forms import RegistrationForm
from .models import CourseModel
import datetime
def home(request):
return render(request, 'home/home.html')
def registration(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
crs = request.POST.get('course')
print(crs)
if form.is_valid():
cleanform = form.save(commit=False)
cleanform.course = crs
cleanform.save()
return redirect('home')
else:
form = RegistrationForm()
return render(request, 'home/registration.html', {'form': form})
In the RegistrationForm's __init__() method, your self.fields['course'].queryset = ...values_list('datetime', flat=True) returns datetime instances. See values_list() docs.
I believe this may cause the issue. I guess the queryset should return CourseModel instances, based on the Django docs:
ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet.
Also, your RegistrationModel.course field has a foreign key to 'self' instead of the CourseModel. Not sure if that is what you want.
Other examples of setting the field queryset can be found here.
I have the following code in django:
models.py
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils import timezone
class Recipe(models.Model):
title = models.CharField(max_length=100)
ingredients = models.TextField(max_length=200,help_text="Put the ingredients required$")
instructions = models.TextField(max_length=500)
def __unicode__(self):
return self.title
forms.py
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import RecipeForm
def add(request):
if request.method == 'POST':
form = RecipeForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('app_name:url'))
else:
messages.error(request, "Error")
return render(request, 'page.html', {'form': RecipeForm()})
Does anyone know how do I associate a user id with it so that when it is saved in database, it also saves which user made this recipe and when a user logs in, he is able to see his recipes only and not the recipes saved by other users. Any suggestions?
You should add a ForeignKey field, pointing to the built-in User model, in your Recipe model:
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='recipes')
this field will contain the id of the user who created the recipe.
EDIT
And if you have an user object you can access all its recipes like this:
user.recipes.all()
and you'll get only the recipes of that user.
I have designed a form in django wherein there are 3 fields "Title","Body" & "Tagline". So my query is that when i press submit button after filling up the data that data should be directly inserted into my "notes" database.
Models.py
from django.db import models
class pim(models.Model):
Title = models.CharField(max_length=40)
Body = models.CharField(max_length=40)
TagLine = models.CharField(max_length=40)
Views.py
from django.shortcuts import render_to_response
from django.http import HttpResponse, Http404
def Notes_create(request):
return render_to_response('notesform.html',locals())
You'll need to create a modelform for your pim model:
class pimForm(ModelForm):
class Meta:
model = pim
And your view will have to display the form and handle it when the request type is a POST:
def new(request):
if request.method == 'POST':
form = pimForm(request.POST)
if form.is_valid():
form.save()
return redirect(reverse('your.pim.detail.view', args=[pim.pk]))
else:
form = pimForm()
return render_to_response('notesform.html', {'form': form}, context_instance=RequestContext(request))
Something like that should work
I want to save the email and name fields in django default table called UserSignup
my models.py is:
from django.db import models
class UserSignup(models.Model):
mailid = models.CharField(max_length=100)
name = models.CharField(max_length=100)
my views.py is:
from django import views
from django.shortcuts import render_to_response
from django.template import RequestContext
from Deals.signup.forms import signup
from django.contrib.auth.models import User
from django.http import HttpResponse
def usersignup(request,form_class=signup):
form = form_class()
print form
if form.is_valid():
mail= UserSignup(mailid=request.POST['mailid'])
mail.save()
name= UserSignup(name=request.POST['name'])
name.save()
else:
form = form_class()
return render_to_response('signup/registration_form.html',{'form':form})
and forms.py is
from django import forms
from django.contrib.auth.models import User
from Deals.signup.models import *
from django.utils.translation import ugettext_lazy as _
class signup(forms.Form):
email = forms.EmailField(widget=forms.TextInput(),
label=_("Email address:"))
username = forms.RegexField(regex=r'^\w+$',
max_length=30,
widget=forms.TextInput(),
label=_("Name:"))
def save(self,request,update):
name = self.cleaned_data['name']
name.save()
email = self.cleaned_data['email']
email.save()
Please help me in saving my forms input in database
Check the Django documentation properly http://docs.djangoproject.com/en/dev/topics/forms/
Just change your code in views.py.
def usersignup(request,form_class=signup):
if request.method == 'POST': #If its a form submission, the method is POST
form = form_class(request.POST)
if form.is_valid():
newuser = form.save()
else: #Else display the form
form = form_class()
return render_to_response('signup/registration_form.html',{'form':form})
The 'save' function in your forms file is incorrect and is not needed.
On a side note, your "UserSignup" is not a default User Table. That would be the user model provided by Django. And that already has the fields that you are creating in UserSignup. Why don't you use that feature of Django?
It might be better to save the model elements in the form in one time.
def save(self):
new_user = User.objects.create_user(name = self.cleaned_data['name'],
email = self.cleaned_data['email'])
return new_user