views.py
getting something else
in output instead of values present in it
I am trying but not gating answers
please provide me some suggestions
I think so error occurs in :(instance=Task)
from django.shortcuts import render
from django.http import *
from MYapp.models import *
from .form import *
def venue(request):
venue_list = Task.objects.all()
return render(request,'MYapp/venue.html',{'venue_list': venue_list})
def navebar(request):
return render(request,'MYapp/navebar.html')
def db(request,db_id):
venues = Task.objects.get(pk=db_id)
return render(request,'MYapp/db.html',{'venues': venues})
def search(request):
if request.method =="POST":
searched = request.POST.get('searched', False)
Tasks =Task.objects.filter( firstname__contains = searched)
return render(request,'MYapp/search.html',{'searched':searched, 'Tasks':Tasks})
else:
return render(request,'MYapp/search.html',{})
def update(request,db_id):
venues = Task.objects.get(pk=db_id)
form = TaskForm(request.POST or None, instance=Task)
return render(request,'MYapp/update.html',{'venues': venues,'form':form})
assigning a variable instead of class
def update(request,db_id):
venues = Task.objects.get(pk=db_id)
form = TaskForm(request.POST or None, instance=Task)
return render(request,'MYapp/update.html',{'venues':
venues,'form':form})
do this
def update(request,db_id):
venues = Task.objects.get(pk=db_id)
form = TaskForm(request.POST or None, instance=venues )
return render(request,'MYapp/update.html',{'venues':
venues,'form':form})
Related
here is my code views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseForbidden
from quiz.forms import NewQuizForm, NewQuestionForm
from quiz.models import Answer, Question, Quizzes, Attempter, Attempt
from courses.models import Module
from completion.models import Completion
# Create your views here.
def NewQuiz(request, course_id, module_id):
user = request.user
module = get_object_or_404(Module, id=module_id)
if request.method == 'POST':
form = NewQuizForm(request.POST)
if form.is_valid():
title = form.cleaned_data.get('title')
description = form.cleaned_data.get('description')
due = form.cleaned_data.get('due')
allowed_attempts = form.cleaned_data.get('allowed_attempts')
time_limit_mins = form.cleaned_data.get('time_limit_mins')
quiz = Quizzes.objects.create(user=user, title=title, description=description, due=due, allowed_attempts=allowed_attempts, time_limit_mins=time_limit_mins)
module.quizzes.add(quiz)
module.save()
return redirect('new-question', course_id=course_id, module_id=module_id, quiz_id=quiz.id)
else:
form = NewQuizForm()
context = {
'form': form,
}
return render(request, 'quiz/newquiz.html', context)
def NewQuestion(request, course_id, module_id, quiz_id):
user = request.user
quiz = get_object_or_404(Quizzes, id=quiz_id)
if request.method == 'POST':
form = NewQuestionForm(request.POST)
if form.is_valid():
question_text = form.cleaned_data.get('question_text')
points = form.cleaned_data.get('points')
answer_text = request.POST.getlist('answer_text')
is_correct = request.POST.getlist('is_correct')
question = Question.objects.create(question_text=question_text, user=user, points=points)
for a, c in zip(answer_text, is_correct):
answer = Answer.objects.create(answer_text=a, is_correct=c, user=user)
question.answers.add(answer)
question.save()
quiz.questions.add(question)
quiz.save()
return redirect('new-question', course_id=course_id, module_id=module_id, quiz_id=quiz.id)
else:
form = NewQuestionForm()
context = {
'form': form,
}
return render(request, 'quiz/newquestion.html', context)
def QuizDetail(request, course_id, module_id, quiz_id):
user = request.user
quiz = get_object_or_404(Quizzes, id=quiz_id)
my_attempts = Attempter.objects.filter(quiz=quiz, user=user)
context = {
'quiz': quiz,
'my_attempts': my_attempts,
'course_id': course_id,
'module_id': module_id,
}
return render(request, 'quiz/quizdetail.html', context)
and quiz/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('<course_id>/<module_id>/quiz/newquiz', views.NewQuiz, name='new-quiz'),
path('<course_id>/modules/<module_id>/quiz/<quiz_id>/newquestion', views.NewQuestion, name='new-question'),
path('<course_id>/modules/<module_id>/quiz/<quiz_id>/', views.QuizDetail, name='quiz-detail'),
path('<course_id>/modules/<module_id>/quiz/<quiz_id>/take', views.TakeQuiz, name='take-quiz'),
path('<course_id>/modules/<module_id>/quiz/<quiz_id>/take/submit', views.SubmitAttempt, name='submit-quiz'),
path('<course_id>/modules/<module_id>/quiz/<quiz_id>/<attempt_id>/results', views.AttemptDetail, name='attempt-detail'),
]
and template
<i class="material-icons"></i>Add new quiz
in the project urls.py
path('quiz/',include('quiz.urls')),
it says like this "Reverse for 'new-quiz' with arguments '(11, '')' not found. 1 pattern(s) tried: ['course/(?P<course_id>[^/]+)/(?P<module_id>[^/]+)/quiz/newquiz$']"which means it detect the first argument but not the others why???
Use single quotes in your template, so 'new-quiz' instead of "new-quiz":
<i class="material-icons"></i>Add new quiz
I want to have one abstract function for all my tablelists (one for each model) and (one delete_item) function in view.
I don't know how to make the delete (column in this table) and pass the model to the delete_item function in the view
Tables.py
############ Abstract Table
class abs_Table(tables.Table):
SN = tables.Column(empty_values=(), orderable=False)
delete = tables.LinkColumn('delete_item', args=[A('pk'), ?????Model???], attrs={
'a': {'class': 'btn btn-small btn-dark'}
# })
def __init__(self, *args, **kwargs):
super(abs_Table, self).__init__(*args, **kwargs)
self.counter = itertools.count(1)
def render_SN(self, record):
pg = getattr(self, 'paginator', None)
if pg:
v = next(self.counter)
return v + self.paginator.per_page * (self.page.number-1)
else:
return next(self.counter)
class Meta:
model = None
fields = [ 'SN', 'id', 'delete', ]
attrs = {"class": "table-striped table-bordered", 'width': '100%'}
empty_text = "There are no Records matching the search criteria..."
Then for model Table
Tables.py
class ModelTable(abs_Table):
class Meta(abs_Table.Meta):
model = modelname
fields = abs_Table.Meta.fields+[selected_model_fields]
Views.py
def delete_item(request, pk, delmodel):
obj = get_object_or_404(delmodel, id=pk)
if request.method == "POST":
obj.delete()
return redirect("../")
else:
pass
context = {
'object': obj
}
return render(request, '/delete_confirmation.html', context)
For the Views part. It works for me after passing the model as string and then using apps.get_model to change it into a model.
views.py`
from django.apps import apps
def delete_item(request, pk, delmodel):
DeleteModel = apps.get_model("Myapp", delmodel)
obj = get_object_or_404(DeleteModel, id=pk)
if request.method == "POST":
obj.delete()
return redirect("../")
else:
pass
context = {
'object': obj
}
return render(request, '/delete_confirmation.html', context)
Still the confirmation is not handled correctly and the delete column in tables need to be improved.
Uploading a file is only allowed once the form is submitted. The upload url must not be accessible otherwise.
After the user logs in, the upload url is directly accessed. How can i restrict this? This will create multiple entries of file upload for the same form
models.py
class uploadmeta(models.Model):
path = models.ForeignKey(Mdform, verbose_name="ID", on_delete=models.PROTECT)
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
datafile = models.FileField(upload_to=get_upload_folder, verbose_name="Dataset", validators=[validate_file_extension])
def get_absolute_url(self):
return reverse('file_list', kwargs={'pk': self.pk})
views.py
if request.user.is_authenticated:
if request.method == 'POST':
form = uploadmetaform(request.POST, request.FILES)
if form.is_valid():
path = form.cleaned_data['path']
if uploadmeta.objects.filter(path=path).exists():
user = form.cleaned_data['user']
datafile = form.cleaned_data['datafile']
context = {
'path': path,
'user': user,
'datafile': datafile
}
template = loader.get_template('nameexists.html')
return HttpResponse(template.render(context, request))
else:
user = form.cleaned_data['user']
datafile = form.cleaned_data['datafile']
path = dict(form.fields['path'].path)[path]
print(path)
b = form(path=path, user=user, datafile=datafile)
b.save()
context = {
'path': path,
'user': user,
'datafile': datafile
}
template = loader.get_template('thankyou.html')
return HttpResponse(template.render(context, request))
else:
form = uploadmetaform()
return render(request, 'uploaddata.html', {'form': form})
else:
return render(request, 'home.html')```
from django.shortcuts import render
from basicform.forms import BasicForm
from django.template import loader
from django.http import HttpResponse
from basicform.choices import *
from basicform.models import BasicFormModel
def responseform(request):
if request.method == 'POST':
basicForm = BasicForm(request.POST)
if basicForm.is_valid():
name = basicForm.cleaned_data['name']
if BasicFormModel.objects.filter(name=name).exists():
favourite_color = basicForm.cleaned_data['favourite_color']
choices = basicForm.cleaned_data['choices']
context = {
'name': name,
'favourite_color': favourite_color,
'choices': choices
}
template = loader.get_template('nameexists.html')
return HttpResponse(template.render(context, request))
else:
favourite_color = basicForm.cleaned_data['favourite_color']
choices = basicForm.cleaned_data['choices']
print("cleanded choices="+choices)
choices = dict(basicForm.fields['choices'].choices)[choices]
print(choices)
b = BasicFormModel(name=name, favourite_color=favourite_color, choices=choices)
b.save()
context = {
'name': name,
'favourite_color': favourite_color,
'choices': choices
}
template = loader.get_template('thankyou.html')
return HttpResponse(template.render(context, request))
else:
form = BasicForm()
return render(request, 'responseform.html', {'form':form});
**
This is the ValueError it is returning. The view
poster.views.post_tweet didn't return an HttpResponse object
**
poster/views.py
from django.http import HttpResponseRedirect
def post_tweet(request, tweet_id=None):
tweet = None
if tweet_id:
tweet = get_object_or_404(Tweet, id=tweet_id)
if request.method == 'POST':
form = TweetForm(request.POST, instance=tweet)
if form.is_valid():
new_tweet = form.save(commit=False)
new_tweet.state = 'pending'
new_tweet.save()
send_review_email(tweet)
return HttpResponseRedirect('/post/thankyou/')
else:
form = TweetForm(instance=tweet)
return render(request,'post_tweet.html',{'form': form})
def thank_you(request):
tweets_in_queue = Tweet.objects.filter(
state='pending').aggregate(Count('id')).values()[0]
return render(request, 'thank_you.html',
{'tweets_in_queue': tweets_in_queue})
myproject/urls.py
url(r'^post/', include('poster.urls'))
poster/urls.py
url(r'^thankyou', 'thank_you'),
If it's a POST, but the form isn't valid, you're not returning anything. If you move the return render(request,'post_tweet.html',{'form': form}) left by one indentation level it should all work.
I try to use flask login in may app:
My controller:
#app.route("/process_log", methods=['POST'])
def process_login():
filled_form = LoginForm(request.form)
if filled_form.validate():
phone = filled_form.phone.data
password = filled_form.password.data
if User.phone_exists(phone) and User.pass_match(phone, password):
user = User.get_by_phone(phone)
login_user(user.get_id)
return redirect(url_for("index"))
else:
return render_template("login.html", form = filled_form, error = u"Не верный логин или пароль")
else:
return render_template("home.html", form = filled_form)
and I have some class with defined functions which required for API of flask login
My User class:
from pymongo import MongoClient
from bson.objectid import ObjectId
class User():
client = MongoClient()
db = client['test']
col = db['user']
user_id = None
def __init__(self, dic):
self.dic = dic
def is_authenticated():
return True
def is_anonymous():
return False
def is_active():
return True
def get_id(self):
return unicode(str(self.user_id))
def save(self):
self.user_id = self.col.insert(self.dic)
print "Debug:" + str(self.user_id)
#staticmethod
def _get_col():
client = MongoClient()
db = client['test']
col = db['user']
return col
#staticmethod
def phone_exists(phone):
col = User._get_col()
if col.find_one({'phone': phone}) != None:
return True
else:
return False
#staticmethod
def pass_match(phone, password):
col = User._get_col()
if col.find_one({'phone': phone})['password'] == password:
return True
else:
return False
#staticmethod
def get(userid):
col = User._get_col()
return col.find_one({'_id':userid})
#staticmethod
def get_by_phone(phone):
col = User._get_col()
dic = col.find_one({'phone': phone})
print dic['password']
return User(dic)
As you see function is_active is defined(Note:I also tried to pass refference with self)
But I still have this error AttributeError: 'function' object has no attribute 'is_active'
I am sorry for too much code here, but it should be pretty straightforward.
Note: I am using mongodb for my project.
Please help me to find my error. Thank you too much
One more thing:
Should I provide login_user(....) with Id or with my user object?
You must sent to login_user User instance (not id), see: https://github.com/maxcountryman/flask-login/blob/master/flask_login.py#L576.
So next code must work:
user = User.get_by_phone(phone)
login_user(user)