Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to generate Time based One Time Password(OTP) with Django
I am generating a random string as OTP using the following code - from django.utils.crypto import get_random_string otp = get_random_string(6, allowed_chars='0123456789') The problem with this is due to SMS delivery issues people request for a lot of OTPs and then when they arrive together they have no idea which one is currently valid. I want to generate a OTP that wouldn't change for 30 minutes and is unique for every phone number which would be something like +919999999999. -
How to limit the format of django-rest-framework-api uploading(post method)
In fact, I need your help to limit the my api to upload I only need Jason and excel formats(csv,xls,xlsl) on the server-side, but I did not find any code for that. The second question is, what methods should I use to authenticate the user? Here's a link that i use for my api I will thank you :) -
when a condition satisfied redirect to one page if failed redirect to another page using success url in class based views
when the if condition is valid then i want to redirect the page to success.html page and if not valid redirect to faild.html page.How can it possible using class based views. class LogView(FormView): form_class = LogForm template_name = 'log.html' success_url='failed' def get_success_url(self): if not self.success_url: raise ImproperlyConfigured("No URL to redirect to.Provide a success_url.") return str(self.success_url) def form_valid(self,form): cc='' nam1 = self.request.POST.get('nam') roll1 = self.request.POST.get('roll') obj=Register.objects.all() for i in obj: if str(i.name) == str(nam1) and str(i.rollno) == str(roll1): else: pass else: pass -
Django Migration ran without error, but database is not changed
I merged two tables into one on April 13, 2018. Migrations for 'caseAT': caseAT/migrations/0004_auto_20180413_1802.py - Remove field case_ptr from papoose - Add field lead to case - Add field neighbor1 to case - Add field neighbor2 to case - Add field page_to_paragraph to case - Add field pagerange_int_range to case - Add field paranum_array to case - Add field quills to case - Add field root to case - Delete model Papoose (aishah) malikarumi@Tetuoan2:~/Projects/aishah/jamf35$ git commit -m 'just adding the migration I just did for the streamlined/consolidated case papoose merge.' [post_repair_diff_and_align a3fbb69] just adding the migration I just did for the streamlined/consolidated case papoose merge. 1 file changed, 69 insertions(+) create mode 100644 caseAT/migrations/0004_auto_20180413_1802.py Then I took a break from this project to work on something else. Today, when I went back to this project, I got an error and looked to find that although my migration file and my models were as I expected them to be, the database was not. I ran showmigrations and this particular one, 0004_auto_20180413_1802.py, did not have a check in the box. I ran makemigrations and got "No changes detected" but when I ran runserver I got: You have 1 unapplied migration(s). Your project … -
Can't migrate Sqllite to mysql in django
i have successfully installed mysqlclient in my django project folder. prakash@prakash-Lenovo-ideapad-100-15IBY:~/projects/MasterQuote$ pip3 install mysqlclient Output : Collecting mysqlclient Installing collected packages: mysqlclient Successfully installed mysqlclient-1.3.12 But i try to migrate this error occured Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/home/prakash/.local/lib/python3.6/site-packages/MySQLdb/__init__.py", line 19, in <module> import _mysql ImportError: libmysqlclient.so.20: cannot open shared object file: No such file or directory The above exception was the direct cause of the following exception: Traceback (most recent call last): File "./manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/usr/local/lib/python3.6/dist-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/dist-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/usr/local/lib/python3.6/dist-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/usr/local/lib/python3.6/dist-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/usr/local/lib/python3.6/dist-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File … -
Salt: Using salt state in jinja if-else state
I'm trying to deploy a django project with saltstack. I wrote a sls file and It installs packages and run some commands. It installs django, nginx, etc and I want to run manage.py collectstatic for nginx. but when I re-apply this formula, It returns an error that /static directory is already exists. so I modified the sls file collect_static_files: {% if not salt['file.exists'][BASEDIR,'myproject/static']|join('') %} cmd.run: - name: '~~~ collectstatic;' - cwd: /path/to/venv/bin {% else %} cmd.run: - name: echo "Static directory exists." {% endif %} but when I run salt '*' state.apply myformula, It says: minion: Data failed to compile: ---------- Rendering SLS 'base:myproj' failed: Jinja variable 'salt.utils.templates.AliasedLoader object' has no attribute 'file.exists' How can I solve this problem? Thank you. -
Django ModelForm Not Saving into Database
I have been struggling for the past couple of days trying to get my forms to save into my database. As of right now it is creating the object in the database but all of the fields inside the object are empty. I'm trying to save data from a ModelForm into the model. Models.py class ContactForm(models.Model): Name = models.CharField(max_length= 50) Email = models.EmailField() Phone = models.CharField(max_length= 50) Message = models.CharField(max_length= 200) def __str__(self): return self.Name forms.py class ContactForm(ModelForm): name = forms.CharField(max_length=50) email = forms.EmailField(required=True) phone = forms.CharField(max_length=15) message = forms.CharField(max_length=50) class Meta: model = ContactForm fields = ['name','email','phone','message'] views.py def contact(request): if request.method=='POST': form = ContactForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: form = ContactForm() args = {'form': form} return render(request, 'home/contact.html', args) urls.py urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^about/$', views.about, name='about'), url(r'^buy-now/$', views.buyNow, name='buy-now'), url(r'^buy-form/$', views.buyForm, name='buy-form'), url(r'^contact/$', views.contact, name='contact'), url(r'^login/$', login, {'template_name': 'home/login.html'}, name='login'), url(r'^logout/$', logout, {'template_name': 'home/logout.html'}, name='logout'), url(r'^account/$', views.account, name='account'), url(r'^register/$', views.register, name='register'), ] template contact.html <form method ="post"> {% csrf_token %} {{ form }} <button type="submit" class="waves-effect waves-light btn-large">Submit</button> </form> Any help would be greatly appreciated. -
DestroyAPIView Django rest validation
class DeleteLedgerCategory(DestroyAPIView): serializer_class = CategorySerializer permission_classes = [IsAuthenticated] def get_queryset(self): queryset = Category.objects.filter(company = self.request.user.currently_activated_company, id=self.kwargs['pk']) return queryset def preform_destroy(self, instance): if instance.is_default == True: raise ValueError("Cannot delete default system category") return instance.delete() In above class based view. I need to add custom validation error message. ie. if instance.is_default == True: raise error... and only allow to delete the instance if no error encounters. If any unclear question. Do comment -
Django - How to change placeholder of form in views
How to change placeholder of form in views? def myview(request): form = MyForm() form.widget.attrs.placeholder = 'Replace placeholder value' -
Extracting Queryset with a Primary Key Matching a Form input in Django
I currently have a model which contains rfids and their correlating equipment. Model class RFID(models.Model): rf_id = models.CharField(max_length = 10,primary_key=True) equipment_number = models.CharField(max_length = 11, default=0) def __str__(self): return self.rf_id I want to incorporate a form that allows for rfid input. The data given can then match with the primary key of the model (rf_id) and save the results of the query as a variable. Form class RFID_Scan(forms.Form): rf_scan = forms.CharField() Views from .models import RFID from .forms import RFID_Scan def latest_rf_scans(request): template = loader.get_template('metrics/rfid.html') form = RFID_Scan() code = RFID.objects.get(rf_id=rf_scan) context = { 'latest_rf_scans' : latest_rf_scans, 'form' : form, 'code' : code, } return HttpResponse(template.render(context,request)) HTML {% extends "base.html" %} {% block content %} <h1>RFID Scan</h1> <form action="" method="POST"> {% csrf_token %} <table> {{ form }} </table> <input type="submit" value="Submit" /> </form> <h1>RFID Scan Results</h1> <table> <tr> <th>RF Identification Number</th><th>Equipment Number</th> </tr> <tr> <td>{{code.rf_id}}</td><td>{{code.equipment_number}}</td> </table> {% endblock %} I'm fairly new to this and I'm sure this is way off, but any feedback would be greatly appreciated! -
Migrate django mysqlite database to mysql in ubuntu
I tried to migrate django mysqlite database mysql database.but can't migrate sqlite to mysql. i tried all the solutions but no use. My code settings.py DATABSES = { 'default' :{ 'ENGINE' : 'django.db.backends.mysql', 'NAME' :'MasterQuote', 'USER' : 'root', 'PASSWORD' : 'root', 'HOST' : 'localhost', 'PORT' : '' } } Traceback (most recent call last): File "./manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/dist-packages/django/core/management/commands/migrate.py", line 79, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/loader.py", line 206, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/recorder.py", line 61, in applied_migrations if self.has_table(): File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/recorder.py", line 44, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/usr/local/lib/python3.6/dist-packages/django/db/backends/base/base.py", line 255, in cursor return self._cursor() File "/usr/local/lib/python3.6/dist-packages/django/db/backends/dummy/base.py", line 20, in complain raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. I tried all type of solution.I didn't add any data.my code was just initial stage anyone please help … -
override __str__(self) of a model from an imported app
I'm facing the following situation: I have a django project, which uses an outside app [App1]. Within App1, it has the following structure: abstract class 'Base': class Base(models.Model): """ Base model with boilerplate for all models. """ name = models.CharField(max_length=200, db_index=True) alternate_names = models.TextField(null=True, blank=True, default='') .............. .............. class Meta: abstract = True def __str__(self): display_name = getattr(self, 'display_name', None) if display_name: return display_name return self.name abstract class based on 'Base', called 'AbstractClassA': class AbstractClassA(Base): display_name = models.CharField(max_length=200) .... .... class Meta(Base.Meta): abstract = True def get_display_name(self): .... .... return .... The non abstract class class ClassA(AbstractClassA) Now, when I do a query in my view for this ClassA, for example: qs = ClassA.objects.filter(Q(name__icontains=query_term)....) return qs I feed this qs into another outside app (autocomplete), so that when I type in 'xxxx' on my web form, the form would give me suggestions on available matches in the DB, based on this qs. This all works great, the only thing is, the list of potential matches shown to me is the default representation of the ClassA objects, which I traced back to def __str__(self): display_name = getattr(self, 'display_name', None) if display_name: return display_name return self.name defined in the base abstract model … -
DJANGO MEDIA_URL returns to same page instead of showing image
There are lots of answer on how to upload media files, what are the correct configuration and how to serve it on our application. But my project seems to work nothing. The aim is simple: User uploads an image. Django displays it on. models.py class UploadImageModel(models.Model): image = models.FileField() title = models.CharField(max_length=100, null=True, blank=True) urls.py from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include("Image.urls")), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py from django.shortcuts import render from django.views import View from .forms import UploadImageModelForm from .models import UploadImageModel # Create your views here. class UploadImage(View): def get(self, request, *args, **kwargs): form = UploadImageModelForm() context = { "form":form, } return render(request, "index.html", context) def post(self, request, *args, **kwargs): form = UploadImageModelForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.title = str(instance.image) instance.save() context = { "form":form, "instance":instance, } return render(request, "index.html", context) index.html {% if instance.image %} <img src="{{instance.image.url}}" alt="Image"/> {% endif %} ERROR: After uploading an image named .jpg, if I visit, 127.0.0.1:8000/media/1.jpeg, browser does not displays image, instead it shows index.html page. SO how to serve this … -
Load Template outside Django Project Directory
I have a Django project that is going to use React as the frontend. The project structure is as follows: ProjectName/ ├── api/ │ └── otherapp1/ │ └── otherapp2/ │ └── api/ │ └── views.py (will contain the method for loading react page) │ └── settings.py │ └── manage.py └── frontend/ └── public/ └── index.html (react root page) How can I load the index.html page with Django so I can use django for authentication and cookie/session management? I can't figure out how to configure the template/template dirs properly since it's outside the root folder for the django part of the project. -
Obtaining value in views.py from template
I've got the following code within my html template: Template <div class="submitbutton"> <a href="{% url 'accounts:customerhomepage' %}" target="_blank" value="1"> <button> View Demo </button> </a> </div> I'd like to pass the value of 1 to the function in views.py that will render the page. Within the view, I've got the following code: Views.py demo = request.GET.get('value') print(demo) The printed result is 'None' rather than '1'. I'm not sure where my code is wrong. Thanks! -
VSCode Python Path Setup mac
Anaconda:1.8.3 VScode: 1.22.2 Mac: 10.13.4 Just upgraded to Anaconda 1.8.3 and now cannot access Django packages. from the conda python environment prompt I get: Last login: Sun Apr 29 19:21:31 on ttys001 /Users/bill/.anaconda/navigator/a.tool ; exit; Bills-iMac:~ bill$ /Users/bill/.anaconda/navigator/a.tool ; exit; Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 12:04:33) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> django.VERSION (2, 0, 2, 'final', 0) >>> So I know that Django is installed and can be imported from the terminal. From within the VSCode integrated terminal I get: Bills-iMac:Prov bill$ python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in <module> ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Bills-iMac:Prov bill$ Within the VSCode Settings my python.pythonPath hasn't changed - it is still: { "python.pythonPath": "/anaconda3/envs/py36" } Within the venv the path is: >>> import sys … -
HttpResponseRedirect not working for deletion and page redirect on button click
I am trying to delete a job at the click of a button and redirect to a different page. The deletion works but the redirection does not. My code is as follows: views.py: @login_required def delete_job(request): job_id = request.GET['Jobid'] job = Job.objects.get(pk=job_id) try: job.delete() #return render(request, 'main/communitypartner_dash.html', {'form':form,'job' : job}) #return redirect('user_dash') return HttpResponseRedirect('main/communitypartner_dash.html') #return HttpResponseRedirect(reverse('user_dash')) #jobs = user.jobs.all() #return render_to_response('main/communitypartner_dash.html') except Exception as e: return HttpResponse("deletion not successful") #return render(request, 'main/communitypartner_dash.html', {'form':form,'job' : job}) url.py: url(r'^job/job_delete/$', views.delete_job), html: <button type="button" class="btn btn-primary" onclick="doDelete()">Dissolve</button> <script> function doDelete(){ $.ajax({ url: '/job/job_delete/', data: { 'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(), 'Jobid': {{job.id}} }, dataType: 'json', complete: function (response) { // $('#status').html(response.responseText); }, error: function () { // $('#status').html('Bummer: there was an error!'); }, }); return false; } I tried all the ways that are commented out in the try section of views.py. Please help. Thanks -
Djanog extract field form html
I have a html page that returns data in a form. The forms is a multiple choice checkbox field with "name=states1". When I run print(vars(self)) in my forms.py I see that the data is there ['MD', 'WV', 'WY'] (see below) however, when I try to extract it with print(self.data['states1']) I just get 'WY' and print(len(self.data['states1'])) returns 2. {'instance': <AA: AAobject>, '_validate_unique': False, 'is_bound': True, 'data': <QueryDict: {'csrfmiddlewaretoken': ['AAAAA']: ['1'], 'states1': ['MD', 'WV', 'WY'], 'states': [''], 'price': ['2.00'], 'user': ['1', '1']}>, ... However, when I run import json print(json.dumps(self.data, indent=2)) I get the following output { "csrfmiddlewaretoken": "AAAAA", "roles": "1", "states1": "WY", "states": "", "price": "2.00", "user": "1" } The data is just gone. Why is my data being restricted to the last field, when I can clearly see it when looking at vars? -
How to display the label of the field that is validated in the serializers of django rest
How to display the label of the field that is validated in the serializers of django rest? The return json displays the error, however with the name of the field and not with the name of the Label. Thank you. inf_nome = serializers.CharField(label='Nome', max_length=255) doc_cpf = serializers.CharField(label='CPF', max_length=15) class Meta: model = Associado fields = ('inf_nome', 'doc_cpf') associado = AssociadoSerializer(data=request.data) if associado.is_valid(): return Response({'mansagem': 'Sucesso! Up'}, status=HTTP_200_OK) return JsonResponse(associado.errors) inf_nome:["Este campo é obrigatório."] doc_cpf:["Este campo é obrigatório."] -
Url in Django 2
I still don't understand very well how urls works in Django 1, so sometimes is hard to make to django 2. Someone could help me with how this would be in Django2? urlpatterns = [ url(r'^activate/(?P[0-9A-Za-z_-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'), ] -
Python Django display gregorian date
I have a function that extract data form an mssql db and display the data on a template. currently in my template i have a for loop in my template that loop through the results. i get all the result i wanted, however my date are still display in julian date but i want the dates to be display in gregorian date so that is understandable by the end users. in the template i have a for loop <th>date</th> <th></th> <th></th> {%for a in results%} <td>a.date_entered</td> <td></td> <td></td> {%endfor%} view.py def bydate_display(request): if "selectdate" in request.POST and "selectdate1" in request.POST and "selectaccount" in request.POST: selected_date = request.POST["selectdate"] selected_date1 = request.POST["selectdate1"] selected_acc = request.POST["selectaccount"] if selected_date==selected_date and selected_date1==selected_date1 and selected_acc==selected_acc: convert=datetime.datetime.strptime(selected_date, "%Y-%m-%d").toordinal() convert1=datetime.datetime.strptime(selected_date1, "%Y-%m-%d").toordinal() engine=create_engine('mssql+pymssql://username:password@servername /db') connection=engine.connect() metadata=MetaData() fund=Table('gltrxdet',metadata,autoload=True,autoload_with=engine) rate=Table('gltrx_all',metadata,autoload=True,autoload_with=engine) stmt=select([fund.columns.account_code,fund.columns.description,fund.columns.nat_balance,fund.columns.rate_type_home,rate.columns.date_applied,rate.columns.date_entered,fund.columns.journal_ctrl_num,rate.columns.journal_ctrl_num]) stmt=stmt.where(and_(rate.columns.journal_ctrl_num==fund.columns.journal_ctrl_num,fund.columns.account_code==selected_acc,rate.columns.date_entered.between(convert,convert1))) results=connection.execute(stmt).fetchall() return render(request,'bydatedisplay.html',locals()) -
django settings.py won't read env variable for unit tests
I have database environment variables specified for my django app: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.getenv("POSTGRES_NAME"), 'USER': os.getenv("POSTGRES_USER"), 'PASSWORD': os.getenv("POSTGRES_PW"), 'HOST': os.getenv("POSTGRES_HOST"), 'PORT': os.getenv("POSTGRES_PORT"), } } The variables successfully get read in when I run "python manage.py runserver", during the build on Circle CI, and also in its production environment. But I am not understanding why when I run unit tests they don't get read in. Thanks for the help! -
Can not get instance in current Serializer: Django Rest Framework
I'm is study DRT and faced with problem. I'm can not get instance fields in current serializer. I have model User and Profile, linked it by OnetoOne. I linked UserProfileSerializer with UserSerializer and first serializer is has fields: lat, long. But i can not get instance this fields, get only user object. How get instance fields: lat and long? Serializator class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('first_name',) class UserProfileSerializer(serializers.ModelSerializer): user = UpdateUserSerializer(many=True, required=False) lat = serializers.DecimalField(max_digits=None, decimal_places=None) long = serializers.DecimalField(max_digits=None, decimal_places=None) class Meta: model = Profile fields = ('lat', 'long', 'user',) def update(self, instance, validated_data): print(validated_data) #get user object -
Why doesn't the curly braces work for a Vue app within a Django template?
Basically, Im trying to integrate Vue with Django. I have the following template: <!DOCTYPE html> <html> <head> <title>Django Vue</title> </head> <body> {% verbatim %} <div id="components-demo"> <button-counter></button-counter> </div> {% endverbatim %} <!-- Vuejs --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <!-- App --> <script> // Define a new component called button-counter Vue.component('button-counter', { data: function () { return { count: 0 } }, template: ` <button v-on:click="count++">You clicked me {{ count }} times.</button> ` }); // App definition new Vue({ el: '#components-demo' }); </script> </body> </html> Everything is very simple, CDNs are used, not webpack. The component shows up, but the count does not. In other words, the curly braces are not functioning properly within my template. Why is that? I have the verbatim tag up and running. It looks like this: Any help? -
iOS + Django Database Login Function
I am really stuck and I need your help. I am working on my web and iOS application. I used also Django to save users to database. Login function is already working on my web (HTML) but I really don ´t know how to create function to iOS app (Swift). I would be really glad to you if you can help me. Please HELP ! Thank you so much.