I am uploading a photo by using a foreign key in forms but I didn't get any data in a database and I didn't get any errors.
models.py
from django.db import models
class username(models.Model):
name=models.CharField(max_length=100)
phone=models.BigIntegerField()
email=models.EmailField(max_length=100)
class Profilephoto(models.Model):
profile_photo = models.FileField(upload_to='media/')
uname = models.ForeignKey(username, on_delete=models.CASCADE, null=True)
forms.py
from django import forms
from .models import Profilephoto
class DocumentForm(forms.ModelForm):
class Meta:
model = Profilephoto
fields = ['profile_photo','uname']
view.py
from django.shortcuts import render, redirect, HttpResponse
from .models import username,Profilephoto
from .form import DocumentForm
def home(request):
if request.method == 'POST':
name = request.POST['name']
phone = request.POST['phone']
email = request.POST['email']
username(name=name,phone=phone,email=email).save()
users = username.objects.latest('id')
return render(request, 'home.html',{'usernames': users})
else:
users = username.objects.latest('id')
return render(request, 'home.html',{'usernames': users})
def data1(request,id):
if request.method == 'GET':
obj = username.objects.get(id=id)
form = DocumentForm(instance=obj)
return render(request, 'data1.html', {'form': form, 'usernames': obj})
elif request.method == 'POST':
obj = username.objects.get(id=id)
form = DocumentForm(request.POST, request.FILES, instance=obj)
if form.is_valid():
form.save()
return redirect('home')
return render(request, 'data1.html', {'usernames': obj})
data1.html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form|crispy }}
<div align="center">p
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
Please Help me Thanks in Advance
It's happening because your DocumentForm is form of model Profilephoto and in view function you are passing Username's instance.
so in your views.py, try this:
def data1(request,id):
if request.method == 'GET':
obj = username.objects.get(id=id)
form = DocumentForm()
return render(request, 'data1.html', {'form': form, 'usernames': obj})
elif request.method == 'POST':
obj = username.objects.get(id=id)
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('home')
return render(request, 'data1.html', {'usernames': obj})
Related
I have following views and each time form is submitted, result is rendered in new tab which has empty form.
How to render result in same form (with data submitted) without opening new tab?
views.py
class contact(View):
def __init__(self, logger=None, **kwargs):
self.logger = logging.getLogger(__name__)
def get(self, request):
return render(request, 'test.html')
def post(self, request):
if request.method == 'POST':
form = ContactForm(request.POST, request.FILES)
if form.is_valid():
self.host = form.data['ip']
messages.success(request, "Successful")
else:
form = ContactForm()
else:
form = ContactForm()
return render(request, 'test.html', {'form':form})
forms.py
class ContactForm(forms.Form):
ip = forms.CharField()
urls.py
urlpatterns = [
path('', contact.as_view()),
]
html
<body>
<form action="/" method= "post" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<button type="submit">Submit</button>
</form>
</body>
if form.is_valid()
form.save()
messages.success(request, 'Contact request submitted successfully.')
return render(request, 'your_page.html', {'form': ContactForm(request.GET)})
I'm really new to Django and I want to teach myself my making a simple note. But I don't understand how django forms work. I made simple template when I can display the user's notes and now I am trying to make a view when the user can add new notes to account using a simple form.
Here is my views.py file
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from .forms import CreateUserForm, CreateNoteForm
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .models import *
# Create your views here.
def loginPage(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
messages.info(request, 'Username or pasword is incorrect')
context = {}
return render(request, 'accounts/login.html', context)
def registerPage(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
user = form.cleaned_data.get('username')
messages.success(request, 'Account was created for '+ user)
return redirect('home')
context = {'form': form}
return render(request, 'accounts/register.html', context)
def logoutUser(request):
logout(request)
return redirect('login')
#login_required(login_url='login')
def home(request):
if request.user.is_authenticated:
username = request.POST.get('username')
context = {'username': username}
return render(request, 'accounts/home.html', context)
def notes(request):
username = None
if request.user.is_authenticated:
username = request.user.username
user_id = request.user.pk
user_notes = Note.objects.filter(user=user_id)
context = {
'user_notes': user_notes,
'username': username,
#'user_id' : user_id,
}
return render(request, 'accounts/notes.html', context)
def createNote(request):
username = request.user.username
user_id = request.user.pk
user_notes = Note.objects.filter(user=user_id)
form = CreateNoteForm()
if request.method == 'POST':
form = CreateNoteForm(request.POST)
if form.is_valid():
form.save()
return redirect('notes')
context = {'user_notes': user_notes, 'form': form}
return render(request, 'accounts/create_note.html', context)
forms.py:
from django.forms import ModelForm
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Note
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
class CreateNoteForm(forms.ModelForm):
class Meta:
model = Note
fields = ['user', 'title', 'text']
and create_note.html:
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<br>
<br>
<div class="container">
<div class="card text-white bg-dark mb-3">
<div class="container">
<form action="{% url 'notes' %}" method="POST">
<div class="card-body">
{% csrf_token %}
{{form}}
<input type="Submit" name="Submit">
</div>
</form>
</div>
</div>
</div>
{% endblock %}
The problem is the new note isn't added when I submit the data. And also if anyone have other suggestions for structuring my views or making this app better I am happy to read them and learn new ways of improving my project. Sorry for long post. I am really noob.
hello guys am having issues with django 3.0. am trying to create a user register page but i keep getting erros. these are my codes
users/views.py
from .form import UserRegisterForm
from django.shortcuts import render, redirect
# Create your views here.
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'register.html', {'form': form})
form.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
register.html
{% extends 'website/base.html' %}
{% block body %}
{% include 'website/nav_bar.html' %}
<div>
<form method="post">
{% csrf_token %}
<fieldset>
<legend>join now</legend>
{{ form.as_p }}
</fieldset>
<button type="submit">submit</button>
</form>
</div>
{% endblock body %}
ERROR MESSAGE
Here
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'register.html', {'form': form})
You forgot the case for normal GET request :)
something like that
def register(request):
form = UserRegisterForm()
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
return redirect('login')
return render(request, 'register.html', {'form': form})
More details on docs website https://docs.djangoproject.com/en/3.0/topics/forms/#the-view
im currently facing the problem that i want to call a view from another app (accounts app which holds the user model) within my main app (a blog app).
this is the error i get:
django.core.exceptions.FieldError: Unknown field(s) (username) specified for User
urls.py
...
from quickblog import views as core_views
from accounts import views as views_accounts
...
url(r'^myaccount/$', views_accounts.view_profile, name='myaccount'),
views.py (accounts app):
from django.shortcuts import render, redirect
from django.urls import reverse
from accounts.forms import (
RegistrationForm,
EditProfileForm
)
from django.contrib.auth.models import User
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect(reverse('accounts:home'))
else:
form = RegistrationForm()
args = {'form': form}
return render(request, 'reg_form.html', args)
def view_profile(request, pk=None):
if pk:
user = User.objects.get(pk=pk)
else:
user = request.user
args = {'user': user}
return render(request, 'profile.html', args)
def edit_profile(request):
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return redirect(reverse('accounts:view_profile'))
else:
form = EditProfileForm(instance=request.user)
args = {'form': form}
return render(request, 'edit_profile.html', args)
def change_password(request):
if request.method == 'POST':
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
return redirect(reverse('accounts:view_profile'))
else:
return redirect(reverse('accounts:change_password'))
else:
form = PasswordChangeForm(user=request.user)
args = {'form': form}
return render(request, 'change_password.html', args)
profile.html:
{% extends 'quickblog/base.html' %}
{% block head %}
<title>Profile</title>
{% endblock %}
{% block body %}
<div class="container">
<h1>Profile</h1>
<p>Username: {{ user }}</p>
<p>Bio: {{ user.bio }}</p>
<p>Avatar: {{ user.avatar }}</p>
{% if user.avatar.image %}
<img src="{{ user.avatar.image.url }}" width="250">
{% endif %}
</div>
{% endblock %}
This is my first django app, is there maybe anything i need to know about linking two apps within one project?
thanks
found the error at forms.py
class RegistrationForm(UserCreationForm):
user = forms.CharField(required=True)
class Meta:
model = User
fields = (
'username', < has to be user
'password1',
'password2',
)
anyways, thanks everybody :)
I try to add a comment but it does not save it to the database. There is no error.
My Views is
def add_comment(request, id):
article = get_object_or_404(Article, id=id)
if request.method == "POST":
form = CommentForm(request.POST,instance=article)
if form.is_valid():
comment = form.save(commit=False)
comment.post = article
comment.save()
return redirect('articles:detail', pk=article.pk)
else:
form = CommentForm()
template="article/comment.html"
return render(request, template, {'form': form})
comment.html:
<form method="POST">{% csrf_token %}
{{form.as_p}}
<button type="submit">Send</button>
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('name', 'comment')