Пример #1
0
from django.db import models
from django.forms import ModelForm
from django.urls import reverse
from django_summernote.widgets import SummernoteWidget
from django.core.files.storage import FileSystemStorage
from django.forms.widgets import HiddenInput, Textarea, TextInput, Select

fs = FileSystemStorage(location='media/')


class Model(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True


class Profile(Model):
    display_name = models.CharField(max_length=255)
    caption = models.CharField(max_length=30, default='', blank=True)
    desc = models.TextField(blank=True)

    class Meta:
        ordering = ['display_name']

    def __str__(self):
        return self.display_name


class Character(Profile):
Пример #2
0
from django.db import models
from django.core.files import File
from django.core.files.storage import FileSystemStorage
from datetime import datetime
import urllib
import os

imagefs = FileSystemStorage(location='/b7_1/exports/leica/images')


class PI(models.Model):
    """ Store PI name.  Names must be entered manually
    """
    sunetid = models.CharField('PI sunetid',
                               max_length=32,
                               primary_key=True,
                               db_index=True)
    first = models.CharField('first name', max_length=32)
    last = models.CharField('surname', max_length=32, null=True, blank=True)
    fullname = models.CharField('Full name',
                                max_length=65,
                                null=True,
                                blank=True)
    aliases = models.CharField('aliases',
                               max_length=128,
                               null=True,
                               blank=True)

    def save(self):
        self.fullname = self.first + " " + self.last
        self.aliases = self.first + " " + self.last
Пример #3
0
 def setUp(self):
     self.umask = 0o027
     self.old_umask = os.umask(self.umask)
     self.storage_dir = tempfile.mkdtemp()
     self.storage = FileSystemStorage(self.storage_dir)
Пример #4
0
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.core.validators import RegexValidator
from datetime import datetime
from django.conf import settings
from django.core.files.storage import FileSystemStorage
docs_storage = FileSystemStorage(location=settings.DOCS_STORAGE_ROOT)


def driving_files():
    a = str(datetime.now().strftime("%H:%M:%S"))
    return 'uploads/driving_licence/' + 'DL' + '-'.join(a.split(':'))


def pancard_files():
    a = str(datetime.now().strftime("%H:%M:%S"))

    return 'uploads/pancard/' + 'pancard' + '-'.join(a.split(':'))


# Create your models here.
class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    about = models.CharField(max_length=100, default='')
    city = models.CharField(max_length=25, default='')
    phone_regex = RegexValidator(regex=r'^\d{10}$', message= \
        "Phone number must be of 10 digits")
    mobile = models.CharField(validators=[phone_regex],
                              max_length=10,
                              blank=True,
Пример #5
0
 class DummyImageFieldModel(models.Model):
     fs = FileSystemStorage(location=gettempdir())
     image_field = models.ImageField(upload_to="%Y/%m/%d", storage=fs)
Пример #6
0
def edit_student_save(request):
    if request.method != "POST":
        return HttpResponse("<h2>Method Not Allowed</h2>")
    else:
        student_id = request.session.get("student_id")
        if student_id == None:
            return HttpResponseRedirect(reverse("manage_student"))

        form = EditStudentForm(request.POST, request.FILES)
        if form.is_valid():
            first_name = form.cleaned_data["first_name"]
            last_name = form.cleaned_data["last_name"]
            username = form.cleaned_data["username"]
            email = form.cleaned_data["email"]
            address = form.cleaned_data["address"]
            session_year_id = form.cleaned_data["session_year_id"]
            course_id = form.cleaned_data["course"]
            sex = form.cleaned_data["sex"]

            if request.FILES.get('profile_pic', False):
                profile_pic = request.FILES['profile_pic']
                fs = FileSystemStorage()
                filename = fs.save(profile_pic.name, profile_pic)
                profile_pic_url = fs.url(filename)
            else:
                profile_pic_url = None

            try:
                user = CustomUser.objects.get(id=student_id)
                user.first_name = first_name
                user.last_name = last_name
                user.username = username
                user.email = email
                user.save()

                student = Students.objects.get(admin=student_id)
                student.address = address
                session_year = SessionYearModel.object.get(id=session_year_id)
                student.session_year_id = session_year
                student.gender = sex
                course = Courses.objects.get(id=course_id)
                student.course_id = course
                if profile_pic_url != None:
                    student.profile_pic = profile_pic_url
                student.save()
                del request.session['student_id']
                messages.success(request, "Successfully Edited Student")
                return HttpResponseRedirect(
                    reverse("edit_student", kwargs={"student_id": student_id}))
            except:
                messages.error(request, "Failed to Edit Student")
                return HttpResponseRedirect(
                    reverse("edit_student", kwargs={"student_id": student_id}))
        else:
            form = EditStudentForm(request.POST)
            student = Students.objects.get(admin=student_id)
            return render(request, "hod_template/edit_student_template.html", {
                "form": form,
                "id": student_id,
                "username": student.admin.username
            })
Пример #7
0
# -*- coding: utf-8 -*-
import datetime
import tempfile
import shutil

from django.db import models
# Can't import as "forms" due to implementation details in the test suite (the
# current file is called "forms" and is already imported).
from django import forms as django_forms
from django.core.files.storage import FileSystemStorage

temp_storage_location = tempfile.mkdtemp()
temp_storage = FileSystemStorage(location=temp_storage_location)


class BoundaryModel(models.Model):
    positive_integer = models.PositiveIntegerField(null=True, blank=True)


class Defaults(models.Model):
    name = models.CharField(max_length=255, default='class default value')
    def_date = models.DateField(default=datetime.date(1980, 1, 1))
    value = models.IntegerField(default=42)


class ChoiceModel(models.Model):
    """For ModelChoiceField and ModelMultipleChoiceField tests."""
    name = models.CharField(max_length=10)


class ChoiceOptionModel(models.Model):
Пример #8
0
        for child in form.instance.child_set.all():
            if len(child.name.split()) < 2:
                child.name = child.name + ' ' + last_name
                child.save()


class EmptyModelAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        return super().get_queryset(request).filter(pk__gt=1)


class OldSubscriberAdmin(admin.ModelAdmin):
    actions = None


temp_storage = FileSystemStorage(tempfile.mkdtemp())
UPLOAD_TO = os.path.join(temp_storage.location, 'test_upload')


class PictureInline(admin.TabularInline):
    model = Picture
    extra = 1


class GalleryAdmin(admin.ModelAdmin):
    inlines = [PictureInline]


class PictureAdmin(admin.ModelAdmin):
    pass
Пример #9
0
    def post(self, request):
        print("in post man in stddetail")
        Email = request.session['agn_stdmail']
        Sscqual = request.POST.get('Sscqual')
        print("123456")
        print(Sscqual)
        Sscname = request.POST.get('Sscname')
        Sscdate = request.POST.get('Sscdate')
        Sscmarks = request.POST.get('Sscmarks')
        Sscgrading = request.POST.get('Sscgrading')
        SscDoc = request.FILES['SscDoc']

        fs = FileSystemStorage()
        name = fs.save(SscDoc.name, SscDoc)
        url = fs.url(name)
        print(url)
        Intqual = request.POST.get('Intqual')
        Intname = request.POST.get('Intname')
        Intdate = request.POST.get('Intdate')
        Intmarks = request.POST.get('Intmarks')
        Intgrading = request.POST.get('Intgrading')
        IntDoc = request.FILES['IntDoc']

        name1 = fs.save(IntDoc.name, IntDoc)
        url1 = fs.url(name1)
        Uniqual = request.POST.get('Uniqual')
        Uniname = request.POST.get('Uniname')
        Unicname = request.POST.get('Unicname')
        Unidate = request.POST.get('Unidate')
        Unimarks = request.POST.get('Unimarks')
        Unigrading = request.POST.get('Unigrading')
        UniDoc = request.FILES['UniDoc']
        agentid = request.session['agentid']
        agentmail = request.session['Email2']

        name2 = fs.save(UniDoc.name, UniDoc)
        url2 = fs.url(name2)
        stdacd = Stdacd(Email=Email,
                        Sscqual=Sscqual,
                        Sscname=Sscname,
                        Sscdate=Sscdate,
                        Sscmarks=Sscmarks,
                        Sscgrading=Sscgrading,
                        SscDoc=SscDoc,
                        Intqual=Intqual,
                        Intname=Intname,
                        Intdate=Intdate,
                        Intmarks=Intmarks,
                        Intgrading=Intgrading,
                        IntDoc=IntDoc,
                        Uniqual=Uniqual,
                        Uniname=Uniname,
                        Unicname=Unicname,
                        Unidate=Unidate,
                        Unimarks=Unimarks,
                        Unigrading=Unigrading,
                        UniDoc=UniDoc,
                        Agentid=agentid,
                        Agentmail=agentmail)

        stdacd.register()
        value = {
            'Sscqual': Sscqual,
            'Sscname': Sscname,
            'Sscdate': Sscdate,
            'Sscmarks': Sscmarks,
            'Sscgrading': Sscgrading,
            'SscDoc': url,
            'Intqual': Intqual,
            'Intname': Intname,
            'Intdate': Intdate,
            'Intmarks': Intmarks,
            'Intgrading': Intgrading,
            'IntDoc': url1,
            'Uniqual': Uniqual,
            'Uniname': Uniname,
            'Unicname': Unicname,
            'Unidate': Unidate,
            'Unimarks': Unimarks,
            'Unigrading': Unigrading,
            'UniDoc': url2
        }
        data = {'value': value}
        return render(request, 'agent_portal/academic.html', data)
Пример #10
0
 def SaveIcon(user, newIcon):
     
     # data gathering
     
     hret = CU.HttpReturn()
     try:
         user_m = AM.User.objects.get(username=user)
     except AM.User.DoesNotExist:
         hret.results = "User not found."
         hret.status = 501
         return hret
     
     try:
         profile_m = MT.Profile.objects.get(UserFK=user_m)
     except AM.User.DoesNotExist:
         hret.results = "Profile not found."
         hret.status = 501
         return hret
     
     # save parameter file from user to the server's file storage
     # new icon type: django.core.files.uploadedfile.InMemoryUploadedFile
     
     # 1. check if it's an image
     
     import magic
     filetype = magic.from_buffer(newIcon.read())
     newIcon.seek(0)     # reset file cursor
     
     if 'image' not in filetype:
         hret.results = "File is not an image."
         hret.status = 422
         return hret
     
     # 2. reduce size of image to at most 500 pixels per side
     
     
     
     
     # 3. save file at server
     
     from django.core.files.storage import FileSystemStorage
     from django.core.files.base import ContentFile
     import socket
     
     folder = profile_m.HashID[0]
     
     host = socket.gethostname()
     if host.startswith('test') or host.startswith('prod'):
         fsLoc = os.path.join(settings.BASE_DIR, 'app_proj/static/user_icons', folder )
     else:
         fsLoc = os.path.join(settings.BASE_DIR, 'members/static/user_icons', folder )
     
     fs = FileSystemStorage(location=fsLoc)      # requires the absolute path
     
     if profile_m.Icon:
         existingFullPath = os.path.join(fsLoc, profile_m.Icon)
         if os.path.isfile(existingFullPath):
             os.remove(existingFullPath)
     
     fileName = profile_m.HashID + '_icon.jpg'
     fs.save(fileName, ContentFile(newIcon.read()))
     
     profile_m.Icon = fileName
     profile_m.save()
     
     # return succesfull results
     
     records = {
         'message': "User icon saved.",
         'iconFileName': fileName,
     }
     
     hret = CU.HttpReturn()
     hret.results = records
     hret.status = 201
     return hret
Пример #11
0
        was opened.
        """
        def __init__(self, *args, **kwargs):
            self.was_opened = False
            super().__init__(*args, **kwargs)

        def open(self):
            self.was_opened = True
            super().open()

    class TestImageField(ImageField):
        attr_class = TestImageFieldFile

    # Set up a temp directory for file storage.
    temp_storage_dir = tempfile.mkdtemp()
    temp_storage = FileSystemStorage(temp_storage_dir)
    temp_upload_to_dir = os.path.join(temp_storage.location, 'tests')

    class Person(models.Model):
        """
        Model that defines an ImageField with no dimension fields.
        """
        name = models.CharField(max_length=50)
        mugshot = TestImageField(storage=temp_storage, upload_to='tests')

    class AbstractPersonWithHeight(models.Model):
        """
        Abstract model that defines an ImageField with only one dimension field
        to make sure the dimension update is correctly run on concrete subclass
        instance post-initialization.
        """
Пример #12
0
            if len(child.name.split()) < 2:
                child.name = child.name + ' ' + last_name
                child.save()


class EmptyModelAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        return super(EmptyModelAdmin,
                     self).get_queryset(request).filter(pk__gt=1)


class OldSubscriberAdmin(admin.ModelAdmin):
    actions = None


temp_storage = FileSystemStorage(
    tempfile.mkdtemp(dir=os.environ['DJANGO_TEST_TEMP_DIR']))
UPLOAD_TO = os.path.join(temp_storage.location, 'test_upload')


class PictureInline(admin.TabularInline):
    model = Picture
    extra = 1


class GalleryAdmin(admin.ModelAdmin):
    inlines = [PictureInline]


class PictureAdmin(admin.ModelAdmin):
    pass
Пример #13
0
from django.utils.translation import ungettext, ugettext_lazy as _

from forms_builder.forms import EntriesForm
from forms_builder.models import Form, Field, FormEntry, FieldEntry
from forms_builder.settings import CSV_DELIMITER, UPLOAD_ROOT
from forms_builder.settings import USE_SITES, EDITABLE_SLUGS
from forms_builder.utils import now, slugify
from patient_portal.admin import form_creator_admin_site
try:
    import xlwt
    XLWT_INSTALLED = True
    XLWT_DATETIME_STYLE = xlwt.easyxf(num_format_str='MM/DD/YYYY HH:MM:SS')
except ImportError:
    XLWT_INSTALLED = False

fs = FileSystemStorage(location=UPLOAD_ROOT)
form_admin_filter_horizontal = ()
form_admin_fieldsets = [
    (None, {
        "fields": ("title", (
            "status",
            "login_required",
        ), "intro", "button_text", "response")
    }),
]

if EDITABLE_SLUGS:
    form_admin_fieldsets.append((_("Slug"), {
        "fields": ("slug", ),
        "classes": ("collapse", )
    }))
Пример #14
0
    if not person.id:
        l = ldap.initialize('ldap://ldap.uiuc.edu')
        u = l.search_s('ou=people,dc=uiuc,dc=edu', ldap.SCOPE_SUBTREE,
                       'uid=%s' % person.netid)
        try:
            person.ldap_name = u[0][1]['cn'][0]
        except IndexError:
            raise ValueError('Bad Netid', 'Not a valid netid')


class PreResumePerson(ResumePerson):
    number = models.IntegerField()


# Wher to store the resumes
fs = FileSystemStorage(location=settings.RESUME_STORAGE_LOCATION)


def create_resume_file_name(instance, filename):
    return "%s/%s-%s.pdf" % (settings.RESUME_STORAGE_LOCATION,
                             instance.person.netid,
                             os.urandom(16).encode('hex'))


class Resume(models.Model):
    person = models.ForeignKey(ResumePerson, null=True)
    approved = models.BooleanField(default=False)
    resume = ContentTypeRestrictedFileField(upload_to=create_resume_file_name,
                                            storage=fs,
                                            content_types=['application/pdf'],
                                            max_upload_size=1048576)
Пример #15
0
from django.db import models
from django.contrib.auth.models import User
from django.core.files.storage import FileSystemStorage

fs = FileSystemStorage(location='/media/uploads')

# TODO: Need to use Reporter instead of SignUp


class Reporter(models.Model):
    user_name = models.CharField(max_length=120, null=True)
    password = models.CharField(max_length=120, null=True)
    created_at = models.DateTimeField(auto_now_add=True, blank=True)
    email = models.EmailField()
    is_superuser = models.BooleanField(blank=True, default=False)
    user = models.OneToOneField(User, blank=True, null=True)

    def __str__(self):
        return (self.user_name)


class Group(models.Model):
    name = models.CharField(max_length=120)
    members = models.ManyToManyField(Reporter, through='Membership')

    def __str__(self):
        return self.name


class Report(models.Model):
    # See https://docs.djangoproject.com/en/1.8/ref/models/fields/ for explanations of model fields
Пример #16
0
    def post(self, request):
        Email = request.session['agn_stdmail']
        Testeng = request.POST.getlist('Testeng[]')
        Yeareng = request.POST.getlist('Yeareng[]')
        Overallscoreeng = request.POST.getlist('Overallscoreeng[]')
        agentid = request.session['agentid']
        agentmail = request.session['Email2']

        Testad = request.POST.getlist('Testad[]')
        Yearad = request.POST.getlist('Yearad[]')
        Overallscoread = request.POST.getlist('Overallscoread[]')
        fs = FileSystemStorage()
        Uploadeng = request.FILES.getlist('Uploadeng[]')
        print("webfWJEFBJEfliwejhfiWNFLIH")
        print(Testeng)
        print(Yeareng)
        print(Overallscoreeng)
        print(Uploadeng)
        print(Testad)
        print(Yearad)
        print(Overallscoread)
        Uploadad = request.FILES.getlist('Uploadad[]')
        print(Uploadad)
        urleng = []
        urlad = []
        for i in range(0, len(Testeng)):
            testeng = Testeng[i]
            yeareng = Yeareng[i]
            overallscoreeng = Overallscoreeng[i]
            uploadeng = Uploadeng[i]
            name = fs.save(uploadeng.name, uploadeng)
            url = fs.url(name)
            urleng.append(url)
            stdpro = Stdpro(Agentmail=agentmail,
                            Agentid=agentid,
                            Email=Email,
                            Testeng=testeng,
                            Yeareng=yeareng,
                            Overallscoreeng=overallscoreeng,
                            Uploadeng=uploadeng,
                            Urleng=url)
            stdpro.register()

        for i in range(0, len(Testad)):
            testad = Testad[i]
            yearad = Yearad[i]
            overallscoread = Overallscoread[i]
            uploadad = Uploadad[i]
            name = fs.save(uploadad.name, uploadad)
            url = fs.url(name)
            urlad.append(url)
            stdpro1 = Stdpro1(Agentmail=agentmail,
                              Agentid=agentid,
                              Email=Email,
                              Testad=testad,
                              Yearad=yearad,
                              Overallscoread=overallscoread,
                              Uploadad=uploadad,
                              Urlad=url)
            stdpro1.register()
        '''name3=fs.save(Uploadeng.name,Uploadeng)
        url3=fs.url(name3)

        
        name5=fs.save(Uploadad.name,Uploadad)
        url5=fs.url(name5)
        
        print(url3)'''
        '''stdpro=Stdpro(Email=Email,Testeng=Testeng,Yeareng=Yeareng,Overallscoreeng=Overallscoreeng,Uploadeng=Uploadeng,
            Testad=Testad,Yearad=Yearad,Overallscoread=Overallscoread,Uploadad=Uploadad)
        stdpro.register()'''
        value = {
            'Testeng': Testeng,
            'Yeareng': Yeareng,
            'Overallscoreeng': Overallscoreeng,
            'Uploadeng': urleng,
            'Testad': Testad,
            'Yearad': Yearad,
            'Overallscoread': Overallscoread,
            'Uploadad': urlad
        }
        data = {'value': value}
        return render(request, 'agent_portal/Profressional.html')
Пример #17
0
def storage():
    '''Provide a storage that exposes the test templates'''
    root = os.path.join(os.path.dirname(__file__), '..', 'app', 'templates')
    return FileSystemStorage(location=root, base_url='/baseurl/')
Пример #18
0
def register(request):
    if 'username' in request.POST and 'password' in request.POST and 'email' in request.POST:
        u = request.POST['username']
        p = request.POST['password']
        e = request.POST['email']
        g = request.POST['inlineRadioOptions']
        uploaded_file = request.FILES['document']

        #django file system function, used for the profile picture
        fs = FileSystemStorage()
        name = fs.save(uploaded_file.name, uploaded_file)
        url = fs.url(name)  #full url

        dob = request.POST['bday']  #gets dob string

        todays_date = datetime.today().date()  #gets todays date
        birth_date = datetime.strptime(
            dob, '%Y-%m-%d').date()  #converts dob string into datetime format

        print(dob)  #prints user dob string
        print(todays_date)  #prints todays date
        print(birth_date)  #prints birth date

        age = ageCalculation(todays_date, birth_date)  #gets age from function
        print(age)  #prints value returned from the function

        some_var = request.POST.getlist(
            'hobby')  #some_var holds list of boxes ticked
        print(
            some_var
        )  # print boxes checked (hobbies) to the terminal  DEBUGGING PURPOSES GET RID OF AFTER

        user = Member(username=u, email=e)
        user.set_password(p)
        #user.save()
        prof = Profile(
            user_name=u, Gender=g, imageurl=url, age=age
        )  #the profile will have a user_name and a gender until now.. more to be added
        prof.save()
        user.profile = prof
        try:
            user.save()
        except IntegrityError:
            raise Http404('Username ' + u +
                          ' already taken: Usernames must be unique')

        for i in some_var:
            print(
                i
            )  # print specific hobbies from list to the terminal DEBUGGING PURPOSES GET RID OF AFTER

            selected_ob = Hobbie_choice.objects.get(
                choice=i)  # on each loop i create Hobbie_choice object

            user.choice.add(
                selected_ob)  # add it to the hobby choice of the created user

#       All_choices = user.choice.all()                               # get all the newly added hobbies

        return render(request, 'match/after_register.html')
    else:
        raise Http404('Please enter all fields')
Пример #19
0
def insert(request):
    if request.session['shop']:
        if request.method == 'POST':
            submit = request.POST['update']
            if submit == "insert":
                pname = request.POST['pname']
                img = request.FILES['img']
                fs = FileSystemStorage()
                name = fs.save(img.name, img)
                url = fs.url(name)
                cost = request.POST['cost']
                season = request.POST['season']
                stock = request.POST['stock']
                pmodel = request.POST['pmodel']
                if stock == "yes" and (season == "all" or season == month):
                    itemavail = 10
                else:
                    itemavail = 0
                product.objects.create(pname=pname,
                                       img=url,
                                       cost=cost,
                                       season=season,
                                       pmodel=pmodel,
                                       stockavailable=stock,
                                       itemavail=itemavail)
                return render(request, 'shop/update.html',
                              {'msg': 'update success'})
            elif submit == "stockupdate":
                pname = request.POST['pname']
                stock = request.POST['itemavail']
                t = product.objects.filter(pname=pname)
                if len(t) <= 0:
                    return render(request, 'shop/update.html',
                                  {'msg': "no items matched for update"})

                for i in t:
                    stockavailable = "no"
                    if i.season == month or i.season == "all":
                        if int(stock) >= 1:
                            stockavailable = "yes"

                product.objects.filter(pname=pname).update(
                    itemavail=stock, stockavailable=stockavailable)
                return update(request)

            elif submit == "costupdate":
                pname = request.POST['pname']
                cost = request.POST['cost']
                t = product.objects.filter(pname=pname)
                if len(t) <= 0:
                    return render(request, 'shop/update.html',
                                  {'msg': "no items matched for update"})

                product.objects.filter(pname=pname).update(cost=cost)
                return update(request)
            elif submit == "finditem":
                pname = request.POST['pname']
                t = product.objects.filter(pname=pname)
                if len(t) >= 1:
                    return render(request, 'shop/update.html', {
                        'msg': "item found",
                        'detail': t
                    })
                elif pname == "all":
                    t = product.objects.all()
                    return render(request, 'shop/update.html', {
                        'msg': "item found",
                        'detail': t
                    })

                else:
                    return render(request, 'shop/update.html',
                                  {'msg': "no item  found"})
            elif submit == "findbyorder":
                orderno = request.POST['orderno']
                t = purchasedetail.objects.filter(orderno=orderno)
                w = customer.objects.all()
                for i in w:
                    for j in i.orderno:
                        if int(j) == int(orderno):
                            w = customer.objects.filter(cname=i.cname)
                            break
                    else:
                        continue
                return render(request, 'shop/update.html', {
                    'msg': "details found",
                    'details': t,
                    'detail1': w
                })
            elif submit == "findbycustomer":
                t = tempcn.objects.all()
                for i in t:
                    tempcn.objects.filter(orderno=i.orderno).delete()
                cname = request.POST['cname']
                t = purchasedetail.objects.filter(cname=cname)
                f = customer.objects.filter(cname=cname)
                if cname == "all":
                    t = purchasedetail.objects.all()
                    f = customer.objects.all()
                if len(t) >= 1:
                    return render(request, 'shop/update.html', {
                        'msg': "details found",
                        'details': t,
                        'detail1': f
                    })
                else:
                    if len(t) == 0:
                        cname = cname.lower()
                        A = cname[0] + cname[1]
                        v = "^" + str(A) + ".*$"
                        t = purchasedetail.objects.all()
                        for i in t:
                            p = i.cname
                            p = str(p).lower()
                            x = re.search(v, p)
                            if (x):
                                tempcn.objects.create(
                                    cname=i.cname,
                                    orderno=i.orderno,
                                    totalcost=i.totalcost,
                                    productdetails=i.productdetails,
                                    status=i.status,
                                    date=i.date,
                                    orderby=i.orderby)
                            else:
                                continue
                        t = tempcn.objects.all()
                        if len(t) >= 1:
                            return render(request, 'shop/update.html', {
                                'msg': "some details found",
                                'details': t
                            })
                        else:
                            return render(request, 'shop/update.html',
                                          {'msg': "details not found"})
            elif submit == "shop":
                user = request.POST['cname']
                request.session["user"] = "******"
                request.session["admin"] = user
                return show(request)
            elif submit == "deleteitem":
                pname = request.POST['pname']
                product.objects.filter(pname=pname).delete()
                return render(request, 'shop/update.html',
                              {'msg': "product deleted"})
            elif submit == "cancelorder":
                orderno = request.POST['orderno']
                purchasedetail.objects.filter(orderno=orderno).update(
                    status="cancelled")
                return render(request, 'shop/update.html',
                              {'msg': "order cancelled"})

            elif submit == "delivered":
                orderno = request.POST['orderno']
                purchasedetail.objects.filter(orderno=orderno).update(
                    status="delivered")
                return render(request, 'shop/update.html',
                              {'msg': "order status updated"})
            elif submit == "todaysbusiness" or submit == "totalbusiness":
                if submit == "todaysbusiness":
                    t = purchasedetail.objects.filter(date=DATE)
                if submit == "totalbusiness":
                    t = purchasedetail.objects.all()
                today = 0
                for i in t:
                    if i.totalcost == None:
                        continue
                    today = today + int(i.totalcost)
                return render(request, 'shop/update.html',
                              {'today': 'TOTAL:' + str(today) + ' rupees'})
            elif submit == "addstaff":
                sname = request.POST['sname']
                phonenumber = request.POST['phone']
                salary = request.POST['salary']
                password = request.POST['password']
                if staff.objects.filter(phonenumber=phonenumber).exists():
                    return render(request, 'shop/update.html',
                                  {'msg': "staff phonenumber exists"})
                else:
                    staff.objects.create(sname=sname,
                                         phonenumber=phonenumber,
                                         salary=salary,
                                         password=password,
                                         dateofjoining=str(DATE))
                    allstaff.objects.create(sname=sname,
                                            phonenumber=phonenumber,
                                            salary=salary,
                                            dateofjoining=str(DATE))
                    return render(request, 'shop/update.html',
                                  {'msg': "staff added"})
            elif submit == "salaryupdate":
                phonenumber = request.POST['phone']
                salary = request.POST['salary']

                if staff.objects.filter(phonenumber=phonenumber).exists():
                    staff.objects.filter(phonenumber=phonenumber).update(
                        salary=salary)
                    allstaff.objects.filter(phonenumber=phonenumber).update(
                        salary=salary)
                    return render(request, 'shop/update.html',
                                  {'msg': "salary updated"})
                elif allstaff.objects.filter(phonenumber=phonenumber).exists():
                    allstaff.objects.filter(phonenumber=phonenumber).update(
                        salary=salary)
                    return render(request, 'shop/update.html',
                                  {'msg': "salary updated"})

                else:
                    return render(request, 'shop/update.html',
                                  {'msg': "staff not exist"})
            elif submit == "removestaff":
                phonenumber = request.POST['phone']
                if staff.objects.filter(phonenumber=phonenumber).exists():
                    staff.objects.filter(phonenumber=phonenumber).delete()
                    allstaff.objects.filter(phonenumber=phonenumber).delete()
                    return render(request, 'shop/update.html',
                                  {'msg': "staff removed"})

                elif allstaff.objects.filter(phonenumber=phonenumber).exists():
                    allstaff.objects.filter(phonenumber=phonenumber).delete()
                    return render(request, 'shop/update.html',
                                  {'msg': "staff removed"})

                else:
                    return render(request, 'shop/update.html',
                                  {'msg': "staff not exist"})
            elif submit == "addnewstaff":
                sname = request.POST['sname']
                phonenumber = request.POST['phone']
                salary = request.POST['salary']
                if allstaff.objects.filter(phonenumber=phonenumber).exists():
                    return render(request, 'shop/update.html',
                                  {'msg': "staff phonenumber exists"})
                else:
                    allstaff.objects.create(sname=sname,
                                            phonenumber=phonenumber,
                                            salary=salary,
                                            dateofjoining=str(DATE))
                    return render(request, 'shop/update.html',
                                  {'msg': "staff added"})
            elif submit == "tobedelivered":
                t = purchasedetail.objects.filter(status="tobedelivered")
                if len(t) > 0:
                    return render(request, 'shop/update.html', {'details': t})
                else:
                    return render(request, 'shop/update.html',
                                  {'msg': "no orders pending"})
            elif submit == "findstaffbyname":
                sname = request.POST['sname']
                if sname == "all":
                    t = allstaff.objects.all()
                    return render(request, 'shop/update.html', {'sdetail': t})

                elif allstaff.objects.filter(sname=sname).exists():
                    t = allstaff.objects.filter(sname=sname)
                    return render(request, 'shop/update.html', {'sdetail': t})

                else:
                    return render(request, 'shop/update.html',
                                  {'msg': "no staff found"})
            elif submit == "findstaffbynumber":
                phonenumber = request.POST['phone']
                t = allstaff.objects.filter(phonenumber=phonenumber)
                if len(t) > 0:
                    return render(request, 'shop/update.html', {'sdetail': t})
                else:
                    return render(request, 'shop/update.html',
                                  {'msg': "no staff found"})

    else:
        return render(request, 'shop/adminlogin.html')
Пример #20
0
 def storage(self):
     return FileSystemStorage(location=self.chunks_dir)
Пример #21
0
#skin-purple-light
#skin-yellow
#skin-yellow-light
GVSIGOL_SKIN = '##GVSIGOL_SKIN##'

GVSIGOL_NAME = '##GVSIGOL_NAME##'
GVSIGOL_SURNAME = '##GVSIGOL_SURNAME##'
GVSIGOL_NAME_SHORT = '##GVSIGOL_NAME_SHORT##'
GVSIGOL_SURNAME_SHORT = '##GVSIGOL_SURNAME_SHORT##'

CSRF_TRUSTED_ORIGINS = ['##GVSIGOL_HOST##']

FILEMANAGER_DIRECTORY = '##FILEMANAGER_DIR##'
FILEMANAGER_MEDIA_ROOT = os.path.join(MEDIA_ROOT, FILEMANAGER_DIRECTORY)
FILEMANAGER_MEDIA_URL = os.path.join(MEDIA_URL, FILEMANAGER_DIRECTORY)
FILEMANAGER_STORAGE = FileSystemStorage(location=FILEMANAGER_MEDIA_ROOT, base_url=FILEMANAGER_MEDIA_URL, file_permissions_mode=0o666)

CONTROL_FIELDS = [{
                'name': 'modified_by',
                'type': 'character_varying'
                },{
                'name': 'last_modification',
                'type': 'date'
                }]

EXTERNAL_LAYER_SUPPORTED_TYPES = ['WMS', 'WMTS', 'XYZ', 'Bing', 'OSM']

WMTS_MAX_VERSION = '1.0.0'
WMS_MAX_VERSION = '1.3.0'
BING_LAYERS = ['Road','Aerial','AerialWithLabels']
Пример #22
0
    def post(self, request, book_id):
        book_form = BookForm(request.POST,
                             author_choices=self.authors,
                             publisher_choices=self.publishers,
                             genre_choices=self.genres)
        book = self.book_dao.get_byid(book_id)

        context = {'book': book}

        if 'update-book' in request.POST:
            if book_form.is_valid():
                updated_book = Book()
                updated_book.book_id = book_id
                updated_book.title = book_form.cleaned_data['title']
                updated_book.isbn10 = book_form.cleaned_data['isbn10']
                updated_book.isbn13 = book_form.cleaned_data['isbn13']
                updated_book.copyRightDate = book_form.cleaned_data[
                    'copyright_date']
                updated_book.edition = book_form.cleaned_data['edition']
                updated_book.numberOfPages = book_form.cleaned_data[
                    'num_pages']
                updated_book.type = book_form.cleaned_data['book_type']
                author = Author()
                author.author_id = int(book_form.cleaned_data['authors'])
                updated_book.author = author
                publisher = Publisher()
                publisher.publisher_id = int(
                    book_form.cleaned_data['publishers'])
                updated_book.publisher = publisher
                genre = Genre()
                genre.genre_id = int(book_form.cleaned_data['genres'])
                updated_book.genre = genre

                self.book_dao.update(updated_book)

                context['notification'] = "Book updated successfully!"

            else:
                context['notification'] = "Not a valid submission."

        elif 'delete-book' in request.POST:
            book_id = int(request.POST.get('delete-book'))
            self.book_dao.delete(book_id)

        if 'add-image' in request.POST:
            image_form = BookImageForm(request.POST, request.FILES)

            if image_form.is_valid():
                image_file = request.FILES['image']
                fs = FileSystemStorage()
                filename = fs.save(image_file.name, image_file)
                uploaded_file_url = fs.url(filename)

                image = Image()
                image.image_url = uploaded_file_url
                image.caption = ''
                image.book.book_id = book_id

                self.image_dao.create(image)

                context['notification'] = filename
            else:
                context['notification'] = "Not a valid submission."

        return render(request, self.template_name, context)
Пример #23
0
import csvimport.monkeypatch_tzinfo

from django.db import models
from csvimport.app import settings
from copy import deepcopy
from django.core.files.storage import FileSystemStorage
import re

fs = FileSystemStorage(location=settings.MEDIA_ROOT)
CHOICES = (('manual', 'manual'), ('cronjob', 'cronjob'))
MODELS = []


def get_models():
    """ Cannot load at module level for later djangos - since its too early
    """
    global MODELS
    if MODELS:
        return MODELS
    # Create your models here.
    if not getattr(settings, 'CSVIMPORT_MODELS', []):
        try:
            # django1.7 or later ...
            try:
                allmodels = models.get_models()
            except:
                allmodels = []
        except:
            allmodels = models.loading.get_models()
        if allmodels:
            MODELS = ['%s.%s' % (m._meta.app_label,
Пример #24
0
from groups.models import Group, GroupMember
from datetime import datetime
from autoslug import AutoSlugField
from django.db.models import Max
from dashboard.models import NewsItem
from django.core.urlresolvers import reverse
import os.path
from django.conf import settings
from django.utils.safestring import mark_safe
from courselib.slugs import make_slug

STATUS_CHOICES = [('NEW', 'New'), ('INP', 'In-Progress'), ('DON', 'Marked')]

from django.core.files.storage import FileSystemStorage

SubmissionSystemStorage = FileSystemStorage(location=settings.SUBMISSION_PATH,
                                            base_url=None)

# per-activity models, defined by instructor:


class SubmissionComponent(models.Model):
    """
    A component of the activity that will be submitted by students
    """
    activity = models.ForeignKey(Activity)
    title = models.CharField(
        max_length=100,
        help_text=
        'Name for this component (e.g. "Part 1" or "Programming Section")')
    description = models.CharField(
        max_length=1000,
Пример #25
0
from django.contrib.messages import info
from django.core.files.storage import FileSystemStorage
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.utils.translation import ungettext, ugettext_lazy as _

from mezzanine.conf import settings
from mezzanine.core.admin import TabularDynamicInlineAdmin
from mezzanine.core.forms import DynamicInlineAdminForm
from mezzanine.forms.forms import EntriesForm
from mezzanine.forms.models import Form, Field, FormEntry, FieldEntry
from mezzanine.pages.admin import PageAdmin
from mezzanine.utils.static import static_lazy as static
from mezzanine.utils.urls import admin_url, slugify

fs = FileSystemStorage(location=settings.FORMS_UPLOAD_ROOT)

# Copy the fieldsets for PageAdmin and add the extra fields for FormAdmin.
form_fieldsets = deepcopy(PageAdmin.fieldsets)
form_fieldsets[0][1]["fields"][3:0] = ["content", "button_text", "response"]
form_fieldsets = list(form_fieldsets)
form_fieldsets.insert(1, (_("Email"), {
    "fields": ("send_email", "email_from", "email_copies", "email_subject",
               "email_message")
}))

inline_field_excludes = []
if not settings.FORMS_USE_HTML5:
    inline_field_excludes += ["placeholder_text"]

Пример #26
0
def stu_profile_edit_save(request):
    id = request.POST.get("student_id")
    print(id)
    enrolment_no = request.POST.get("enrolment_no")
    stu_first_name = request.POST.get("stu_first_name")
    stu_last_name = request.POST.get("stu_last_name")
    sex = request.POST.get("sex")
    phone_no = request.POST.get("phone_no")
    ssc_percentage = request.POST.get("ssc_percentage")
    hsc_percentage = request.POST.get("hsc_percentage")
    ug_stream = request.POST.get("ug_stream")
    ug_percentage = request.POST.get("ug_percentage")
    pg_cgpa = request.POST.get("pg_cgpa")

    context = {
        "eno": enrolment_no,
        "fname": stu_first_name,
        "lname": stu_last_name,
        "phone_no": phone_no,
        "ssc": ssc_percentage,
        "hsc": hsc_percentage,
        "ug": ug_percentage,
        "pg": pg_cgpa,
    }

    if enrolment_no == "" or stu_first_name == "" or stu_last_name == "" or phone_no == "" or ssc_percentage == "" or hsc_percentage == "" or ug_stream == "" or ug_percentage == "" or pg_cgpa == "":
        messages.error(request, "fill all the details")
        response = stu_profile(request, context)
        return response

    user = Students.objects.get(id=id)
    if request.FILES.get('profile_pic'):
        profile_pic = request.FILES.get('profile_pic')
        # dir_storage = '/media/student_media/profile_picture/' + enrolment_no
        fs = FileSystemStorage()
        filename = fs.save(profile_pic.name, profile_pic)
        print(filename)
        profile_pic_url = fs.url(filename)
        user.profile_pic = profile_pic_url

    # usernamecheck = CustomUser.objects.filter(username=enrolment_no).first()
    #
    # if usernamecheck != None:
    #     messages.error(request, "With this enrollment Account is already Created")
    #     response = edit_student(request, context)
    #     return response

    usertable = CustomUser.objects.get(id=user.user_type_id)
    usertable.first_name = stu_first_name
    usertable.last_name = stu_last_name
    usertable.save()
    user.enrolment_no = enrolment_no
    user.gender = sex
    user.phone_no = phone_no
    user.ssc_percentage = ssc_percentage
    user.hsc_percentage = hsc_percentage
    user.ug_percentage = ug_percentage
    user.pg_cgpa = pg_cgpa
    user.save()

    messages.success(request, "Student Account Updated")
    return HttpResponseRedirect(reverse("stu_profile_edit", kwargs={'id': id}))
Пример #27
0
 def setUp(self):
     self.storage_dir = tempfile.mkdtemp()
     self.storage = FileSystemStorage(self.storage_dir)
     self.thread = threading.Thread(target=self.save_file,
                                    args=['conflict'])
Пример #28
0
def write_upload_to_file(photo_file, upload_path):
    """ Save bufferred file in memory to disk """
    fss = FileSystemStorage()
    filename = fss.save(upload_path + photo_file.name, photo_file)
    uploaded_file_url = fss.url(filename)
    return uploaded_file_url
Пример #29
0
 def setUp(self):
     self.storage_dir = tempfile.mkdtemp()
     self.storage = FileSystemStorage(self.storage_dir)
Пример #30
0
def index(request):
    # Authentication
    auth_error = get_auth_error(request)
    if auth_error is not None:
        return auth_error

    # Finally process the request
    if request.method != 'POST':
        # GET processing
        # Render the form
        return render(request, 'SubmitExperiment/index.html',
                      {'form': ExperimentForm()})

    # POST processing
    # Validate form and submit experiment
    form = ExperimentForm(request.POST, request.FILES)
    if not form.is_valid():
        messages.error(request, 'Submitted form was not valid.')
        messages.info(request, 'Please fix the errors and try again.')
        return render(request, 'SubmitExperiment/index.html', {'form': form})

    # I shouldn't be validating fields here, but in form
    # I can't know whether user is logged in or not
    if request.user.is_authenticated:
        email = request.user.email
    else:
        email = form.cleaned_data['author_email']

    if email is None or len(email) == 0:
        messages.error(request, 'Submitted form was not valid.')
        messages.info(request, 'Please fix the errors and try again.')
        form.add_error('author_email', 'This field is required.')
        return render(request, 'SubmitExperiment/index.html', {'form': form})

    # Form is valid here, continue
    in_file = request.FILES['in_file']

    if form.cleaned_data['default_cfg']:
        # Picking default configuration if possible
        config_list = PredefinedConfiguration.objects.all().order_by(
            'required_bytes')
        if len(config_list) == 0:
            raise AssertionError('there are no predefined configurations')

        last_leq_id = None
        for c in config_list:
            if in_file.size >= c.required_bytes:
                last_leq_id = c.id
            else:
                break

        if last_leq_id is None:
            last_leq_id = config_list[0].id
            messages.warning(
                request, "Provided file is too small for all configurations.")

        chosen_cfg = PredefinedConfiguration.objects.get(id=last_leq_id)
        messages.info(
            request,
            "Best possible configuration was chosen and requires {} bytes.".
            format(chosen_cfg.required_bytes))
        cfg_file = chosen_cfg.cfg_file

    elif form.cleaned_data['choose_cfg'] is not None:
        # User picked one of predefined configurations
        cfg = PredefinedConfiguration.objects.get(
            id=form.cleaned_data['choose_cfg'].id)
        cfg_file = cfg.cfg_file
        if in_file.size < cfg.required_bytes:
            messages.warning(
                request, "Your file is smaller than"
                " recommended file size for chosen configuration.")
            messages.warning(
                request,
                "Recommended file size: {} bytes".format(cfg.required_bytes))
            messages.warning(
                request,
                "Size of provided file: {} bytes".format(in_file.size))
    else:
        # User provided his own configuration
        cfg_file = request.FILES['own_cfg']

    fs = FileSystemStorage()
    in_file_path = fs.path(fs.save(in_file.name, in_file))
    cfg_file_path = fs.path(fs.save(cfg_file.name, cfg_file))

    try:
        _thread.start_new_thread(submit_experiment,
                                 (form, email, in_file_path, cfg_file_path))
    except BaseException as e:
        print('Could not start a thread: {}'.format(e))

    messages.success(
        request,
        'Experiment {} was created.'.format(form.cleaned_data['exp_name']))
    return redirect('SubmitExperiment:index')