form fields a not showing up on html page django - html

This is my template which I am using in the login page but the problem is fields are not showing up .I want to use mdbootstrap on the page.i have searched it on many websites but did't got a solution and every one was using the same thing to use the form is the something I am missing in my code?
<form action="{% url 'log_in' %}" method="POST">
{% csrf_token %}
<div class="md-form">
<i class="fa fa-envelope prefix"></i>
{{ form.username }}
{{ form.username.label_tag }}
</div>
<div style="padding:5px"></div>
<div class="md-form" >
<i class="fa fa-lock prefix"></i>
{{ form.password.label_tag }}
{{ form.password }}
</div>
{% if requset.GET.next %}
<input type="hidden" name="next" value="{{ request.GET.next }}">
{% endif %}
<button type='submit' class="btn info-color ">log in</button>
</form>
and forms.py
from django.contrib.auth.forms import AuthenticationForm
from django import forms
class LoginForm(AuthenticationForm):
username = forms.CharField(label="Username", max_length=30,
widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'username'}))
password = forms.CharField(label="Password", max_length=30,
widget=forms.PasswordInput(attrs={'class': 'form-control', 'name': 'password'}))
my view function is
def log_in(request):
if request.user.is_authenticated:
return render(request,'registration/userhome.html')
elif request.POST:
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user.is_active:
login(request, user)
return render(request,"registration/userhome.html")
else :
return HttpResponse("Invalid login details supplied.")
views login_view()
def login_view(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
pass # does nothing, just trigger the validation
else:
form = LoginForm()
return render(request,"registration/login.html",{'form':form})
I have not even rendered the login page but still they are working and the part of form feilds are missing in it
my urls.py file
from django.urls import path
from . import views
from django.contrib.auth.views import LoginView
urlpatterns =[
path("",views.index,name='index'),
path("userhome/",views.userhome,name='userhome'),
path("quiz/", views.quiz, name='quiz'),
path("signup/", views.sign_up,name='sign_up'),
path("login/", views.login_view, name='login'),
path("login/", views.log_in, name='log_in'),
path("index", views.log_out,name='log_out'),
path("rules/",views.rules,name='rules'),
]

You must have a view like this :
def myView(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
pass # does nothing, just trigger the validation
else:
form = LoginForm()
return render(request, 'myTemplate.html', {'form': form})

Related

django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'authentication.User' that has not been installed

I'm creating app with authentication. My project is dockerized. When I run the server everything works fine, except
authentication.User: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'.
But when I want to run docker-compose exec web python3 manage.py makemigrations or docker-compose exec web python3 manage.py migrate I get an error:
File "/usr/local/lib/python3.9/site-packages/django/contrib/auth/init.py", line 176, in get_user_model
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'authentication.User' that has not been installed
I've thought it points to settings.py field AUTH_USER_MODEL, but I haven't got it.
My views.py:
def signup(request):
if request.method == "POST":
context = {'has_error': False, 'data': request.POST}
email = request.POST.get('email')
username = request.POST.get('username')
password = request.POST.get('password')
if len(password) < 6:
messages.add_message(request, messages.ERROR,
'Password should be at least 6 characters')
context['has_error'] = True
if not validate_email(email):
messages.add_message(request, messages.ERROR,
'Enter a valid email address')
context['has_error'] = True
if not username:
messages.add_message(request, messages.ERROR,
'Username is required')
context['has_error'] = True
if models.User.objects.filter(username=username).exists():
messages.add_message(request, messages.ERROR,
'Username is taken, choose another one')
context['has_error'] = True
return render(request, 'authentication/signup.html', context) # status=409
if models.User.objects.filter(email=email).exists():
messages.add_message(request, messages.ERROR,
'Email is taken, choose another one')
context['has_error'] = True
return render(request, 'authentication/signup.html', context) # status=409
if context['has_error']:
return render(request, 'authentication/signup.html', context)
user = models.User.objects.create_user(username=username, email=email)
user.set_password(password)
user.save()
return render(request, 'authentication/signup.html')
My models.py:
from django.db import models
class User(models.Model):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
username = models.CharField(
max_length=200
)
def __str__(self):
return self.email
My signup.html:
{% include "_base.html" %}
{% load static %}
{% block title %}Sign Up{% endblock title %}
{% block content %}
<link rel="stylesheet" href="{% static 'css/authentication/signup.css' %}">
<div class="container">
<form class="signup_form" method="post" action="{% url 'signup' %}">
{% csrf_token %}
<input type="text" placeholder="Email" class="input_1" name="email">
<input type="text" placeholder="Username" class="input_2" name="username">
<input type="text" placeholder="Password" class="input_3" name="password">
<button type="submit" class="submit_btn">Sign Up</button>
</form>
</div>
{% endblock content %}
_base.html is just navbar.
When I add AUTH_USER_MODEL to settings.py it results in same error.
For this you should try adding an id field in the user model like so:
from uuid import uuid4
id = models.UUIDField(primary_key=True, editable=False, default=uuid4)
Also in your user model add this to the class:
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
I advice you also change the class name form User to CustomUser to avoid clashes with internal django backend, that will be.
From:
class User(models.Model):
to:
class CustomUser(AbstractUser):

facing problems in uploading files to a particular directory

i am using a html template to upload a file but i don't know how to process that file in django views file
i also have a model which is connected with the database
here is my html file
{% extends 'base.html' %}
{% block body %}
<form action="file" method="post" enctype="multipart/form-data" >
{% csrf_token %}
<input type="text" name="userName" placeholder="username">
<input name="file" type="file">
<input type="submit" value="submit">
</form>
{% for message in messages %}
{{ message }}
{%endfor%}
{% endblock %}
and here is my views.py function
def File(request):
if request.user.is_authenticated:
if request.method == 'POST':
user = request.POST['userName']
file = request.FILES
print(file)
# file = request.POST.copy()
# file.update(request.FILES)
# content_type = copied_data['file'].get('content-type')
# path = os.path.join(r'C:\Users\harsh\PycharmProjects\swatchBharat\SwatchBharat\media\files\\',file)
if User.objects.filter(username=user).exists():
file2 = points()
file_obj1 = DjangoFile(open(file, mode='rb'), name=file)
file_obj = File.objects.create(title=file, file=file_obj1, content_object=file, author=file.client)
file2.file =file2.save(ContentFile(file_obj))
file2.user = user
file2.save()
return HttpResponse('sucess bale bale!!!!!!!')
else:
messages.info(request,'the username you entered is incorrect')
return redirect("file")
return render(request, 'file.html')
else:
return HttpResponse('sorry this is restricted, login to continue')
my model.py file
from django.db import models
# Create your models here.
class points(models.Model):
user = models.TextField(max_length=50,default=None)
file = models.FileField(upload_to='files/')
point_3 = models.BooleanField(default=False)
point_5 = models.BooleanField(default=False)
point_9 = models.BooleanField(default=False)
i am stuck with it pls someone help me out
the solution for this is simple , thanks to shivendra-pratap-kushwaha for documentation link - docs.djangoproject.com/en/3.2/topics/http/file-uploads this was really helpfull
just need to specify request.FILES['file'] instead of request.FILES

Django: Template Form action not redirecting

My Form action is not redirecting to the passed view. I am calling simple_upload view method from login_form.html form action. Instead, upon clicking the login button, it stays on the same page. Below is my code:
urls.py:
from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from uploads.core import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', views.login_form, name='login_form'),
url(r'^upload/', views.simple_upload, name='simple_upload'),
url(r'^drop_down/$', views.drop_down, name='drop_down'),
url(r'^visualize_view/$', views.visualize_view, name='visualize_view'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.AKASH_ROOT)
login_form.html:
{% block content %}
<button onclick="document.getElementById('id01').style.display='block'" style="width:auto;">Login</button>
<div id="id01" class="modal">
<form class="modal-content animate" action="{% url 'simple_upload' %}" method="get">
{% csrf_token %}
<div class="imgcontainer">
<span class="close" title="Close Modal">×</span>
<img src="https://www.w3schools.com/howto/img_avatar2.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="submit">Login</button>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
</div>
<script>
// Get the modal
var modal = document.getElementById('id01');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
{% endblock %}
views.py:
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.core.files.storage import FileSystemStorage
from .models import Document
from .forms import ExpenseForm
def login_form(request):
return render(request, 'core/login_form.html')
def simple_upload(request):
return HttpResponse("Hello World")
Project hierarchy:
Your home URL pattern is not terminated, so it matches every path. It should be:
url(r'^$', views.login_form, name='login_form'),
It's not good form logic. Forms have valid and invalid actions. If your form is valid you redirect to new (success) page your user, but if not you render same (login) page. But firstly you should give a name your login page like below or use Django's inherit auth urls:
url(r'^login', views.login_form, name='login_form'),
It's my url paths:
from django.contrib import admin
from django.urls import path, include
from . import views
app_name = "user"
urlpatterns = [
path('sign_up/', views.sign_up, name="sign_up"),
path('account_activation_sent/', views.account_activation_sent, name='account_activation_sent'),
path('activate/<uidb64>/<token>/', views.activate, name="activate"),
path('login/', views.login_user, name="login"),
path('logout/', views.logout_user, name="logout"),
path('password_reset/', views.password_reset, name="password_reset"),
path('password_reset/done/', views.password_reset_done, name="password_reset_done"),
path('password_reset/<uidb64>/<token>/', views.password_reset_confirm, name="password_reset_confirm"),
path('password_reset/complete/', views.password_reset_complete, name="password_reset_complete"),
path('profile/<slug:slug>/', views.profile, name="profile"),
]
I wanna show you my simple login function and you will understand:
def login_user(request):
if request.user.is_authenticated:
return redirect("index")
else:
form = LoginForm(request.POST or None)
context = {
"form": form
}
go_to = request.POST.get('next', '/')
print(go_to)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = authenticate(username=username, password=password)
if user is None:
messages.error(request, "Username or password is incorrect! Try again.")
return render(request, "auths/login.html", context)
messages.success(request, "Login successful! Welcome bro.")
login(request, user)
go_to = request.POST.get('next', '/')
if go_to:
go_to = request.POST.get(
'next')
return redirect(go_to)
else:
return redirect("index")
return render(request, "auths/login.html", context)
I use Django's form and It's easy but you can use your custom form in your template. My form is like this:
class LoginForm(forms.Form):
username = forms.CharField(label="Username")
password = forms.CharField(label="Password", widget=forms.PasswordInput)
def __init__(self, *args, **kwargs):
super(LoginForm, self).__init__(*args, **kwargs)
self.fields['username'].label = ''
self.fields['password'].label = ''
class Meta:
model = User
fields = ('username', 'password' )
I hope It will help you.

Django how to adding comments option on a post

I am developing a blog which i want to add comment form option to it, i have added the form to the same page directly under the article, i want that went a user comment it should redirect to the same page with the article but i keep getting and error
here is my code
view
def comment(request, article_id):
try:
article = Article.objects.get(pk=article_id)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.cleaned_data['comment']
article.comments_set.create(comment=comment)
#messages.infos(request,comment)
return redirect('blog:_article')
#else:
#pass
#form = CommentForm()
#context['form'] = form
#return render(request,'blog/comment.html', context)
except Exception as e:
#wriet error to file
return render(request,'blog/404.html')
urls
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.index, name='index'),
path('<int:article_id>/article', views._article, name='_article'),
path('<int:article_id>/comment', views.comment, name='comment'),
]
models
class Comments(models.Model):
comment = models.TextField()
date = models.DateTimeField(default=timezone.now)
article = models.ForeignKey(Article, on_delete=models.CASCADE)
def __str__(self):
return self.comment
form
<form method="post" action="{% url 'blog:comment' article.id %}">
{% csrf_token %}
{% for field in form %}
{{ field.label_tag }}
{% render_field field class="form-control is-valid" rows="4" %}
{% endfor %}<br>
<button class="btn btn-success">Post</button>
</form>
I finally did it by adding the code to handle the comment in the same view that renders the articles this is my code
def _article(request, article_id):
try:
article = Article.objects.get(pk=article_id)
related_articles = Article.objects.filter(tags=article.tags).exclude(pk=article.pk)[:4]
context['article'] = article
context['related_articles'] = related_articles
context['form'] = CommentForm()
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.cleaned_data['comment']
article.comments_set.create(comment=comment)
return render(request,'blog/article.html', context)
except Exception as e:
#write error to file
return render(request,'blog/404.html')
If you don't want the page to redirect to another page or update the page, you should use AJAX (https://www.w3schools.com/jquery/jquery_ajax_get_post.asp) in this case. Your form will hit the url in the action by changing your page to that url so you have to handle the redirecting and rendering in your commenting view to come back to same page if you don't wanna do this dynamically.

form field not showing (django 1.7)

The form field (text area) is not showing in my django template. I can figure out where the problem is.
Views.py
class Profile(View):
"""User Profile page reachable from /user/<username> URL"""
def get(self, request, username):
params = dict()
user = User.objects.get(username=username)
tweets = Tweet.objects.filter(user=user)
params["tweets"] = tweets
params["user"] = user
return render(request, 'profile.html', params)
class PostTweet(View):
"""Tweet Post form available on page /user/<username> URL"""
def post(self, request, username):
if request.method == 'GET':
form = TweettForm()
else:
form = TweetForm(self.request.POST)
if form.is_valid():
user = User.objects.get(username=username)
tweet = Tweet(text=form.cleaned_data['text'], user=user, country=form.cleaned_data['country'])
tweet.save()
words = form.cleaned_data['text'].split(" ")
for word in words:
if word[0] == "#":
hashtag, created = HashTag.objects.get_or_create(name=word[1:])
hashtag.tweet.add(tweet)
return HttpResponseRedirect('/user/'+username)
return render(request, 'profile.html', {'form': form})
forms.py
from django import forms
class TweetForm(forms.Form):
text = forms.CharField(widget=forms.Textarea(attrs={'rows': 1, 'cols':85}), max_length=160)
country = forms.CharField(widget=forms.HiddenInput())
profile.html
{% extends "base.html" %}
{% block content %}
<div class="row clearfix">
<div class="col-md-12 column">
<form method="post" action="post/">{% csrf_token %}
<div class="col-md-8 col-md-offset-2 fieldWrapper">
{{ form.text.errors }}
{{ form.text }}
</div>
{{ form.country.as_hidden }}
<div>
<input type="submit" value="post">
</div>
</form>
</div>
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from tweets.views import Index, Profile, PostTweet
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', Index.as_view()),
url(r'^user/(\w+)/$', Profile.as_view()),
url(r'^admin/', include(admin.site.urls)),
url(r'^user/(\w+)/post/$', PostTweet.as_view())
)
Only the submit (post) button shows on the on when rendered in the browser. The text are is not there
You get nothing since you are not passing the form to the template. Write get function in PostTweet view and include form = TweetForm() in it as a param passed to the template.