Re: Upload images

61 views
Skip to first unread message
Message has been deleted

Kasper Laudrup

unread,
Feb 11, 2021, 2:23:50 PM2/11/21
to django...@googlegroups.com
On 11/02/2021 19.29, mtp...@gmail.com wrote:
>
> I have implemented the following view but saving the images part is an
> issue:
>

What's the issue? Knowing that would make it easier for someone to help you.

Having a quick look at the code, I would start by removing the
try/except block until you have a way to actually handle the errors you
expect to encounter.

Currently you either ignore exceptions making it impossible to debug
errors, or catch them and tell the client/user that they're to blame for
whatever unknown exception was raised (with a 400 status code) without
leaving any trace of what actually went wrong for you to fix. That's not
error handling.

Kind regards,

Kasper Laudrup

Theresa Taye

unread,
Feb 11, 2021, 4:21:19 PM2/11/21
to django...@googlegroups.com
What is the error message? Is it in your admin site you are getting issues uploading images or when rendered in the template?

For me I use this in my model:
image = models.ImageField(null=True, blank=True, upload_to="images/")

the upload_to specifies wherein the static folder I want to upload the images

On Thu, 11 Feb 2021 at 19:30, mtp...@gmail.com <mtp...@gmail.com> wrote:
Hello everyone,
 I have implemented an endpoint to register an organization how do I make it posssible to upload the images considering the org model as shown below.

```

class Organization(Group):
    email = models.EmailField(max_length=60, blank=False, null=False)
    admin = models.ManyToManyField(settings.AUTH_USER_MODEL)
    users = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='org_users')
    is_active = models.BooleanField(default=False)
    short_name = models.CharField(max_length=200,blank=True)
    location = models.CharField(max_length=200,blank=True, null=True)
    tag_line = models.TextField(null=True,blank=True)
    company_phone =  models.CharField(max_length=15, blank=True, null=True)
    po_box = models.CharField(max_length=15, blank=True, null=True)
    first_logo = models.ImageField(null=True,blank=True)
    second_logo = models.ImageField(null=True,blank=True)
    third_logo = models.ImageField(null=True,blank=True)
    history = HistoricalRecords()

```

I have implemented the following view but saving the images part is an issue:

```
class OrganizationRegistration(generics.CreateAPIView):
    queryset = Organization.objects.all()
    permission_classes = (permissions.AllowAny,)
    serializer_class = OrgRegistrationSerializer

    """
    {
    "admin":{
            "username":"kapy...@abyssmail.com",
            "first_name":"Cindy",
            "last_name":"Georgia",
            "password":"password",
            "email":"kapy...@abyssmail.com"
        },
    "org":{
            "name":"ARIZONA LAW SOCIETY",
            "short_name":"ALS",
            "tag_line":"ALS",
            "email":"kapy...@abyssmail.com",
            "company_phone": "+25475533222",
            "po_box": "200",
            "location":"NAKURU",
        }
    }
    """

    def post(selfrequestformat=None, *args, **kwargs):
        try:
            admins = Group.objects.get(name__iexact='admin')
            admin_role = Role.objects.get(name__iexact="admin")
            
        except:
            # The admin group is
            admins = Group.objects.create(name="admin")

            admin_role = Role.objects.create(name="admin")

        # Validate USer and Org
        if Organization.objects.filter(name__iexact=request.data['org']['name']).exists() is True:
            res = {"data": None, "msg":"Organization with that name already registered","success": False}
            return Response(data=res,status=status.HTTP_400_BAD_REQUEST)

        if User.objects.filter(username__iexact=request.data['admin']['username']).exists() is True:
            res = {"data": None, "msg":"User with that name already registered.","success": False}
            return Response(data=res,status=status.HTTP_400_BAD_REQUEST)


        try:
            admin = User.objects.create(
                username=request.data['admin']['username'],
                email=request.data['admin']['email'],
                first_name=request.data['admin']['first_name'],
                last_name=request.data['admin']['last_name'],
            )

            location_name = request.data['org']['location'].upper()
        
            location_obj, _  = Location.objects.get_or_create(name=location_name)
            area_name = location_obj.name

            # Create Random Password   
            password = User.objects.make_random_password(length=10)

            admin.set_password(password)
            admin.save()
            admin.groups.add(admins)
            admin.roles.add(admin_role)
        except Exception as e:
            return Response(data={"msg":str(e),"success":False, "data": None},status=status.HTTP_400_BAD_REQUEST)

        try: 

            first_file_logo = request.data['org']['first_logo']
            second_file_logo = request.data['org']['second_logo']
            third_file_logo = request.data['org']['third_logo']

            org = Organization.objects.create(
                name=request.data['org']['name'],
                email=request.data['org']['email'],
                location=request.data['org']['location'],
                short_name = request.data['org']['short_name'],
                tag_line = request.data['org']['tag_line'],
                company_phone =  request.data['org']['company_phone'],
                po_box = request.data['org']['po_box'],
                first_logo = first_file_logo,
                second_logo =second_file_logo ,
                third_logo =  third_file_logo
            )

            admin.org_id = org.id
            admin.save()
            # add the user creating the Organization to admins by DEFAULT
            NOTE:
            # all the other normaall users will be added normally i.e
            admins.save()
            org.admin.add(admin)
            org.users.add(admin)
            admin.is_active = False
            admin.save()

            payload = jwt_payload_handler(admin, org)
            jwt_token = jwt_encode_handler(payload)



            support_email = settings.SUPPORT_EMAIL
            # # FIXME:
            # refactor this code inorder to have its own function
            path = get_full_path(request)

            path = settings.BASE_URL



            subject = 'Welcome onboard E-Voting'

            org_html_message = loader.render_to_string('authenticate/org-confirmation.html')
            admin_html_message = loader.render_to_string('authenticate/admin-confirmation.html')
            # if the org is regestering themselves the org id will alway be zero

            admin_message_string = strip_tags(admin_html_message)
            org_message_string = strip_tags(org_html_message)
            
            admin_ctx = {
                'name': admin.username,
                'password': password,
                'email': admin.email,
                'link': '{}registration/confirmation/{}/'.format(path, jwt_token.decode("utf-8"))
                }

            org_ctx = {
                'name': org.name,
                'email': org.email,
                'link': '{}registration/confirmation/{}/'.format(path, jwt_token.decode("utf-8"))
                }


            admin_html_content = loader.render_to_string('authenticate/admin-confirmation.html', admin_ctx)
            org_html_content = loader.render_to_string('authenticate/org-confirmation.html', org_ctx)

            admin_message = {
                "html": admin_html_content,
                "text": admin_message_string
            }

            org_message = {
                "html": org_html_content,
                "text": org_message_string
            }


            # SEND BOTH MAIL TO ACTIVATE USER AND ORG 
            send_mail_to_org = send_credentials.delay(
                'Welcome onboard E-Vote: Organization Confirmation',
                org_message,
                org.email
            )

            send_mail_to_admin = send_credentials.delay(
                'Welcome onboard E-Vote: Admin Confirmation',
                admin_message,
                admin.email
            )



            
            serializer = OrgRegSerializer(org)
            res = {"msg": "Check personal and organization emails, NOTE: finish org registration first!!!", "success": True, "data": serializer.data}
            return Response(
                data=res,
                status=status.HTTP_201_CREATED
            )
        except Exception as e:
            return Response(data={"msg":str(e),"success":False, "data": None},status=status.HTTP_400_BAD_REQUEST)
``

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/8afd1264-fb4f-4b49-8b62-d6a5e19d8c11n%40googlegroups.com.
Message has been deleted

mtp...@gmail.com

unread,
Feb 11, 2021, 11:13:06 PM2/11/21
to Django users
How do I check if the files are valid images or not before creating the organization objec

Kasper Laudrup

unread,
Feb 12, 2021, 7:09:01 AM2/12/21
to django...@googlegroups.com
On 12/02/2021 05.12, mtp...@gmail.com wrote:
> How do I check if the files are valid images or not before creating the
> organization object.
>

When asking someone for help, at least have the courtesy to reply the
suggestions you're given before asking an unrelated question.

This will greatly improve the chances of getting help from someone.

Kind regards,

Kasper Laudrup

sakshi jain

unread,
Feb 13, 2021, 9:49:14 AM2/13/21
to django...@googlegroups.com
Hello team 
I'm Ashima 

Here I want some little help in image upload in django 

I'm share one Screenshot plz help me How I set the path 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
B612_20210213_094641_681.jpg

sakshi jain

unread,
Feb 14, 2021, 12:07:24 AM2/14/21
to django...@googlegroups.com
hello team plz help 
image.png

Omkar Parab

unread,
Feb 14, 2021, 1:16:09 AM2/14/21
to django...@googlegroups.com
First, go to "cd myzite" folder and then run,

python manage.py startapp app_name




sakshi jain

unread,
Feb 14, 2021, 1:56:31 AM2/14/21
to django...@googlegroups.com
Reply all
Reply to author
Forward
0 new messages