Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django- how to add user profile permissions based for selected users
In my Django app, I have a user_profile model (below). This model has an is_adm boolean which is True/False depending on whether or not the user is an 'administrator': user_profile/models.py: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField('username', max_length=50, unique=True) email = models.EmailField('email address', unique=True) first_name = models.CharField(max_length=20, blank=True, null=True) last_name = models.CharField(max_length=20, blank=True, null=True) is_adm = models.BooleanField(default=False) Separately I have a posts model for blog posts. There is an admin panel for this model. posts/models.py: class Posts(models.Model): title = models.CharField(max_length=300, default='') publish_date = models.DateField(blank=True, null=True) author = models.CharField(max_length=300) copy = models.TextField(blank=True, default='') link = models.URLField(blank=True) source = models.TextField(default='', blank=True) published = models.BooleanField(default=False) I want the ability for is_adm = True users to be able to: add a Post model instance in the admin panel delete any Post model instance in the admin panel view any Post model instance in the admin panel edit certain fields in the Posts admin panel (every field except for copy and source) I know that Django has Permissions and Authorization: https://docs.djangoproject.com/en/2.2/topics/auth/default/#permissions-and-authorization But how do I add these methods like: has_view_permission(), has_add_permission(), has_change_permission() and has_delete_permission()... do I add them to the User class? Or somewhere else in the user_profile/models.py file? -
'signupform' object has no attribute 'email'
i am trying to send mail using django when a person login but i get error ,'signupform' object has no attribute 'email' and it says error at line 84 which is mentioned in views.py here is forms.py signupform(UserCreationForm): email=forms.EmailField(max_length=50,help_text='Required',widget=forms.EmailInput(attrs={'placeholder':'email'})) password1=forms.CharField(max_length=50,widget=forms.PasswordInput(attrs={'placeholder':'password'})) password2=forms.CharField(max_length=50,widget=forms.PasswordInput(attrs={'placeholder':'Re Enter password'})) class Meta: model=User fields=['username','email','password1','password2'] widgets={ 'username':TextInput(attrs={'placeholder':'username'}) } here is views.py def signupview(request): form=signupform() if request.method=='POST': form=signupform(request.POST) if form.is_valid(): subject='welcome to blog ' message='its our pleasure to have you ' send_mail(subject, message, settings.EMAIL_HOST_USER [form.email],fail_silently=False,) #line 84 form.save() return redirect('/blogapp/') else: form=signupform() context={'form':form} return render(request,'blogapp/signupform.html',context) -
Django: Pass queryset from template to view
I'm trying to send a queryset from a filter (or the object itself) from a template to a view: Here is the first view sending my filter: def view_one(request): objects = Model.objects.all() filtre = ModelFilter(request.GET, queryset=objects) return render(request, 'template.html', locals()) Here is the template where i'm trying to send the queryset into my view_two {{ filtre.qs }} # With this i can access my queryset <a class="button" href="{% url 'view_two' %}">Send queryset</a> And now accessing the filter or queryset: def view_two(request): print(request.GET) print(request.GET.get('filtre')) How can i do that ? Because from what django can pass through url, object and queryset are not a possibility .... -
how do I filter all the shipping address objects associated with specific order
how do I filter all the shipping address objects associated with specific order, so when someone orders a product with a shipping address I wanna get that address and render it to the template specific to that order. I would really appreciate your help, thx! models.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) class Product(models.Model): name = models.CharField(max_length=150) description = models.TextField() class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) address_one = models.CharField(max_length=200) views.py @login_required def orders(request): orderitems = OrderItem.objects.filter(order__customer__user=request.user) #how do I get the shipping address associated with order shipping = ShippingAddress.objects.filter() context = {"orderitems": orderitems, "shipping": shipping} HTML {% for orderitem in orderitems %} <div class="order-data-view"> <div class="order">{{ orderitem.product.name }}</div> <div class="date">{{ orderitem.date_added }}</div> <div class="status">dummydata</div> <div class="delivering-to">{{ address_one }}</div> </div> {% endfor %} -
Django - how to make an imagefield store multiple image files and display in html
in my html I have a field called "all photos", which should contain all photos uploaded. my questions are: how to make an imagefield store multiple images files (e.g. .jpg/.png)? how to dispaly all files of this imagefield in html as one field, not as pictures but as multiple clickable links with file names, like it is shown in django admin, e.g. model.py class Order(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT, related_name="order_users",blank=True, null=True) user_name = models.TextField(blank=True, null=True) order_ref = models.TextField(blank=True, null=True) order_time = models.TextField(blank=True, null=True) ... remark = models.TextField(blank=True, null=True) image = models.ImageField(blank=True, null=True, upload_to='images') view.py @login_required def staff_order(request, id): if request.method == "POST": order = Order.objects.get(pk=id) order.email = request.POST['email'] order.image = request.FILES['pic'] order.save() return render(request, 'OnlinePricing/staff_order.html', {'order': order, 'id': id, 'message': ['success', 'order updated.']}) else: order = Order.objects.get(pk = id) return render(request, 'OnlinePricing/staff_order.html', {'order': order, 'id': id, 'message': ['success', 'order updated.']}) html: <form> ... <label>upload photos:</label> <input name="pic" type="file" /></th> <label>all photos: </label><img src= "{{ order.image.url }}"></th> </form> -
Allow the user to crop image manually django
I'm stuck with a problem for a long time on the website I'm working on with django. In my django model, I've added an Image field for the profile pic, using django_resized So now when an user is choosing a pic, I'm cropping and resizing it as a square of 315*315. But I can only choose where the pic is cropped (here in the middle). In some cases, the people's faces are not exactly in the center of the pic and that's a problem. I would like to allow the user to choose manually where to crop the image (with a square to move on the pic), just as all the social medias are doing when you upload a profile pic. Here's my code, thank you very much in advance. from django.db import models from django_resized import ResizedImageField class Account(models.Model): profile_pic = ResizedImageField(size=[315, 315], crop=['middle', 'center'], quality=99, default="default_profile_pic.png", null=True, blank=True) -
How to trim/strip leading whitespaces from StringField for list view in Django/Mongodb?
Want to sort data by names, but unfortunately there are many data with leading whitespaces, that is why rest_framework.filters.OrderingFilter doesn't work properly. Mongo, DRF are used in my project. My model: from mongoengine import DynamicDocument, fields class Book(DynamicDocument): name = fields.StringField(required=True) description = fields.StringField(blank=True, null=True) meta = { 'collection': 'books', 'strict': False, } My view: from rest_framework.filters import OrderingFilter from rest_framework_mongoengine import viewsets from core.serializers import BookSerializer from core.models import Book class BookViewSet(viewsets.ModelViewSet): serializer_class = BookSerializer queryset = Book.objects.all() filter_backends = [OrderingFilter] ordering_fields = ['name'] ordering = ['name'] Someone has any idea, how to solve that? Try to annotate queryset: from django.db.models import F, Func ... class BookViewSet(viewsets.ModelViewSet): ... def get_queryset(self): queryset = self.queryset.annotate(name_lower=Func(F('name'), function='LOWER')) -
Django query data based on checkbox
I am trying to query data, brands of a certain items based on checkboxes. If no checkboxes are checked, then all brands are shown, If a checkbox with, lets say django is checked, then all brands of brand django is query from the db. Here is the checkboxes of brands: {% for brand in brands.all %} <div class="card-body" id="tabl"> <label class="custom-control custom-checkbox"> <input type="checkbox" value="{{ brand.brand }}" class="custom-control-input"> <div class="custom-control-label">{{ brand.brand}}</div> </label> </div> {% endfor %} models.py class Product(models.Model): """ Containing the products, each product belong to a category and each product have a feedback system """ category = models.ForeignKey(Category, related_name='products', on_delete=CASCADE) name = models.CharField(max_length=55) brand = models.CharField(max_length=55) price = models.FloatField() featured = models.BooleanField(default=False) image = ResizedImageField(size=[460,460], quality=100, upload_to='products', default='None', blank=True, null=True) slug = models.SlugField(max_length=400, unique=True, blank=True) description = models.TextField(default='product', blank=True) def __str__(self): return self.name views.py def products(request, slug): """ List all products of a category """ category = get_object_or_404(Category, slug=slug) products = Product.objects.filter(category=category) brands = Product.objects.filter(category=category).distinct('brand') context = { 'products': products, 'category': category, 'brands': brands, 'title': Product, } return render(request, 'products/products.html', context) Then further down on the page I will query the products, but then how to do it, based on what checkbox is pressed, is lost on me. … -
How do I authenticate a Lambda function to access a Django endpoint?
Note: This question appears to be identical, but actual problem asked is unanswered and the OP ends up changing his entire approach. Suppose I have some lambda-based application that I want to let access my Django application. How do I authenticate it? I could just give the lambda function a username/password, but that's far from ideal in a long term security context. Is there a way to directly authenticate a lambda function in django? Alternatively, are there better security practices that could be employed (i.e. secret rotation) so that this can be done? -
Django : How can we display the filenames of multiple selected files before uploading them
I did an app to upload files to a blob storage and to display their names in a table, once they are uploaded. However, I would like to change the part where they select the files. I would like that the filenames of the files, that the user has selected, are shown in the template before that it click on the button update. Like that the user could verify that it is these files that he wants to upload. The best would be that the user could unselect few files if he did a mistake. Is it possible to do that on Django ? Is it a part in Javascript ? Anyone could show me what I should change or add ? Thank you Here is my Form.py class FilesForm(forms.ModelForm): class Meta: model = UploadFiles fields = ['Filename'] widgets = {'Filename': ClearableFileInput(attrs={'multiple': True}),} The models.py class UploadFiles(models.Model): Id = models.IntegerField(db_column='ID') # Field name made lowercase. Filename = models.CharField(db_column='FileName', max_length=255, blank=True, null=True) # Field name made lowercase. PreviousFilename = models.CharField(db_column='FileNameBeforeIndex', max_length=255, blank=True, null=True) # Field name made lowercase. User = models.CharField(db_column='User', max_length=255, blank=True, null=True) # Field name made lowercase. SizeFile = models.IntegerField(db_column='Sizefile') Uploaded_at = models.DateTimeField(db_column='Timestamp', auto_now_add=True) # Field name made lowercase. … -
Django Many To Many Field Query Admin Page
I have a field in my student model called counselors. All I am trying to do is list the users that are in the group counselors to be displayed in this many to many relationship. How do i go about doing this? Here is the field in my model. Thanks counselor = models.ForeignKey(User, related_name='Counselors', on_delete = models.PROTECT,null=True,blank = True) The current setup only shows all the users within the User table not Users associated in the Counselors group. -
Django rest framework POST request followed by GET request
I am using django rest framework and I want after a POST request in a URL to follow a GET request to another URL with processing some data coming from the POST request. I attach my views.py: from rest_framework.response import Response from rest_framework.decorators import api_view from importer import event_import_data from utils import optimization_solution @api_view(['POST']) def event(request): event_data_post = request.data return Response(event_data_post) @api_view(['GET']) def optimization(request): response_dict = {} event_data = event_import_data(event_data_post) response_dict = optimization_solution(event_data) return Response(response_dict) So, initially I POST a json file in a URL and then I expect by using the dictionary provided by the POST request to use it in the GET request in another URL. However, I am getting the following error: NameError: name 'event_data_post' is not defined Any idea of what is causing the error and how can I bypass it? -
how do I get all the product list that's been ordered in template
how do I filter all the objects associated with "orderitem" for a specific user, so when someone orders a couple of products I want to show the ordered products in the template, right now I'm getting "The QuerySet value for an exact lookup must be limited to one result using slicing". would really appreciate your help, thx! models.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) class Product(models.Model): name = models.CharField(max_length=150) description = models.TextField() views.py def orders(request): if request.user.is_authenticated: customer = request.user.customer orders = Order.objects.filter(customer=customer) orderitems = OrderItem.objects.filter(order=orders) else: print('error') context = {"orderitems": orderitems} return render(request, 'accounts/orders.html', context) HTML {% for orderitem in orderitems %} <div class="ordered-view"> <div class="order">{{ orderitem.product.name }}</div> <div class="date">dummydata</div> <div class="status">dummydata</div> <div class="total">dummydata</div> </div> {% endfor %} -
How to roundup and round down the decimal part in python
how to round down and round up the decimal vlaues in pytho. user input a =2.336 After round up it should be like a =2.34 a =4.13623 After round up it should be like a =4.14 Is there any built in functions in python to manipulate -
Why does Django ExtractWeekDay assign the same day to consecutive dates?
I have a model CustomerPurchase which records metadata about a purchase made. I am trying to filter complaints that these purchases are attached to via a foreign key and related name tickets then group by weekday to find which days of the week have the most complaints. I am running into an issue where I am having consecutive days listed as two different weekdays when using Django's ExtractWeekDay. Why does this happen? sample of my code: from django.db.models.base import model from django.db.models.functions import ExtractWeekDay, Trunc interval_type = 'days' class CustomerPurchase(model): business = ForeignKey('data.Business', on_delete=CASCADE) VISIT_TIME_CHOICES = ( ('L', 'Lunch'), ('M', 'Mid-day'), ('D', 'Dinner'), ('N', 'Late Night'), ('U', 'Unrecorded') ) visit_time = CharField(max_length=1, choices=VISIT_TIME_CHOICES, default='U') CustomerPurchase.objects.filter(business__company=1080, tickets__conversation__ci_priority__isnull=False ).exclude(visit_time='U').annotate( day=ExtractWeekDay('tickets__created_at') ).values('day').annotate( date_value=Trunc('tickets__created_at', kind=interval_type, output_field=DateField()) ) the output of the above query: <QuerySet [{'day': 1, 'date_value': datetime.date(2021, 5, 30), 'count': 99}, {'day': 1, 'date_value': datetime.date(2021, 5, 31), 'count': 102}, {'day': 1, 'date_value': datetime.date(2021, 6, 6), 'count': 92}, {'day': 1, 'date_value': datetime.date(2021, 6, 7), 'count': 126}, {'day': 1, 'date_value': datetime.date(2021, 6, 13), 'count': 104}, {'day': 1, 'date_value': datetime.date(2021, 6, 14), 'count': 130}, {'day': 1, 'date_value': datetime.date(2021, 6, 20), 'count': 64}, {'day': 1, 'date_value': datetime.date(2021, 6, 21), 'count': 51}, {'day': 1, 'date_value': datetime.date(2021, 6, 27), … -
How are resources allocated to Django processes/thread?
If I am hosting a website on a cloud server that I provisioned with a fixed amount of resources (CPU, RAM etc). If there are 3 clients accessing the webpage, how is the website served? Is one thread/process/Djandgo instance spawned to serve a client? Or can one single thread serve multiple client requests? How do I figure out how much resources I need for my server, or if I even need multiple servers? And how does this extend to application hosting in general? -
implementation of link decorator in RichTextField (CKEditor) to Django admin panel
I am using CKeditor in my Django app and I'd like to ask if there is any way to implement link decorator to my body field (RichTextField). What I want is a feature that will detect tags (I am using django-taggit to handle tags) in the text and will create a hyperlink that will redirect to the tag page. For example. I put python is amazing in my RichTextField where python is a tag so it will be automatically hyperlinked to http://127.0.0.1:8000/tag/python after I save the article. Right now, I need to do it manually by clicking cltr+K and inserting a link but I am wondering if this can be automated by any chance? -
Django format a request in a list
I need help to format a response of a django request, This is a exemple : With a model like this: Book(models): name = string author = string release = date A request : Book.objects.filter(author='Hergé').value('name') I got : [{'name':'Tintin au Tibet'}, {'name':'Tintin au Congo'}, {'name':'Tintin chez les Picarros'}] I want this : ['Tintin au Tibet','Tintin au Congo','Tintin chez les Picarros'] My question: How to I get what I want by changing only the request ? -
Django : Add an additional set to objects without direct relative ForeignKey
The subject seems a bit confusing but my case is a little complicated. I'm building an app for mapping supplier products files (called FLOW). I've got 4 models : models.flow : flow from the supplier (csv) class Flow(models.Model): [...] nothing special here models.FicheHeader : all the fields I will populate with the datas fetched in the CSV class FicheHeader(models.Model): label = models.CharField(max_length=50, unique=True) models.FicheHeaderFlow : built another table for referencing all needed fields that need to be fulfilled class FicheHeaderFlow(models.Model): label = models.ForeignKey(FicheHeader, on_delete=models.CASCADE) flow = models.ForeignKey(Flow, on_delete=models.CASCADE) used = models.BooleanField(default=False) models.FlowSample : samples of the first line from the CSV recorded when flow is created class FlowSample(models.Model): index_col = models.IntegerField() content = models.TextField(max_length=255) flow_id = models.ForeignKey(Flow, on_delete=models.CASCADE) This last Model is only connected to the Flow FK. Now , I need to display in the same template all fields mapped with the relative columns ids of the CSV and show the result preview using the FlowSamples. I managed to do everything BUT retrieving FlowSamples related to the MappingField.fl_fiche_header_flow. Because MappingField and FlowSample have no FK direct relation (no SET possible). My query_set : def get_queryset(self, *args, **kwargs): return FicheHeaderFlow.objects. prefetch_related(Prefetch('mappingfield_set', MappingField.objects.select_related('fl_fiche_header_flow') .order_by('fl_fiche_header_flow_id', 'fl_fiche_inside_field_position'))) .filter(flow_id=self.kwargs['pk']).order_by('-used', 'pk') I tried during 2 … -
Parse second/third page and add to list with BeautifulSoup
I am trying to scrape a website for recipes and then present a page with a random pick. For this I have made a piece of code that works perfect when I just get the first page, 35 recipes. However: I want to grab the recipes from the 2nd and 3rd page as well. I figured I should write a loop for this but I can't seem to get it right. What did I do wrong in this code? from django.shortcuts import render import requests import re from bs4 import BeautifulSoup import random # Create your views here. def recipe(request): #Create soup page = 0 while page != 2: webpage_response = requests.get("https://www.ah.nl/allerhande/recepten-zoeken?page=" + str(page)) webpage = webpage_response.content soup = BeautifulSoup(webpage, "html.parser") recipe_links = soup.find_all('a', attrs={'class' : re.compile('^display-card_root__.*')}) recipe_pictures = soup.find_all('img', attrs={'class' : re.compile('^card-image-set_imageSet__.*')}) recipe_prep_time = [ul.find('li').text for ul in soup.find_all('ul', attrs={'class': re.compile('^recipe-card-properties_root')})] #Set up lists links = [] titles = [] pictures = [] #create prefix for link prefix = "https://ah.nl" #scrape page for recipe for link in recipe_links: links.append(prefix + link.get('href')) for title in recipe_links: titles.append(title.get('aria-label')) for img in recipe_pictures: pictures.append(img.get('data-srcset')) page = page +1 #create random int to select a recipe nummer = random.randint(0,105) print(nummer) #select correct link … -
Limit Django filter query set by a N number of field
I think I cannot well express myself with words so I can put some code so you can understand me better I have a model class Obj(models.Model): foo = models.IntegerField() Then I have 8 objects where. obj1.foo = 1 obj2.foo = 1 obj3.foo = 1 obj4.foo = 2 obj5.foo = 2 obj6.foo = 2 obj7.foo = 3 obj8.foo = 3 With the query set objs = Obj.objects.all() obj = QuerySet[obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8] Then the query that I want is limit the obj by foo filtered_obj = QuerySet[ obj1, # foo=1 obj2, # foo=1 obj4, # foo=2 obj5, # foo=2 obj7, # foo=3 obj8. # foo=3 ] I don't want repeated fields more than 2 times. -
Verifying SendGrid's Signed Event Webhook in Django
I am trying to get signed from sengrid Webhook: https://docs.sendgrid.com/for-developers/tracking-events/getting-started-event-webhook-security-features from sendgrid.helpers.eventwebhook import EventWebhook, EventWebhookHeader def is_valid_signature(request): #event_webhook_signature=request.META['HTTP_X_TWILIO_EMAIL_EVENT_WEBHOOK_SIGNATURE'] #event_webhook_timestamp=request.META['HTTP_X_TWILIO_EMAIL_EVENT_WEBHOOK_TIMESTAMP'] event_webhook = EventWebhook() key=settings.SENDGRID_HEADER ec_public_key = event_webhook.convert_public_key_to_ecdsa(key) text=json.dumps(str(request.body)) return event_webhook.verify_signature( text, request.headers[EventWebhookHeader.SIGNATURE], request.headers[EventWebhookHeader.TIMESTAMP], ec_public_key ) When I send test example from sengrid, always return False. I compared keys and all is correct, so, I think that the problem is the sintax of the payload: "b[{\"email\":\"example@test.com\",\"timestamp\":1648560198,\"smtp-id\":\"\\\\u003c14c5d75ce93.dfd.64b469@ismtpd-555\\\\u003e\",\"event\":\"processed\",\"category\":[\"cat facts\"],\"sg_event_id\":\"G6NRn4zC5sGxoV2Hoz7gpw==\",\"sg_message_id\":\"14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0\"},{other tests},\\r\\n]\\r\\n" -
Django unspecified error when deploying on Apache2
Below is the error when I try deploy Django==3.2.12, wagtail==2.16.1, python 3.8.2, mod_wsgi 4.9 on a Debian 11 server. I have a full stack trace at the end. class SimpleLazyObject(LazyObject): TypeError: Error when calling the metaclass bases 'property' object is not callable When I run this on my local dev machine which is a Mac it works just fine. I found someone with the exact same problem but no clarity about how it was resolved. The resources I have been using to assist are 1, 2, 3, 4. I have tried installing mod_wsgi using pip and as well as from sources. Used various guides for Apache2 config. Upgraded from python 3.8 to 3.9 as well as downgraded to 3.7. Create interpreter '0.0.0.0|'. [Tue Mar 29 11:49:06.679710 2022] [wsgi:info] [pid 199764:tid 139683953432320] mod_wsgi (pid=199764): Adding '/var/www/html/portal' to path. [Tue Mar 29 11:49:06.680057 2022] [wsgi:info] [pid 199764:tid 139683953432320] mod_wsgi (pid=199764): Adding '/var/www/html/portal/portalvenv/lib/python3.8/site-packages' to path. [Tue Mar 29 11:49:06.689628 2022] [wsgi:info] [pid 199764:tid 139683953432320] [remote xx.xx.xx.xxx:yyyy] mod_wsgi (pid=199764, process='saida-befree_portal', application='0.0.0.0|'): Loading Python script file '/var/www/html/portal/portal/wsgi.py'. [Tue Mar 29 11:49:06.705081 2022] [wsgi:error] [pid 199764:tid 139683953432320] [remote xx.xx.xx.xxx:yyyy] mod_wsgi (pid=199764): Failed to exec Python script file '/var/www/html/portal/portal/wsgi.py'. [Tue Mar 29 11:49:06.713633 2022] [wsgi:error] [pid 199764:tid … -
how to configuring django redirect_uri domain name when use ms-identity-python-django-tutorial
I'm trying to integrate the sso in ms-identity-python-django-tutorial, the redirect_url I configured in the Azure portal is https://example.com/auth/redirect, but the redirect_url when django project is started locally The domain name has always been localhost, how do I configure it as example.com in my project -
how to round up float or int input values in python
How to round up number in python, i have tried but when the user enters value it becomes string type.user can enter Float or int value.after that data is need to round(). Here i am checking ENtered value is valid Int or Float, If yes i am asking for choice => roundof Then here i need to roundof and print output def isfloat(num): try: float(num) return True except ValueError: return False def swicthChoice(arg,val): if(arg=="roundOf"): data = int(val) print(round(data)) else: print("Enter Valid ") def ask_ip(): val = input("Enter your value: ") #float or int. res = isfloat(val) if(res): arg = input("Enter your Chioce: ") swicthChoice(arg,val) else: print("Invalid Input") ask_ip() ask_ip()