def add(request): errors = Book.objects.validate_book(request.POST) if len(errors): for key, value in errors.items(): messages.errors(request, value) return redirect('/books') else: if len(request.POST['author']): author = Author.objects.create(author = request.POST['author']) else: author = Author.objects.get(id = request.POST['author_id']) book = Book.objects.create( title = request.POST['title'], author = author, ) Review.objects.create( review = request.POST['review'], rating = request.POST['rating'], book = book, reviewer = User.objects.get(id = request.session['id']) ) messages.success(request, "New book and review added") return redirect('/books')
def feed(request): if request.method == "POST": print("yes pressed it is") form = FeedForm(request.POST) if form.is_valid(): name = form.cleaned_data["fname"] lname = form.cleaned_data["flname"] email = form.cleaned_data["fmail"] feedback = form.cleaned_data["fmsg"] if len(feedback) != 0: print(feedback) try: user_db.feed.insert({ "name": name, "mail": email, "lname": lname, "msg": feedback }) except: messages.errors(request, "Error occured.Please try again later") return HttpResponseRedirect("/feed") else: messages.success(request, "Thanks for your feedback !!!") return HttpResponseRedirect("/feed") else: messages.success(request, "Error occured.Empty Feedback") return HttpResponseRedirect("/feed") else: form = FeedForm() return render(request, "contact.html")
def get_imported_source_account(): unpaid_sources = AccountType.objects.get(name=names.UNPAID_ACCOUNT_TYPE) sources = unpaid_sources.accounts.all() if not sources.exists(): messages.errors("Carteira não configurada") raise ImproperlyConfigured( "You need to define some 'unpaid source' accounts") return sources[0]
def login(request): print(request.POST) err = LoginManager.objects.basic_validate(request.POST) print(err) if err: for key, value in err.items(): print('key:', key, 'value:', value) messages.errors(request, value) return redirect('/')
def add_blog(request): blog_text = request.POST['blog_text'] errors = Blog.objects.validate_blog(blog_text) if len(errors) > 0: for key, val in errors.items(): messages.errors(request, val) return redirect('/blog') user = User.objects.get(id=request.session['loginID']) Blog.objects.create(text=blog_text, user=user) all_blogs = Blog.objects.all() context = {"all_blogs": all_blogs} return render(request, 'blog.html', context)
def dashboard(request): if 'user' not in request.session: messages.errors(request, "You must be logged in") return redirect('/') today = datetime.date.today() this_user = User.objects.get(id=request.session['id']) context = { "today_event": this_user.join_events.filter(date=today), "time": strftime("%m-%d-%Y", localtime()), "events": Event.objects.all(), "user": this_user } return render(request, 'dashboard.html', context)
def shutc(request): db_exist= user_db.store_details.find({"_id":request.session["_id"]}) if db_exist is None: messages.errors("Register Your Store First") return HttpResponseRedirect('/login') user_db.store_details.update_one( {"_id": request.session["_id"]}, { "$set": {'status':'Closed' } },upsert=True ) return HttpResponseRedirect('/')
def upload_monthly_data(request,action): if action=='clean': df=request.session['df'] df=clean_monthly_file(df) if (type(df).__name__)=='DataFrame': action='import' df=df.to_dict('dict') request.session['dicto']=df return redirect('upload_monthly_data', action) else: e=str(df) error='UPLOAD FAILED DUE TO WRONG FILE FORMAT. PLEASE CHECK THE FILE AND TRY AGAIN. ERROR KEYWORD:'+e messages.error(error) return redirect('import_monthly_file') if action =='import': listo=request.session['dicto'] rows=len(listo['imei']) ob=[] file_name=request.session['file_name'] for i in range(0,rows): i=str(i) try: file_name=request.session['file_name'] ob.append(Monthly(file_name=file_name,location_id=listo['location_id'][i],location_name=listo['location_name'][i],activity_date=clean_date(listo['activity_date'][i]),imei=listo['imei'][i],ctn=listo['ctn'][i],qualifying_activity_type=listo['qualifying_activity_type'][i],product_sku=listo['product_sku'][i],device_name=listo['device_name'][i],promotion_name=listo['promotion_name'][i],promotion_start_date=clean_date(listo['promotion_start_date'][i]),promotion_end_date=clean_date(listo['promotion_end_date'][i]),promotion_category=listo['promotion_category'][i],promotion_sale_price=listo['promotion_sale_price'][i],imm_purchase_price=listo['imm_purchase_price'][i],credit_amount=listo['credit_amount'][i],payment_date=clean_date(listo['payment_date'][i]),ship_date=clean_date(listo['ship_date'][i]),imm_invoice_number=listo['imm_invoice_number'][i],reason=listo['reason'][i])) except ValidationError: continue try: with transaction.atomic(): Monthly.objects.bulk_create(ob) except Exception as e: errors='Errors'+str(e) messages.errors(request,errors) return redirect('import_monthly_file') else: i=ImportHistory(file_type='MonthlyTrailingFile',file_name=file_name,count=rows,remarks='Successful') i.save() messages.success(request, 'File Imported Successfully successful') return redirect('/admin/app/monthly')
def pay_now(request, purpose): if request.method == 'POST': if 'Donate' in purpose: form = DonateForm(request.POST) if 'Goodie' in purpose: form = GoodiesForm(request.POST) if form.is_valid(): form.save(commit=False) form.reqId = CHANNEL_ID + str( display.value(datetime.now().strftime('%Y%m%d%H%M%S'))[0:20]) obj = form.save() data = get_final_data(request, obj, purpose) else: messages.errors(request, 'Invalid Form') return render(request, 'payment_status.html', data)
def save_model(self, request, obj, form, change): current_project = obj if form.is_valid(): current_project = Project(name=obj.name, email=obj.email, telephone_land = obj.telephone_land, telephone_cell = obj.telephone_cell, website = obj.website) current_project.save() param = "" if request.GET.has_key("learn_session_id"): param = "&learn_session_id=%s" % (current_session.id) messages.info(request, "/cooper/public_form/human_proxy/?human_id=%s%s" % (current_project.id, param)) return HttpResponseRedirect( "/cooper/public_form/human_proxy/?human_id=%s%s" % (current_project.id, param)) else: messages.errors(request, form.errors) return HttpResponseRedirect( "/cooper/public_form/human_proxy/?human_id=%s%s" % (current_project.id, param))
def edit(request): if request.method == 'POST': user_form = UserEditForm(instance=request.user, data=request.POST) profile_form = ProfileEditForm(instance=request.user.profile, data=request.POST, files=request.FILES) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, 'Profile updated successfully') else: messages.errors(request, 'Error updating your profile') else: user_form = UserEditForm(instance=request.user) profile_form = ProfileEditForm(instance=request.user.profile) return render(request, 'account/edit.html', {'user_form': user_form, 'profile_form': profile_form})
def profile(request): """ Display the user's profile. """ profile = get_object_or_404(UserProfile, user=request.user) if request.method == 'POST': form = UserProfileForm(request.POST, instance=profile) if form.is_valid(): form.save() messages.success(request, 'Profile updated successfully') else: messages.errors(request, 'Update failed. please ensure the form is valid.') else: form = UserProfileForm(instance=profile) orders = profile.orders.all() template = 'profiles/profile.html' context = {'form': form, 'orders': orders, 'on_profile_page': True} return render(request, template, context)
def upload_question(request,quiz_slug=None): ''' View for uploading the question ''' quiz = get_object_or_404(Quiz,slug=quiz_slug) template_name = 'question/upload_question.html' if request.method == 'POST': csvfile = request.FILES['questionfile'] # gets the input field name print(csvfile.name) # prints the csv file name if not csvfile.name.endswith('.csv'): print("Invalid!!") # prints invalid at the console messages.errors(request, "CSV file format not supported") return(HttpResponseRedirect('quiz:fail')) file_data = csvfile.read().decode("utf-8") # reads the csv file # print(file_data) lines = file_data.split("\n") # split using the delimiter data_dict = {} # empty dictionary to store the csv data print(len(lines)) for line in lines: print(line) fields = line.split(',') # print(fields) data_dict = { 'question_text':fields[0], } # print(len(data_dict)) if data_dict != '': question = Question.objects.create( quiz=quiz, text=data_dict['question_text'] ) # question.quiz = quiz # question.date_created = timezone.now() # question.date_upadated= timezone.now() # question.save() messages.success(request, "File Successfully Uploaded") # return HttpResponseRedirect(reverse('quiz:upload_successful')) else: messages.errors(request, "File not uploaded") context = {'quiz':quiz} return render(request, template_name, context)
def create_exercise(request): if request.method == "POST": create_form = ExerciseForm(request.POST) # check if created form have valid values if create_form.is_valid(): create_form.save() messages.success( request, f"{create_form.cleaned_data['title']} has been created!") return redirect(reverse(show_exercise)) else: # if does not have any valid values and re-render the form messages.errors( request, f"{create_form.cleaned_data['title']} has not been created!") return render(request, "products/create_exercise.template.html", {"form": create_form}) else: create_form = ExerciseForm() return render(request, "products/create_exercise.template.html", {"form": create_form})
def add_product(request): """ Add a product to the store """ if not request.user.is_superuser: messages.error(request, 'Sorry, admission denied') return redirect(reverse('home')) if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): product = form.save() messages.success(request, 'Successfully added product') return redirect(reverse('product_detail', args=[product.id])) else: messages.errors(request, 'Failed to add product. Ensure the form is valid') else: form = ProductForm() template = 'products/add_product.html' context = { 'form': form, } return render(request, template, context)
def upload_teachers(request): ''' View for uploading Teachers ''' # quiz = get_object_or_404(Quiz,slug=quiz_slug) template_name = 'teachers/profile/upload.html' if request.method == 'POST': csvfile = request.FILES['teacherprofile'] # gets the input field name print(csvfile.name) # prints the csv file name if not csvfile.name.endswith('.csv'): print("Invalid!!") # prints invalid at the console messages.errors(request, "CSV file format not supported") return (HttpResponseRedirect('teacherprofile:fail')) file_data = csvfile.read().decode("utf-8") # reads the csv file # print(file_data) lines = file_data.split("\n") # split using the delimiter data_dict = {} # empty dictionary to store the csv data print(len(lines)) for line in lines: print(line) fields = line.split(',') # print(fields) user_dict = { 'email': fields[0], 'password': fields[1], # 'password2':fields[2], } teacher_profile_dict = { 'first_name': fields[2], 'other_name': fields[3], 'last_name': fields[4], 'gender': fields[5], 'mugshot': fields[6], 'teacher_class': fields[7], 'date_of_birth': fields[9], 'date_admitted': fields[9], 'address': fields[10] } # print(len(data_dict)) if data_dict != '': user = User.objects.create_user(email=user_dict['email'], password=user_dict['password']) user.staff = True user.save() # save the user user.groups.add(Group.objects.get(name='Instructors')) student_profile = TeacherProfile.objects.create( user=user, first_name=teacher_profile_dict['first_name'], other_name=teacher_profile_dict['other_name'], last_name=teacher_profile_dict['last_name'], mugshot=teacher_profile_dict['mugshot'], gender=teacher_profile_dict['gender'], teacher_class=teacher_profile_dict['teacher_class'], date_of_birth=teacher_profile_dict['date_of_birth'], date_admitted=teacher_profile_dict['date_admitted'], address=teacher_profile_dict['address']) messages.success(request, "File Successfully Uploaded") else: messages.errors(request, "File not uploaded") context = {} return render(request, template_name, context)