I am trying to go to the author profile if i press on his name. This is my HTML which do these:
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ user.username }}</h2>
</div>
</div>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Profile Info</legend>
<p class="text-secondary"><h3>Contact Me Here: </h3>{{ user.email }}</p>
</fieldset>
</form>
</div>
{% endblock content %}
In my views.py i have this:
def author_profile(request):
user = Post.author
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
context = {
'u_form': u_form,
'p_form': p_form
}
return render(request, 'blog/author_profile.html', context)
Where UserUpdateForm and ProfileUpdateForm from the forms.py have this code:
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email']
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']
Class for the Post:
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
If i press on the name it is getting me to the user profile, I tried to work with Post.author but didn't worked.
It's my first time with django.
Related
I am new at Django I want some helps. Basically,I want from users that they can select multiple images and save it, but I got like this and I don't know how to do it. I want to display the images and user can select one of them.
please help me.
models.py
class Images(models.Model):
product_image=models.ImageField(upload_to='media',null=True, blank=True)
def __str__(self):
return "{}".format (self.product_image)
class user_select(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
product_image=models.ForeignKey(Images, on_delete=models.CASCADE)
def __str__(self):
return "{}".format (self.name)
forms.py
class UserForm(forms.ModelForm):
class Meta:
model = user_select
fields = '__all__'
views.py
def home(request):
form = UserForm()
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
form.save()
context = {'form':form}
return render(request, 'home.html', {'form':form})
home.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container mt-5">
<div class="row mt-5 mr-5">
<div class="col-md-8 mt-5">
<div class="card border border-secondary mt-5">
<div class="col-md-8 mt-5" align='center'>
<form method="POST" action="" >
{% csrf_token %}
<div class="col-md-8">
{{ form|crispy }}
</div>
</form>
<button type="submit" class="btn btn-success mt-5 mb-5">Place Order</button>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
enter image description here
I am following a Django tutorial on Youtube, I added a bio field in the UserUpdateForm. There is a slot for me to edit the bio on change_profile.html but when I press the update button it updates everything else except for the bio.
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
# What I added
bio = forms.CharField(required=False)
class Meta:
model = User
fields = ['username', 'email', 'bio']
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']
The function that saves the forms
#login_required
def change_profile(request):
if request.method == 'POST':
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, 'Profile Updated')
return redirect('profile')
else:
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
context = {
'u_form' : u_form,
'p_form' : p_form
}
return render(request, 'users/change_profile.html', context)
The change_profile.html
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block title %}Change Profile{% endblock title %}
{% block content %}
<div class="content-section">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Edit Profile</legend>
{{ u_form|crispy }}
{{ p_form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Update</button>
</div>
</form>
</div>
{% endblock content %}
And the profile.html
{% extends "blog/base.html" %}
{% block title %}Profile{% endblock title %}
{% block content %}
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ user.username }}</h2>
<p class="text-secondary">{{ user.email }}</p>
<p class="article-content">{{ user.bio }}</p>
</div>
</div>
<a class="ml-2" href="{% url 'change_profile' %}">Edit Profile</a>
{% endblock content %}
It's because the default User model has no attribute called bio, so there's nowhere to store the value you're getting from the form. You need to add it to the model first. You can create a custom user model, but since you already have a Profile model, you can store bio along with image:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField()
bio = models.CharField(max_length=225, blank=True, null=True)
And in forms.py add the new field to the field list:
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('image', 'bio')
You could have simply override the the User model and add your custom fields, then you don't need to add extra fields in your form. Check this example:
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
bio = models.TextField()
def __str__(self):
return unicode(self.user)
Make sure you add mention your custom User model in settings:
AUTH_USER_MODEL ='your_app.UserProfile'
Good morning guys, I have a problem with a form.
My code:
models.py
class AnagraficaGenerale(models.Model):
ragionesociale = models.CharField(max_length=40, null=True, blank=True)
cf = models.CharField(max_length=40, null=True, blank=True)
piva = models.CharField(max_length=40, null=True, blank=True)
forms.py
class AnagraficaGeneraleForm(forms.ModelForm):
class Meta:
model = AnagraficaGenerale
fields = '__all__'
views.py
#login_required
def anagrafica_new(request):
if request.method == "POST":
form = AnagraficaGeneraleForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('anagrafica_list')
else:
form = AnagraficaGeneraleForm()
return render(request, 'Anagrafiche/anagrafica_new.html', {'form': form})
html
{% extends 'FBIsystem/basenobar.html' %}
{%load staticfiles %}
{% block content %}
<div id="page-wrapper">
<div class="panel">
<div class="panel-body">
<h3 class="title-hero">
Nuova Anagrafica
</h3>
<form method="POST" class="form-horizontal bordered-row">
{% csrf_token %}
<div class="example-box-wrapper">
<div class="form-group">
<label class="col-sm-2 control-label" > Ragione Sociale:</label>
<div class="col-sm-6">
{{ form.ragionesociale }}
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-lg btn-block">Salva</button>
</form>
</div>
</div>
</div>
{% endblock %}
Everything seems ok but not save, if I try with {{form.as_table}} it save.
I think there is a problem with custom field but I don't know how.
whats wrong?
TY
Hi guys I'm a beginner to Django and I'm trying to implement a login system into my django planner.
The error:
FieldError at /login_user/
Cannot resolve keyword 'user' into field. Choices are: description, end_time, id, start_time, title
I've tried adding the user field into my event model on model.py and migrating it but it just makes the whole application crash.
views.py
def event(request, event_id=None):
instance = Event()
if event_id:
instance = get_object_or_404(Event, pk=event_id)
else:
instance = Event()
form = EventForm(request.POST or None, instance=instance)
if request.POST and form.is_valid():
form.save()
return HttpResponseRedirect(reverse('cal:calendar'))
return render(request, 'cal/event.html', {'form': form})
def login_user(request):
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
events = Event.objects.filter(user=request.user)
login(request, user)
return render(request, 'cal/calendar.html', {'calendar': calendar})
else:
return render(request, 'cal/login.html', {'error_message': 'Your account has been disabled'})
else:
return render(request, 'cal/login.html', {'error_message': 'Invalid login'})
return render(request, 'cal/login.html')
forms.py
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email', 'password',]
models.py
from django.contrib.auth.models import Permission, User
from django.db import models
class Event(models.Model):
#user = models.ForeignKey(User, default=1)
title = models.CharField(max_length=200)
description = models.TextField()
start_time = models.DateTimeField()
end_time = models.DateTimeField()
#property
def get_html_url(self):
url = reverse('cal:event_edit', args=(self.id,))
return f' {self.title} '
calendar.html
{% extends 'cal/base.html' %}
{% block title %}
Calendar
{% endblock %}
{% block content %}
<div class="clearfix">
<a class="btn btn-info left" href="{% url 'cal:calendar' %}?{{ prev_month }}"> Previous Month </a>
<a class="btn btn-info right" href="{% url 'cal:calendar' %}?{{ next_month }}"> Next Month </a>
<a class="btn btn-info right" href="{% url 'cal:event_new' %}"> New Event </a>
</div>
{{ calendar }}
{% endblock %}
login.html
{% extends 'cal/base_visitor.html' %}
{% block title %}Log In{% endblock %}
{% block login_active %}active{% endblock %}
{% block body %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-6">
<div class="panel panel-default">
<div class="panel-body">
<h3>Log In</h3>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<form class="form-horizontal" role="form" action="{% url 'cal:login_user'%}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label class="control-label col-sm-2" for="id_username">
Username:
</label>
<div class="col-sm-10">
<input id="id_username" maxlength="30" name="username" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="id_password">
Password:
</label>
<div class="col-sm-10">
<input id="id_password" maxlength="30" name="password" type="password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
<div class="panel-footer">
Don't have an account? Click here to register.
</div>
</div>
</div>
</div>
</div>
{% endblock %}
In your view you are filtering Event objects with the keyword user, but your event model has no field called user. If you want your event associated with a user you can add a foreignkey to your Event model:
class Event(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
title = models.CharField(max_length=200)
description = models.TextField()
start_time = models.DateTimeField()
end_time = models.DateTimeField()
#property
def get_html_url(self):
url = reverse('cal:event_edit', args=(self.id,))
return f' {self.title} '
Or, in your view, you can simply filter your Event objects by another keyword the choices for which your error gave you, and which are just the fields you specified in your model. So in your view you could do this:
def login_user(request):
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
events = Event.objects.filter(title='Title you want to filter by') # This line seems to be the source of your error. You just need to filter by a keyword that exists in your model.
login(request, user)
return render(request, 'cal/calendar.html', {'calendar': calendar})
else:
return render(request, 'cal/login.html', {'error_message': 'Your account has been disabled'})
else:
return render(request, 'cal/login.html', {'error_message': 'Invalid login'})
return render(request, 'cal/login.html')
In your models.py you missed adding a relationship for your user table. add user and do a
python manage.py makemigrations myapp
python manage.py migrate myapp
from django.contrib.auth import get_user_model
class Event(models.Model):
user = models.ForeignKey(get_user_model(), null=True)
title = models.CharField(max_length=200)
description = models.TextField()
start_time = models.DateTimeField()
end_time = models.DateTimeField()
#property
def get_html_url(self):
url = reverse('cal:event_edit', args=(self.id,))
return f' {self.title} '
I subscribed the code of my model, and after this i'm rendering this form django to put on a bootstrap form. I'm trying, without no sucess, put a datepicker in this form, but I dont found it in anywhere how to do this.
This is my model:
class Usuario(User):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
birthday = models.DateField("Birthday")
class Meta:
verbose_name = "Usuario"
This other code is about the form:
class FormUsuario(UserCreationForm):
class Meta:
model = Usuario
fields = ("username", "email", "birthday")
def __init__(self, *args, **kwargs):
super(FormUsuario, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['placeholder'] = "Usuário"
self.fields['email'].widget.attrs['placeholder'] = "Email"
self.fields['password1'].widget.attrs['placeholder'] = "Senha"
self.fields['password2'].widget.attrs['placeholder'] = "Confirmar senha"
self.fields["birthday"].help_text = "mm/dd/aaaa"
self.fields['email'].required = True
When I used {% csrf_token %} {{ form|bootstrap_horizontal }} on template, is not show a datepicker.
{% load bootstrap %}
<form class="form-horizontal" method="POST" action="/cadastro/">
{% csrf_token %}
{{ form|bootstrap_horizontal }}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success btn-lg btn-block">Salvar</button>
</div>
</div>
</form>
{% endblock %}
How can I make up a datepicker on my bootstrap form?