I want to add description text from users profile page to description column in my database, but when I submit form nothing happens and this column still empty.
I can get id and email on profile page after login, but can not get description form to my profile method
This is my database structure
login method:
#app.route('/', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
cur = mysql.connection.cursor()
cur.execute('SELECT * FROM users.data WHERE email = %s AND password = %s',
(email, password))
account = cur.fetchone()
if account:
session['loggedin'] = True
session['id'] = account[0]
session['email'] = account[3]
return redirect(url_for('profile'))
else:
return render_template('error.html')
return render_template('login.html')
profile method:
#app.route('/profile', methods=['GET','POST'])
def profile():
if 'loggedin' in session:
return render_template('profile.html', id=session['id'], email=session['email'])
if request.method == 'POST':
description = request.form['text']
cur = mysql.connection.cursor()
cur.execute('UPDATE users.data SET description = %s WHERE id = ?', (description, session['id']))
mysql.connection.commit()
cur.close()
return render_template('profile.html', id=session['id'], email=session['email'], description=description)
else:
return 'NO'
return redirect(url_for('login'))
profile.html:
your session id is: {{ id }}
your session email is: {{ email }}
your session symptom is: {{ description }}
<form action="" method="post">
<input type="text" name="text" class="form-control" placeholder="description">
<button class="btn btn-primary">Add</button>
</form>
Please assist.
I found an answer:
#app.route('/profile', methods=['GET','POST'])
def profile():
if request.method == 'GET':
if 'loggedin' in session:
return render_template('profile.html', id=session['id'], email=session['email'])
elif request.method == 'POST':
description = request.form['description']
print(description)
cur = mysql.connection.cursor()
# cur.execute('INSERT INTO users.data(description) VALUES (%s)', (description))
cur.execute('UPDATE users.data SET description = %s WHERE id = %s', (description, session['id']))
mysql.connection.commit()
cur.close()
print(description)
return render_template('profile.html', description=description)
else:
return 'NO'
return redirect(url_for('login'))
Related
I'm newbie to Django. I'm stuck at one thing that, valueError at /login/. I've tried my best to search and try to solve this but i didn't find my problem solution. In Following First Code Sample From Which I Got Error,
class Login(View):
template = 'login.html'
form = forms.LoginForm
def get(self, request):
if request.user.is_authenticated:
username = request.user
stud = Stud.objects.filter(adm=username).exists()
cord = Cord.objects.filter(staff_no=username).exists()
if stud:
return redirect('appStatus')
elif cord:
return redirect('cordIndex')
else:
return redirect('admin')
else:
form = self.form(None)
return render(request, self.template, {'form': form})
def post(self, request):
form = self.form(request.POST)
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
stud = Stud.objects.filter(adm=username).exists()
cord = Cord.objects.filter(staff_no=username).exists()
adv = adv.objects.filter(staff_no=username).exists()
if stud:
return redirect('studIndex')
elif cord:
return redirect('cordIndex')
elif adv:
return redirect('advIndex')
else:
context ={
'form': self.form(request.POST),
'errors': 'Either username or password is wrong'
}
return render(request, self.template, context)
Error traced from terminal:
ValueError: The view system.views.Login didn't return an HttpResponse object. It returned None instead.
I have a page that should show a button if the user is marked as "facturable" (billable), otherwise, the button should not appear. I tried the following code:
{% if form_experfil.facturable %}
<a href="{% url 'incid:xtodo' %}?pagref=factdatshow" type="button"
class="btn btn-primary waves-effect"> Consultar datos de facturaciĆ³n</a>
{% endif %}
But it keeps showing. This and other fails make me think that the {% if %} tag behaviour isnh't as straightforward as I thought, and it does not just clip the html code down to the endif tag, but something gets rendered first. Is there somewhere where this is formally documented without mystical references?. Is there a way to just show this button when the customer has this data and not show it otherwise?.
This is the view:
def perfil_view(request):
perfil = ExUserProfile.objects.get(user=request.user)
facturar = perfil.facturable
if facturar:
factdat = Factdat.objects.get(cliente=request.user)
if request.method == 'POST':
form_perfil = perfilEditForm(data=request.POST, instance=request.user)
form_experfil = experfilEditForm(data=request.POST, instance=perfil)
if facturar:
form_factdat = factdatEditForm(data=request.Post, instance=perfil)
if all([form_perfil.is_valid(), form_experfil.is_valid(), form_factdat.is_valid()]):
form_perfil.save()
form_experfil.save()
form_factdat.save(commit=facturar)
return HttpResponseRedirect('incid/perfil')
else:
form_perfil = perfilEditForm(instance=request.user)
form_experfil = experfilEditForm(instance=perfil)
if facturar:
form_factdat = factdatEditForm(instance=factdat)
template = "incid/perfil.html"
if facturar:
return render(request, template, {
'form_perfil': form_perfil,
'form_experfil': form_experfil,
'form_factdat': form_factdat
})
else:
return render(request, template, {
'form_perfil': form_perfil,
'form_experfil': form_experfil
})
and these are the models:
eclass ExUserProfile(models.Model):
user = models.OneToOneField(User,
primary_key=True,
on_delete=models.DO_NOTHING)
logo = ResizedImageField(size=[200, 200],
crop=['middle', 'center'],
quality=75, upload_to='static/logos/',
default='logos/no-img.jpg')
facturable = models.BooleanField(default=False)
def __str__(self):
return str(self.user)
class Factdat(models.Model):
cliente = models.OneToOneField(User,
verbose_name='cliente_fact',
primary_key=True,
default='',
on_delete=models.DO_NOTHING)
nomfact = models.CharField(max_length=240,
verbose_name='nomfact')
niffact = models.CharField(max_length=16,
verbose_name='niffact')
mailfact = models.EmailField(max_length=254,
verbose_name='mailfact')
telfact = models.CharField(max_length=24,
verbose_name='telfact')
persfact = models.CharField(max_length=128,
verbose_name='persfact')
class Meta:
verbose_name = "Fact_dat"
verbose_name_plural = "Fact_datos"
def __str__(self):
return str(self.cliente)
and just in case, here is the full page:
def perfil_view(request):
perfil = ExUserProfile.objects.get(user=request.user)
facturar = perfil.facturable
if facturar:
factdat = Factdat.objects.get(cliente=request.user)
if request.method == 'POST':
form_perfil = perfilEditForm(data=request.POST, instance=request.user)
form_experfil = experfilEditForm(data=request.POST, instance=perfil)
if facturar:
form_factdat = factdatEditForm(data=request.Post, instance=perfil)
if all([form_perfil.is_valid(), form_experfil.is_valid(), form_factdat.is_valid()]):
form_perfil.save()
form_experfil.save()
form_factdat.save(commit=facturar)
return HttpResponseRedirect('incid/perfil')
else:
form_perfil = perfilEditForm(instance=request.user)
form_experfil = experfilEditForm(instance=perfil)
if facturar:
form_factdat = factdatEditForm(instance=factdat)
template = "incid/perfil.html"
if facturar:
return render(request, template, {
'form_perfil': form_perfil,
'form_experfil': form_experfil,
'form_factdat': form_factdat
})
else:
return render(request, template, {
'form_perfil': form_perfil,
'form_experfil': form_experfil
})
I recevied an error when I request any page in the blog project I am working on, and I have no idea what is going wrong. Please help!
views.py
def post(request, id):
post = get_object_or_404(Post, id=id)
PostView.objects.get_or_create(user=request.user, post=post)
form = CommentForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
form.instance.user = request.user
form.instance.post = post
form.save()
return redirect(reverse("post-detail", kwargs={
'id': post.id
}))
context = {
'post': post,
'form': form,
}
return render(request, 'post.html', context)
here is the model.py:
class Post(models.Model):
title = models.CharField(max_length=50)
overview = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
content = HTMLField()
author = models.ForeignKey(Author, on_delete=models.CASCADE)
#thumbanail = models.ImageField()
#comment_count = models.IntegerField(default= 0)
#view_count = models.IntegerField(default= 0)
categories = models.ManyToManyField(Category)
featured = models.BooleanField()
def get_absolute_url(self):
return reverse('post-detail', kwargs={
'id': self.id
})
def get_update_url(self):
return reverse('post-update', kwargs={
'id': self.id
})
def get_delete_url(self):
return reverse('post-delete', kwargs={
'id': self.id
})
class Meta:
verbose_name_plural = 'Posts'
def __str__(self):
return f'{self.title}'
#property
def get_comments(self):
return self.comments.all().order_by('-timestamp')
#property
def comment_count(self):
return Comment.objects.filter(post=self).count()
#property
def view_count(self):
return PostView.objects.filter(post=self).count()
This is the I am receiving:
FieldError at /
Cannot resolve keyword 'comment_count' into field. Choices are: author, author_id, categories, comments, content, featured, id, overview, postview, timestamp, title
*
Like Hisahm__Pak said
remove #comment_count = models.IntegerField(default= 0)
comment_count = models.IntegerField(default= 0)
then save and make migrations
python manage.py makemigrations
python manage.py migrate
then run the server
python manage.py runserver
Whenever I go to the login site (0.0.0.0:5000/), the page immediately reverts to 0.0.0.0:5000/admin. Any ideas on why this is happening?
running through yocto on intel edison. editing via putty
#app.errorhandler(404)
#app.errorhandler(500)
def errorpage(e):
return render_template('404.html')
def login_required(f):
#wraps(f)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash('please login first.')
return redirect (url_for('index'))
return wrap
#app.route('/', methods=['GET','POST'])
def index():
error = None
if request.method == 'POST':
if request.form['username'] != 'admin' or request.form['password'] != 'password':
error = 'invalid attempt.'
else:
session['logged_in'] = True
return redirect(url_for('admin'))
return render_template('index.html', error = error)
#app.route('/logout')
def logout():
session.pop('logged_in', None)
return render_template('/logout.html')
#app.route('/admin',methods=['GET','POST'])
#login_required
def admin():
It looks like as soon as anyone hits the page with a GET, it's set as logged_in = True and redirects to /admin
#app.route('/', methods=['GET','POST'])
def index():
error = None
if request.method == 'POST':
if request.form['username'] != 'admin' or request.form['password'] != 'password':
error = 'invalid attempt.'
else: # this is always triggered for GETs, even if not logged in!
session['logged_in'] = True
return redirect(url_for('admin'))
return render_template('index.html', error = error)
Instead, you should be checking that they're already logged in, and set the logged_in property in the POST block instead, after credentials have been checked.
Actually, it just looks like your indenting is off on your else block:
#app.route('/', methods=['GET','POST'])
def index():
error = None
if request.method == 'POST':
if request.form['username'] != 'admin' or request.form['password'] != 'password':
error = 'invalid'
else: # this indenting should work now
session['logged_in'] = True
return redirect(url_for('admin'))
return render_template('index.html', error = error)
This is my models.py
class Cfituser(models.Model):
user = models.OneToOneField(User)
socialid = models.IntegerField(null=True)
accesstoken = models.CharField(max_length=255L, null = True)
class Meta:
db_table = 'CfitUser'
def __str__(self):
return "%s's profile" % self.user
#receiver(post_save, sender=User)
def create_cfituser(sender, instance, created, **kwargs):
if created:
Cfituser.objects.get_or_create(user=instance)
This is my views.py
#api_view(['GET', 'POST'])
def users_create(request, format = None):
"""
List all users, or create a new user.
"""
if request.method == 'GET':
cfituser = Cfituser.objects.all()
serializer = CfituserSerializer(cfituser, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = CfituserSerializer(data=request.DATA)
if serializer.is_valid():
print serializer.data
user = User.objects.create_user(username = serializer.data['socialid'])
cfituser = Cfituser.objects.get(user = user)
cfituser.accesstoken = serializer.data['accesstoken']
cfituser.socialid = serializer.data['socialid']
cfituser.save()
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Whenever there is a HTTP Post request, my database tables are filled in as expected but this error keeps popping up. I've tried almost every solution available on SO but I'm stuck with this.
I have tried user = models.OneToOneField(User, null = True) but this leads to two entries in my database table, one with user_id = NULL and one with user_id = actualvalue.
Any suggestions on how to fix this?
Saving by default commits the entry to the database, to prevent that, pass commit=False to save(), and then do your customizations.
serializer = serializer.save(commit=False)
user, created = User.objects.get_or_create(username = serializer.socialid)
cfituser, created = Cfituser.objects.get_or_create(user = user)
# cfituser.user = user This line is unnecessary
cfituser.accesstoken = serializer.accesstoken
cfituser.socialid = serializer.socialid
cfituser.save()
serializer.save()
You are also duplicating your efforts because your signal will also attempt to create a user. If you are on django 1.5, use customized user model; and for social registration/oauth, use django-social-auth.
OneToOneField means, in Cfituser.user the reverse side of the relation will directly return a single object(user.cfituser gives Cfituser). SO Cfituser.user must be unique through out the table(one and only one).
class Cfituser(models.Model):
user = models.OneToOneField(User)
socialid = models.IntegerField(null=True)
accesstoken = models.CharField(max_length=255L, null = True)
def __unicode__(self):
return "%s's profile" % self.user.username
def users_create(request, format = None):
"""
List all users, or create a new user.
"""
if request.method == 'GET':
cfituser = Cfituser.objects.all()
serializer = CfituserSerializer(cfituser, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = CfituserSerializer(data=request.DATA)
if serializer.is_valid():
print serializer.data
user = User.objects.create_user(username = serializer.data['socialid'])
Cfituser(user = user,accesstoken = serializer.data['accesstoken'],socialid = serializer.data['socialid']).save()
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)