How to stop Django from rendering result in new tab - django

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)})

Related

success_url doesn't redirect to redirect page

Please help me out. My success_url doesn't redirect to the redirect page specified. I've tried using HttpResponseRedirect, reverse_lazy, and reverse. All gives the same issue.
Views:
class SignUp(FormView):
template_name = 'blogApi/tenant_registration.html'
form_class = ClientForm
success_url = HttpResponseRedirect("home")
def get(self, request, *args, **kwargs):
form = ClientForm()
context = {'form': form}
return render(request, 'blogApi/tenant_registration.html', context)
def post(self, request, *args, **kwargs):
form = ClientForm(data=request.POST)
if form.is_valid():
name = form.cleaned_data['name']
Client.objects.create(name=name, schema_name=name, domain_url=name + ".localhost")
# return render(request, 'blogApi/tenant_registration.html', {'form': form})
return render(request, 'blogApi/tenant_registration.html', {'form': form})
urls
urlpatterns = [
path('signup/', SignUp.as_view(), name="sign_up"),
path('home/', include(router.urls), name='home'),
path("register", signup, name="register")
]
html page:
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Create Account">
</form>

Cant uploading data through foreign key with crispy forms

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})

Upload multiple files with one single input

Multiple files do not save in admin, only the first saved in admin.
class Image(models.Model):
imageuploader_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True)
image = models.FileField(upload_to ='pictsagram/')
image_caption = models.CharField(max_length=700)
def upload(request):
form = PostForm(request.POST,request.FILES)
if request.method == "POST":
if form.is_valid():
for f in request.FILES.getlist('image'):
post = Image(image=f)
post = form.save(commit=False)
post.imageuploader_profile = request.user
print(request.user)
post.save()
form.save()
return redirect('/')
else:
form = PostForm()
return render(request, 'upload.html', {"form": form})
class PostForm(forms.ModelForm):
class Meta:
model = Image
fields = ('image_caption', 'image',)
<form action="{% url 'site:upload' %}" method="post" enctype="multipart/form-data">
{%csrf_token%}
<input type="file" name="file" multiple onchange="loadFile(event)" required="" id="id_file">
<button type="submit">Post</button>
</form>
It looks like your form is for an Image object, but you're trying to create multiple images from a single form submit.
You are creating the Image(), but it doesn't look like you're attaching it to the form. So you'll probably need to reorganize the view something like:
def upload(request):
if request.method == "POST":
for image_file in request.FILES.getlist('image'):
form = PostForm(request.POST, image_file)
if form.is_valid():
image = form.save(commit=False)
image.imageuploader_profile = request.user
image.save()
form.save()
return redirect('/')
else:
form = PostForm()
return render(request, 'upload.html', {"form": form})
Also, cut/paste can mess up formatting, but always double-check your indentation for intended flow.
use this code:-----------------------------
def upload(request):
form = PostForm(request.POST,request.FILES)
if request.method == "POST":
if form.is_valid():
for f in request.FILES.getlist('file'):
post = Image(image=f)
post = form.save(commit=False)
post.imageuploader_profile = request.user
print(request.user)
post.save()
form.save()
return redirect('/')
else:
form = PostForm()
return render(request, 'upload.html', {"form": form})
class PostForm(forms.ModelForm):
class Meta:
model = Image
fields = ('image_caption', 'image',)
<form action="{% url 'site:upload' %}" method="post" enctype="multipart/form-data">
{%csrf_token%}
<input type="file" name="file" multiple onchange="loadFile(event)" required="" id="id_file">
<button type="submit">Post</button>
</form>

Django 3.0 ValueError

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

django def post method isnt working in cbv

i can't figure our why i can't override the post . when i post the form i go to "/" directory and nothing post . i already know knows that the forms works fine because i have it working as a fbv
my view
class ProfileUpdateView(LoginRequiredMixin, View):
template_name = "accounts/update.html"
def get_object(self):
user = get_object_or_404(User, username=self.kwargs.get("username"))
return user
def get(self, request, *args, **kwargs):
user = get_object_or_404(User, username=self.kwargs.get("username"))
user_form = UserForm(instance=user)
if user.is_client:
print("client get is working")
profile = Client.objects.get(id=user.clients.id)
profile_form = ClientForm(instance=profile)
if user.is_artisan:
profile = Artisan.objects.get(id=user.artisans.id)
profile_form = ArtisanForm(instance=profile)
return render(
request,
self.template_name,
{"user_form": user_form, "profile_form": profile_form},
)
def post(self, request, *args, **kwargs):
print("post is working")
if user.is_client:
print("client post is working")
profile_form = ClientForm(
request.POST, request.FILES, instance=profile
)
user_form = UserForm(request.POST, request.FILES, instance=user)
if user.is_artisan:
profile_form = ArtisanForm(
request.POST, request.FILES, instance=profile
)
user_form = UserForm(request.POST, request.FILES, instance=user)
if profile_form.is_valid() and user_form.is_valid():
print("form validation is working")
created_profile = profile_form.save(commit=False)
user_form.save()
created_profile.save()
reverse("accounts:profile", kwargs={"username": self.user.username})
return render(
request,
self.template_name,
{"user_form": user_form, "profile_form": profile_form},
)
template
<form action="." method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ user_form.as_p }}
<p> client form</p>
------------------------------------------------
{{ profile_form.as_p }}
<button class="btn btn-primary btn-round" type="submit">update</button>
</form>
Your form action is set to ".", i.e. "this directory".
Instead just leave it out to POST to the current URL.
<form method="POST" enctype="multipart/form-data">