I'm developing a Django project, and the team want to seperate the front-end and the back-ed, so I'm using Django to develop api. The format of the data transmitting is json. However, I want to use the defalt user package (django.contrib.auth), and I have to use Form. How could I convert the json received from the frontend to the form that I'm going to use in backend? thanks!
I have tried the silly code as below and it does not work.
#require_http_methods(["POST"])
def register(request):
form = CustomUserCreationForm(data=request.POST)
response = {"status": "success"}
if form.is_valid():
new_user = form.save()
print("valid")
return JsonResponse(response)
This is how your view must look if you want to register new user with custom form :
def register(request):
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
response = {}
if form.is_valid():
# The form is valid, now we can save the user in the db
new_user = form.save()
response = {"status": "success", "message": "User created"}
return JsonResponse(response)
else:
# Invalid form
response = {"status": "error", "message": "Form is invalid"}
else:
# It's not a post request ( GET or others)
# Instantiate an empty form
form = CustomUserCreationForm()
context = {
'form': form,
}
return render(request, 'register_template.html', context=context)
Related
OK im probably doing this all wrong!
I am trying to run a function in a view which calls another view.
This seems to pass my request into the next function as a POST method before loading the form from the second function.
my views.py
''' This section of hte code seems to function correctly '''
#login_required()
def joinLeague(request):
if request.method == 'POST':
league = JoinLeagueQueue(user=request.user)
form = JoinLeagueForm(instance=league, data=request.POST)
if form.is_valid():
form.save()
context = int(league.id) # displays id of model, JoinLeagueQueue
return HttpResponseRedirect(confirmLeague(request, context))
else:
form = JoinLeagueForm()
context = {'form':form}
return render(request, 'userteams/joinleagueform.html', context)
This section of the views file is not working correctly.
it seems to run the POST request without displaying the GET request with the form first.
#login_required()
def confirmLeague(request, league):
# gets ID of application to join league
joinleagueid=JoinLeagueQueue.objects.get(id=league)
pin = joinleagueid.pin # gets pin from application
user = joinleagueid.user # get user from application
leagueinquestion=League.objects.get(leaguePin=pin) # gets the league record for applied league
manager=leagueinquestion.leagueManager # Gets the league manager for league applied for
leaguename=leagueinquestion.leagueName # Gets the league name for league applied for
if request.method == 'POST':
if 'accept' in request.POST:
LeaguesJoinedTo.objects.create(
leaguePin = pin,
playerjoined = user,
)
return redirect('punterDashboard')# user homepage
else:
print("Error in POST request")
else:
context = {'leaguename':leaguename, 'pin':pin, 'manager':manager}
return render(request, 'userteams/confirmleague.html', context)
I now get an error saying Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/userteams/None
Using the URLconf defined in fanfoo_proj.urls, Django tried these URL patterns, in this order:
... im skipping a list of the patterns.
10. userteams/ confirmLeague [name='confirmLeague']
Ok i think the better way would be a HttpRedirect to the second view:
return confirmLeague(request, context)
should change to something like:
return redirect(confirmLeague,args=league)
django doc to urlresolvers: https://docs.djangoproject.com/en/3.0/topics/http/shortcuts/#redirect
def joinLeague(request):
if request.method == 'POST':
league = JoinLeagueQueue(user=request.user)
form = JoinLeagueForm(instance=league, data=request.POST)
if form.is_valid():
form.save()
context = league.id
return HttpResponseRedirect( reverse("your_confirmLeague_url",kwargs={'league':context}) )
else:
form = JoinLeagueForm()
context = {'form':form}
return render(request, 'userteams/joinleagueform.html', context)
def confirmLeague(request, league):
league = get_object_or_404(JoinLeagueQueue, pk=league)
pin = league.pin
if request.method == 'POST':
if 'accept' in request.POST: # This refers to the action from my form which is waiting for a button press in a html form.
LeaguesJoinedTo.objects.create(
leaguePin = pin,
playerjoined = request.user.id,
)
return redirect('punterDashboard')
else:
context = {'league':league}
return render(request, 'userteams/confirmleague.html', context)
I have a list of users with their email adress (only for Staff members), I am trying to send a form to the user.
When I use i.email, I get this error: "to" argument must be a list or tuple
When I use ['i.email'] I don't receive the message.
urls.py
path('users/<int:id>/contact', views.contactUser, name='contact_user'),
views.py
def contactUser(request, id):
i = User.objects.get(id=id)
if request.method == 'POST':
form = ContactUserForm(request.POST)
if form.is_valid():
message = form.cleaned_data['message']
send_mail('Website administration', message, ['website#gmail.com'], ['i.email'])
return redirect('accounts:users')
else:
form = ContactUserForm()
return render(request, 'accounts/contact_user.html', {'form': form, 'username': i})
I am using SendGrid. I have a 'contact us' form which is similar to contactUser and it works fine.
['i.email'] should be [i.email]
I have a view function that resubmits data when I refresh the page.
def home(request):
if request.method == 'POST':
form = ListForm(request.POST or None)
if form.is_valid():
form.save()
all_items = List.objects.all
messages.success(request,('Item has been added to List'))
return render(request, 'home.html', {'all_items': all_items})
else:
all_items = List.objects.all
return render(request, 'home.html',{'all_items':all_items})
Any ideas on how to prevent this please. render_to_response is now deprecated from what Ive read.
Thank you
Preventing form resubmission is nothing new, the canonical solution is the post-redirect-get pattern: after a successful post, you return a redirect HTTP response, forcing the user's browser to do a get. The canonical Django "form handler" view (in it's function version) is:
def yourview(request):
if request.method == "POST":
form = YourForm(request.POST)
if form.is_valid():
do_something_with_the_form_data_here()
return redirect("your_view_name")
# if the form isn't valid we want to redisplay it with
# the validation errors, so we just let the execution
# flow continue...
else:
form = YourForm()
# here `form` will be either an unbound form (if it's a GET
# request) or a bound form with validation errors.
return render(request, "yourtemplate.html", {'form': form, ...})
I have a context_processor.py file with the following function
def include_user_create(request):
if 'form' not in request.session:
form = CreateUserForm()
else:
form = request.session['form']
return { 'create_user_form' : form }
I use this to display my register in my base.html template, so that I may reuse it for all pages. A function create_user handles the form submit
def create_user(request):
form = CreateUserForm(request.POST or None, request.FILES or None)
if request.method == 'POST':
if form.is_valid():
user = form.save(commit=False)
user.save()
user = authenticate(username=user.email, password=user.password)
else:
request.session['form'] = form #<--- save
next = request.POST.get('next', '/')
return HttpResponseRedirect(next)
If the form is invalid I'd like to save the form so that the context_processor may reuse the form, for the purpose of saving the errors so they may be displayed in the template.
Doing this gives me a error:
TypeError: <CreateUserForm bound=True, valid=False, fields=(email;password;confirm_password)> is not JSON serializable
Is it possible to get this to work somehow?
You have this error because a form object is not JSON serializable, and the default session serializer is serializers.JSONSerializer.
Try to change it to a pickle serializer in your settings.py:
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
EDIT:
With this setting, you don't have to care about pickle serialization, you just have to write:
request.session['form'] = form
I have a form which contains an imagefield and some other fields.
my view looks like this:
def post_view(request):
def errorHandle(errors,form):
return render_to_response('post_form.html', {
'errors':errors,
'form' : form,
},context_instance=RequestContext(request))
if request.method == 'POST': # If the form has been submitted...
form = PostForm(request.POST, request.FILES) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
#save
else:
errors = form.errors
return errorHandle(errors,form)
else:
form = PostForm() # An unbound form
sucess = ''
return render_to_response('post_form.html', {
'form': form,
}, context_instance=RequestContext(request))
When errorHandle is called, it returns to the page with the form, errors and the values entered except for the value entered on an ImageField.
tell me if you need to look at my form and model. thanks in advance.
I think it's normal.
Path of a client image is secure for a backend, so, it was not sent. It's an official HTTP feature.