I have a view called Edit, that edits an object. I want the user to only be able to edit it if it's unlocked, meaning, an attribute is called locked = BooleanField() and in the view, you first check whether the object is locked or not before proceeding.
This is the edit function so far:
#login_required
def editdossier(request, pk):
dossier = get_object_or_404(Dossier, id=pk)
form = AddDossierForm(request.POST or None, instance = dossier)
context = {'form': form}
if form.is_valid():
dossier = form.save(commit= False)
dossier.save()
context = {
'form': form,
'dossiers': Dossier.objects.all()
}
return render(request, 'dashboard/home.html', context)
else:
context= {'form': form}
return render(request,'dashboard/modifier_dossier.html' , context)
And this is what I want to do:
#login_required
def editdossier(request, pk):
dossier = get_object_or_404(Dossier, id=pk)
# CHECK IF DOSSIER.LOCKED == FALSE:
form = AddDossierForm(request.POST or None, instance = dossier)
context = {'form': form}
if form.is_valid():
dossier = form.save(commit= False)
dossier.save()
context = {
'form': form,
'dossiers': Dossier.objects.all()
}
return render(request, 'dashboard/home.html', context)
else:
context= {'form': form}
return render(request,'dashboard/modifier_dossier.html' , context)
I did the following check:
if dossier.locked == false:
proceed
but the condition is not checked. I tried if dossier[0].locked == false but it shows an error saying the object is not indexable.
Related
if i print df_costo the result of the dataframe is ok, but in html file doesn0t show nothing
''' code '''
def fase_progetto(request):
try:
qs_costo = CostoFase.objects.all()
costo_fase_data =[
{
'Responsabile': x.responsabile,
'Costo': x.costo
} for x in qs_costo
]
df_costo = pd.DataFrame(costo_fase_data)
print(df_costo)
fig_costo = px.bar(df_costo, x="Responsabile", y="Costo")
gantt_plot_costo = plot(fig_costo, output_type="div")
context = {'costo_plot_div': gantt_plot_costo, 'form': form}
return render(request, 'progetti/progetti.html', context)
except:
return render(request, 'progetti/progetti.html', {'form': form})
I'm trying to do a web page using django. Where a user can register and login to the page. But When I try to login the authenticate function returns None even if the entered password and username are correct.
I'm using django version 2.1.2 and Python 3.5
I have tried adding
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
in settings.py
this is the function that I'm using for registration.
def SignUp(request):
countryobj = Country.objects.all()
if request.method == 'POST':
form = CustomUserCreationForm(request.POST or None)
gr=request.POST.get('grade')
if gr == 'Grade':
messages.add_message(request, messages.WARNING, 'Select Any Grade')
return render(request, 'authentication/registration.html', {'form': form, 'countries': countryobj})
if form.is_valid():
print("hihihih")
user = form.save()
user.refresh_from_db()
username= request.POST.get('username')
user.password=form.cleaned_data.get('password1')
user.student.birthdate = form.cleaned_data.get('birthdate')
user.student.school_name = form.cleaned_data.get('school_name')
user.student.individual = form.cleaned_data.get('individual')
user.student.school_address = form.cleaned_data.get('school_address')
user.student.country = form.cleaned_data.get('country')
user.student.state = form.cleaned_data.get('state')
user.student.communication_address = form.cleaned_data.get('communication_address')
user.student.c_country = form.cleaned_data.get('c_country')
user.student.c_state = form.cleaned_data.get('c_state')
user.student.grade = form.cleaned_data.get('grade')
user.student.cost = form.cleaned_data.get('cost')
user.student.total = form.cleaned_data.get('total')
user.student.type_user = form.cleaned_data.get('type_user')
user.student.currency=form.cleaned_data.get('currency_code')
user.save()
subject = 'Registration Successfull'
message = 'You have successfully completed registration....'+'\n'+'Username:' +user.username+'\n'+ 'Password:' +user.password
email_from = settings.EMAIL_HOST_USER
recipient_list = [user.email]
send_mail(subject, message, email_from, recipient_list)
messages.add_message(request, messages.SUCCESS, 'Registration Successfull .. Check E-mail for credentials')
return redirect('login')
else:
form = CustomUserCreationForm()
return render(request, 'authentication/registration.html', {'form': form,'countries':countryobj})
else:
form = CustomUserCreationForm()
print("lalala")
# return render(request, 'authentication/registration.html')
print(countryobj)
return render(request, 'authentication/registration.html',{'form':form,'countries':countryobj})
This is the function that i use for login
class getLogin(View):
def get(self, request):
if request.user.is_authenticated:
return render(request, "authentication/signin.html")
else:
return render(request,"authentication/signin.html")
def post(self, request):
user = request.POST.get('user')
password = request.POST.get('pass')
usernamelog = User.objects.get(username=user)
auth = authenticate(username=usernamelog, password=password)
print("auth",auth)
if auth:
request.session['user']=auth.id
request.session['grade']=auth.student.grade
print("re",request.session['user'])
print("ath",auth.username)
request.session['username']=auth.username
print("usr", request.session['username'])
request.session['super']=auth.is_superuser
print("ddd",auth.student.grade)
# request.session['auth'] = auth.is_superuser
if auth.is_superuser:
return render(request,"app/admin.html")
else:
student_id=request.session['user']
grade = request.session['grade']
ex = Exam.objects.filter(level=grade)
code = Code.objects.filter(student_id=student_id)
return render(request, "app/student.html", {'link': ex, 'code': code,'profile':student_id})
else:
messages.add_message(request, messages.ERROR, 'Username or password mismatch')
return redirect('login')
I'm not able to authenticate the user even the given username and password are correct
First of all, as Daniel Roseman pointed out, you are overwriting the correctly saved user object with unhashed password. If you want to save the Student model, the you should call user.student.save() instead of user.save().
def SignUp(request):
countryobj = Country.objects.all()
if request.method == 'POST':
form = CustomUserCreationForm(request.POST or None)
gr=request.POST.get('grade')
if gr == 'Grade':
messages.add_message(request, messages.WARNING, 'Select Any Grade')
return render(request, 'authentication/registration.html', {'form': form, 'countries': countryobj})
if form.is_valid():
print("hihihih")
user = form.save()
user.student.birthdate = form.cleaned_data.get('birthdate')
user.student.school_name = form.cleaned_data.get('school_name')
user.student.individual = form.cleaned_data.get('individual')
user.student.school_address = form.cleaned_data.get('school_address')
user.student.country = form.cleaned_data.get('country')
user.student.state = form.cleaned_data.get('state')
user.student.communication_address = form.cleaned_data.get('communication_address')
user.student.c_country = form.cleaned_data.get('c_country')
user.student.c_state = form.cleaned_data.get('c_state')
user.student.grade = form.cleaned_data.get('grade')
user.student.cost = form.cleaned_data.get('cost')
user.student.total = form.cleaned_data.get('total')
user.student.type_user = form.cleaned_data.get('type_user')
user.student.currency=form.cleaned_data.get('currency_code')
user.student.save() # this will save the Student data
subject = 'Registration Successfull'
message = 'You have successfully completed registration....'+'\n'+'Username:' +user.username+'\n'+ 'Password:' +user.password
email_from = settings.EMAIL_HOST_USER
recipient_list = [user.email]
send_mail(subject, message, email_from, recipient_list)
messages.add_message(request, messages.SUCCESS, 'Registration Successfull .. Check E-mail for credentials')
return redirect('login')
else:
form = CustomUserCreationForm()
return render(request, 'authentication/registration.html', {'form': form,'countries':countryobj})
else:
form = CustomUserCreationForm()
print("lalala")
# return render(request, 'authentication/registration.html')
print(countryobj)
return render(request, 'authentication/registration.html',{'form':form,'countries':countryobj})
I'm getting an error
local variable 'form1' referenced before assignment
This is my views.py and I'm unable to figure this out. I am new to Django so can anyone help me with providing a solution and explaining what I am doing wrong.
def getview(request):
formObject = form_input()
formObject.orign = None
formObject.destinations = None
formObject.timeWindow = None
if request.method == 'POST':
formData = ro_input_form(request.POST)
if formData.is_valid():
formObject.orign = request.POST.get('orign')
formObject.destinations = request.POST.get('destinations')
formObject.timeWindow = request.POST.get('timeWindow')
formObject.save()
return HttpResponse(status=200)
else:
form1 = ro_input_form() ## this should be forminput
return render(request, 'inputform.html', {'form1': form1})
This is my models.py:
class form_input(models.Model):
orign = models.TextField(max_length=245,null=True,default='No data')
destinations = models.TextField(max_length=255,null=True,default='No data')
timeWindow = models.DateField(max_length=255,null=True,default='No data')
This is my forms.py
class ro_input_form(forms.ModelForm):
class Meta:
model = form_input
fields = ['orign',
'destinations',
'timeWindow',
]
The problem is that you have passed the form as form1 as a context in your line:
return render(request, 'inputform.html', {'form1': form1})
But missed to declare the form with name form1 inside your if request.method == 'POST': block. The solution can be either replace:
formData = ro_input_form(request.POST)
as
form1 = ro_input_form(request.POST)
and other places where formData is specified.
Else replace:
else:
form1 = ro_input_form() ## this should be forminput
return render(request, 'inputform.html', {'form1': form1})
As:
else:
formData = ro_input_form() ## this should be forminput
return render(request, 'inputform.html', {'form1': formData})
This causes consistency in the form names.
Edit: Trying to fix data not being saved error.
views.py
def getview(request):
if request.method == 'POST':
form1 = ro_input_form(request.POST)
if form1.is_valid():
form1.save()
return HttpResponse(status=200)
else:
form1 = ro_input_form() ## this should be forminput
return render(request, 'inputform.html', {'form1': form1})
Recommendation:
As you are using all the fields of your model while declaring the form ro_input_form, you can just declare the fields in your form as:
fields = '__all__'
instead of
fields = ['orign',
'destinations',
'timeWindow',
]
This is just for easiness. But if you want only specific fields then specifying the fields individually is fine.
you are passing the form1 in html while it's not declared before so you have to declare it before.
You might like to declare form1 at the starting of view and change your form name as form1:
def getview(request):
formObject = form_input()
formObject.orign = None
formObject.destinations = None
formObject.timeWindow = None
form1 = ro_input_form(request.POST)
if request.method == 'POST':
form1 = ro_input_form(request.POST)
if form1.is_valid():
form1.save()
return HttpResponse(status=200)
else:
form1 = ro_input_form() ## this should be forminput
return render(request, 'inputform.html', {'form1': form1})
I need get data from my form and treat them
def parsurl(request):
if request.method == 'POST':
form = DomainForm(request.POST)
context = { 'form': form, }
if form.is_valid():
r = form.cleaned_data.get('url_text')
masall =parser_d(r)
for mas1 in masall:
try:
Events.objects.create(events_title=mas1[1], events_text = mas1[2],events_img = mas1[0], events_is_pars=1, events_seourl = "132")
except:
print ("lololo")
else:
form = DomainForm()
return render_to_response(request, 'form.html', context)
Exception Value:
local variable 'context' referenced before assignment
You have defined context in the if request.method == 'POST' branch, but not in the else branch. Therefore you get an error for GET requests.
You could fix it by moving the line outside of the if statement as follows:
if request.method == 'POST':
...
else:
...
context = {'form': form}
I am working for a view in django, I am currently working on a model form: I check if student is already created, if it is created I will just update info for that student and I add entry to certain event if necessary; if not I create a student and add entry to event.
The webpage works fine in the case where I create a new student which is in except for the first try, but when I try to get student that already exists the page gives me error of didn't return an HttpResponse object. Can you help me please?
def reserve(request, event_id):
event = get_object_or_404(Event, pk=event_id)
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
try:
student = Student.objects.filter(UID=form.cleaned_data['UID'])
#student.first_name=form.cleaned_data['first_name']
#student.last_name=form.cleaned_data['last_name']
msg = 'Student found, added to reserve for this event!'
except Student.DoesNotExist:
student = Student.objects.create(UID=form.cleaned_data['UID'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'])
msg = 'Contact created, reserve successful!'
obj, created = Reservetoevent.objects.get_or_create(m_event=event, m_student = student)
return render(request, 'events/reserve.html', {
'form': form,
'event': event,
'msg': msg,
})
else:
form = StudentForm()
return render(request, 'events/reserve.html', {
'form': form,
'event': event,
})
Your form.is_valid(): is false. Because the last return you have on there is in the else (meaning the request.method == "GET"), there is no response.
Move your last return to the left. And that should fix it. But it won't fix the reason your form is not valid.
def reserve(request, event_id):
event = get_object_or_404(Event, pk=event_id)
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
try:
student = Student.objects.filter(UID=form.cleaned_data['UID'])
#student.first_name=form.cleaned_data['first_name']
#student.last_name=form.cleaned_data['last_name']
msg = 'Student found, added to reserve for this event!'
except Student.DoesNotExist:
student = Student.objects.create(UID=form.cleaned_data['UID'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'])
msg = 'Contact created, reserve successful!'
obj, created = Reservetoevent.objects.get_or_create(m_event=event, m_student = student)
return render(request, 'events/reserve.html', {
'form': form,
'event': event,
'msg': msg,
})
else:
form = StudentForm()
return render(request, 'events/reserve.html', {
'form': form,
'event': event,
})